Skip to content

Commit 2442320

Browse files
authored
fix(sso): refuse SSO callback user writes outside the provider's verified domain (#10060)
* fix(sso): refuse SSO callback user writes outside the provider's verified domain * fix(sso): read the mailbox domain after the last @ when matching an SSO domain
1 parent fc9481b commit 2442320

7 files changed

Lines changed: 284 additions & 5 deletions

File tree

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

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,7 @@ import { clampExpiryForSession } from '@/lib/auth/session-policy'
7575
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'
78+
import { refuseSsoCallbackEmailOutsideProviderDomain } from '@/lib/auth/sso/callback-email-domain'
7879
import { resolveSsoCallbackProviderId } from '@/lib/auth/sso/callback-provider'
7980
import { configuredSsoPlugin } from '@/lib/auth/sso/plugin'
8081
import {
@@ -386,6 +387,7 @@ export const auth = betterAuth({
386387
throw new Error('Sign-ups from this email are not allowed.')
387388
}
388389
if (isHosted) await refuseDisposableAccountEmail(user.email, context?.path)
390+
await refuseSsoCallbackEmailOutsideProviderDomain(user.email, context)
389391
return { data: user }
390392
},
391393
after: async (user, context) => {
@@ -482,6 +484,10 @@ export const auth = betterAuth({
482484
},
483485
},
484486
update: {
487+
before: async (user, context) => {
488+
if (user.email) await refuseSsoCallbackEmailOutsideProviderDomain(user.email, context)
489+
return { data: user }
490+
},
485491
after: async (user) => {
486492
if (user.banned) {
487493
await disableUserResources(user.id)

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

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,12 @@ export const SSO_REQUIRED_ERROR_CODE = 'SSO_REQUIRED'
106106
export const SSO_REQUIRED_MESSAGE =
107107
'Your organization requires single sign-on. Sign in through your identity provider.'
108108

109+
/**
110+
* How an SSO sign-in refused before any session exists identifies itself in the callback's error
111+
* redirect, which the SSO sign-in page explains.
112+
*/
113+
export const SSO_PROVISIONING_FAILED_ERROR_CODE = 'sso_provisioning_failed'
114+
109115
/**
110116
* How an account creation refused for a disposable email domain identifies itself, so the OAuth
111117
* error page can name the way forward instead of telling the person to try again.

‎apps/sim/lib/auth/sso/application/admit-sso-user.ts‎

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ import {
1212
workspace,
1313
} from '@sim/db/schema'
1414
import { createLogger } from '@sim/logger'
15-
import { normalizeSSODomain } from '@sim/utils/sso-domain'
15+
import { isEmailInSSODomain } from '@sim/utils/sso-domain'
1616
import { normalizeEmail } from '@sim/utils/string'
1717
import { and, eq, gt, isNull, sql } from 'drizzle-orm'
1818
import { applySessionPolicyToNewMember } from '@/lib/auth/session-policy'
@@ -132,9 +132,7 @@ async function runAdmissionTransaction(
132132
if (!linkedAccount) {
133133
return { providerId, result: { kind: 'denied', reason: 'account-not-linked' } }
134134
}
135-
const userDomain = normalizeSSODomain(userRow.email)
136-
const providerDomain = normalizeSSODomain(provider.domain)
137-
if (!userDomain || !providerDomain || userDomain !== providerDomain) {
135+
if (!isEmailInSSODomain(userRow.email, provider.domain)) {
138136
return { providerId, result: { kind: 'denied', reason: 'domain-mismatch' } }
139137
}
140138

Lines changed: 177 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,177 @@
1+
import { createServer, type Server } from 'node:http'
2+
import type { AddressInfo } from 'node:net'
3+
import { db } from '@sim/db'
4+
import { account, ssoProvider, user } from '@sim/db/schema'
5+
import { emailMailerMock } from '@sim/testing/mocks/email-mailer.mock'
6+
import { emailTemplatesMock } from '@sim/testing/mocks/email-templates.mock'
7+
import { posthogServerMock } from '@sim/testing/mocks/posthog-server.mock'
8+
import { generateId } from '@sim/utils/id'
9+
import { eq, inArray } from 'drizzle-orm'
10+
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
11+
12+
vi.mock('@/lib/messaging/email/mailer', () => emailMailerMock)
13+
vi.mock('@/components/emails', () => emailTemplatesMock)
14+
vi.mock('@/lib/posthog/server', () => posthogServerMock)
15+
16+
const PROVIDER_DOMAIN = 'verified-tenant.test'
17+
18+
/**
19+
* Drives a real OIDC sign-in through Better Auth's SSO callback against PostgreSQL, with a local
20+
* IdP the tenant controls: whatever address its userinfo asserts is what the callback receives.
21+
*/
22+
describe('SSO callback user writes in PostgreSQL', () => {
23+
let auth: typeof import('@/lib/auth/auth').auth
24+
let idp: Server
25+
let idpOrigin: string
26+
let assertedEmail: string
27+
let assertedSubject: string
28+
let ownerId: string
29+
let providerId: string
30+
let createdEmails: string[]
31+
32+
beforeAll(async () => {
33+
idp = createServer((request, response) => {
34+
response.writeHead(200, { 'content-type': 'application/json' })
35+
if (request.url === '/token') {
36+
response.end(
37+
JSON.stringify({
38+
access_token: 'idp-access-token',
39+
token_type: 'Bearer',
40+
expires_in: 600,
41+
})
42+
)
43+
return
44+
}
45+
response.end(JSON.stringify({ sub: assertedSubject, email: assertedEmail, name: 'Asserted' }))
46+
})
47+
await new Promise<void>((resolve) => idp.listen(0, '127.0.0.1', resolve))
48+
idpOrigin = `http://127.0.0.1:${(idp.address() as AddressInfo).port}`
49+
vi.stubEnv('SSO_ENABLED', 'true')
50+
vi.stubEnv('TRUSTED_ORIGINS', idpOrigin)
51+
;({ auth } = await import('@/lib/auth/auth'))
52+
}, 90_000)
53+
54+
afterAll(async () => {
55+
vi.unstubAllEnvs()
56+
await new Promise((resolve) => idp.close(resolve))
57+
})
58+
59+
beforeEach(async () => {
60+
ownerId = generateId()
61+
providerId = `tenant-idp-${generateId()}`
62+
assertedSubject = generateId()
63+
createdEmails = []
64+
const now = new Date()
65+
await db.insert(user).values({
66+
id: ownerId,
67+
name: 'Tenant administrator',
68+
email: `${ownerId}@${PROVIDER_DOMAIN}`,
69+
emailVerified: true,
70+
createdAt: now,
71+
updatedAt: now,
72+
})
73+
})
74+
75+
afterEach(async () => {
76+
await db.delete(ssoProvider).where(eq(ssoProvider.providerId, providerId))
77+
await db.delete(user).where(eq(user.id, ownerId))
78+
if (createdEmails.length > 0) await db.delete(user).where(inArray(user.email, createdEmails))
79+
})
80+
81+
async function registerProvider(options: { overrideUserInfo?: boolean } = {}) {
82+
await db.insert(ssoProvider).values({
83+
id: generateId(),
84+
providerId,
85+
userId: ownerId,
86+
issuer: idpOrigin,
87+
domain: PROVIDER_DOMAIN,
88+
domainVerified: true,
89+
oidcConfig: JSON.stringify({
90+
issuer: idpOrigin,
91+
clientId: 'tenant-client',
92+
clientSecret: 'tenant-client-secret',
93+
authorizationEndpoint: `${idpOrigin}/authorize`,
94+
tokenEndpoint: `${idpOrigin}/token`,
95+
userInfoEndpoint: `${idpOrigin}/userinfo`,
96+
jwksEndpoint: `${idpOrigin}/jwks`,
97+
pkce: false,
98+
overrideUserInfo: options.overrideUserInfo ?? false,
99+
}),
100+
})
101+
}
102+
103+
/** Starts the sign-in, then returns from the IdP to the callback as the browser would. */
104+
async function signInAs(email: string) {
105+
assertedEmail = email
106+
createdEmails.push(email)
107+
const started = await auth.handler(
108+
new Request('http://localhost:3000/api/auth/sign-in/sso', {
109+
method: 'POST',
110+
headers: { 'content-type': 'application/json', origin: 'http://localhost:3000' },
111+
body: JSON.stringify({ providerId, callbackURL: '/workspace', errorCallbackURL: '/sso' }),
112+
})
113+
)
114+
expect(started.status).toBe(200)
115+
const { url } = (await started.json()) as { url: string }
116+
const state = new URL(url).searchParams.get('state') ?? ''
117+
expect(state).not.toBe('')
118+
const cookie = started.headers
119+
.getSetCookie()
120+
.map((value) => value.split(';')[0])
121+
.join('; ')
122+
const callback = new URL(`http://localhost:3000/api/auth/sso/callback/${providerId}`)
123+
callback.searchParams.set('code', 'authorization-code')
124+
callback.searchParams.set('state', state)
125+
return auth.handler(new Request(callback, { headers: { cookie } }))
126+
}
127+
128+
function redirectOf(response: Response) {
129+
expect(response.status).toBe(302)
130+
return new URL(response.headers.get('location') ?? '', 'http://localhost:3000')
131+
}
132+
133+
async function userByEmail(email: string) {
134+
const [row] = await db.select({ id: user.id }).from(user).where(eq(user.email, email))
135+
return row
136+
}
137+
138+
it('creates no user or account for an asserted address outside the verified domain', async () => {
139+
await registerProvider()
140+
const victim = `ceo-${generateId()}@unverified-victim.test`
141+
142+
const response = await signInAs(victim)
143+
144+
expect(redirectOf(response).searchParams.get('error')).toBe('sso_provisioning_failed')
145+
expect(await userByEmail(victim)).toBeUndefined()
146+
expect(
147+
await db.select({ id: account.id }).from(account).where(eq(account.providerId, providerId))
148+
).toHaveLength(0)
149+
})
150+
151+
it('still creates the user for an asserted address inside the verified domain', async () => {
152+
await registerProvider()
153+
const member = `member-${generateId()}@${PROVIDER_DOMAIN}`
154+
155+
const response = await signInAs(member)
156+
157+
const redirect = redirectOf(response)
158+
expect(redirect.pathname).toBe('/workspace')
159+
expect(redirect.searchParams.has('error')).toBe(false)
160+
expect(await userByEmail(member)).toBeDefined()
161+
})
162+
163+
it('keeps a linked user’s email when the IdP later asserts an address outside the domain', async () => {
164+
await registerProvider({ overrideUserInfo: true })
165+
const member = `member-${generateId()}@${PROVIDER_DOMAIN}`
166+
await signInAs(member)
167+
const linked = await userByEmail(member)
168+
expect(linked).toBeDefined()
169+
170+
const victim = `ceo-${generateId()}@unverified-victim.test`
171+
const response = await signInAs(victim)
172+
173+
expect(redirectOf(response).searchParams.get('error')).toBe('sso_provisioning_failed')
174+
expect(await userByEmail(member)).toEqual(linked)
175+
expect(await userByEmail(victim)).toBeUndefined()
176+
})
177+
})
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
import { createLogger } from '@sim/logger'
2+
import { isEmailInSSODomain } from '@sim/utils/sso-domain'
3+
import { type GenericEndpointContext, getCurrentAdapter } from 'better-auth'
4+
import { APIError, getOAuthState } from 'better-auth/api'
5+
import { SSO_PROVISIONING_FAILED_ERROR_CODE } from '@/lib/auth/constants'
6+
import { isSsoCallbackPath, resolveSsoCallbackProviderId } from '@/lib/auth/sso/callback-provider'
7+
8+
const logger = createLogger('SsoCallbackEmailDomain')
9+
10+
/**
11+
* Refuses writing a user email at an SSO callback unless the provider's domain is verified and the
12+
* address belongs to it.
13+
*
14+
* Better Auth checks the provider's domain only before linking to an existing account. It creates a
15+
* new user (and, with `overrideUserInfo`, rewrites a linked user's email) from whatever address the
16+
* IdP asserts. The admission after-hook refuses such a sign-in, but only once the row has already
17+
* been written, so the check has to run here, in the user write's `before` hook, to keep a tenant's
18+
* IdP from claiming addresses in domains it never proved.
19+
*
20+
* @param context - the Better Auth endpoint context the write runs under; writes outside an SSO
21+
* callback pass through untouched.
22+
*/
23+
export async function refuseSsoCallbackEmailOutsideProviderDomain(
24+
email: string,
25+
context: GenericEndpointContext | null
26+
): Promise<void> {
27+
if (!context || !isSsoCallbackPath(context.path)) return
28+
29+
const providerId = resolveSsoCallbackProviderId({
30+
path: context.path,
31+
routeProviderId: context.params?.providerId,
32+
stateProviderId:
33+
context.path === '/sso/callback' ? (await getOAuthState())?.ssoProviderId : undefined,
34+
})
35+
// The write runs inside Better Auth's transaction, so the lookup joins it through its adapter.
36+
const adapter = await getCurrentAdapter(context.context.adapter)
37+
const provider = providerId
38+
? await adapter.findOne<{ domain: string; domainVerified: boolean }>({
39+
model: 'ssoProvider',
40+
where: [{ field: 'providerId', value: providerId }],
41+
select: ['domain', 'domainVerified'],
42+
})
43+
: null
44+
45+
if (provider?.domainVerified && isEmailInSSODomain(email, provider.domain)) return
46+
47+
logger.warn('Refusing SSO user write for an email outside the provider domain', {
48+
providerId,
49+
path: context.path,
50+
providerFound: Boolean(provider),
51+
domainVerified: provider?.domainVerified ?? false,
52+
})
53+
// The callback redirects a refused creation with `message` and a refused update with `code`.
54+
throw new APIError('FORBIDDEN', {
55+
code: SSO_PROVISIONING_FAILED_ERROR_CODE,
56+
message: SSO_PROVISIONING_FAILED_ERROR_CODE,
57+
})
58+
}

‎packages/utils/src/sso-domain.test.ts‎

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { describe, expect, it } from 'vitest'
2-
import { normalizeSSODomain } from './sso-domain'
2+
import { isEmailInSSODomain, normalizeSSODomain } from './sso-domain'
33

44
describe('normalizeSSODomain', () => {
55
it('strips wildcard, leading @, and email local part', () => {
@@ -21,3 +21,22 @@ describe('normalizeSSODomain', () => {
2121
expect(normalizeSSODomain('company.123')).toBeNull()
2222
})
2323
})
24+
25+
describe('isEmailInSSODomain', () => {
26+
it('matches an address whose mailbox domain is the provider domain', () => {
27+
expect(isEmailInSSODomain('member@Company.com', 'company.com')).toBe(true)
28+
})
29+
30+
it('reads the mailbox domain after the last @, never a domain-shaped local part', () => {
31+
expect(isEmailInSSODomain('company.com/ceo@victim.test', 'company.com')).toBe(false)
32+
expect(isEmailInSSODomain('company.com?ceo@victim.test', 'company.com')).toBe(false)
33+
expect(isEmailInSSODomain('ceo@company.com?x@victim.test', 'company.com')).toBe(false)
34+
expect(isEmailInSSODomain('ceo@company.com:443@victim.test', 'company.com')).toBe(false)
35+
})
36+
37+
it('refuses a mailbox domain carrying anything but domain characters', () => {
38+
expect(isEmailInSSODomain('ceo@company.com/x', 'company.com')).toBe(false)
39+
expect(isEmailInSSODomain('ceo@company.com:443', 'company.com')).toBe(false)
40+
expect(isEmailInSSODomain('company.com', 'company.com')).toBe(false)
41+
})
42+
})

‎packages/utils/src/sso-domain.ts‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,3 +31,18 @@ export function normalizeSSODomain(input: string): string | null {
3131

3232
return value
3333
}
34+
35+
/**
36+
* Whether an email address belongs to an SSO provider's domain, compared on the
37+
* same canonical form {@link normalizeSSODomain} keys domain ownership on. The
38+
* mailbox domain is the text after the last `@` and must hold only domain
39+
* characters: {@link normalizeSSODomain} strips URL syntax first, so handing it
40+
* the whole address would read `company.com/ceo@victim.test` as `company.com`.
41+
*/
42+
export function isEmailInSSODomain(email: string, domain: string): boolean {
43+
const at = email.lastIndexOf('@')
44+
const mailboxDomain = at > 0 ? email.slice(at + 1) : ''
45+
if (!/^[a-z0-9.-]+$/i.test(mailboxDomain)) return false
46+
const emailDomain = normalizeSSODomain(mailboxDomain)
47+
return emailDomain !== null && emailDomain === normalizeSSODomain(domain)
48+
}

0 commit comments

Comments
 (0)