Skip to content

Commit 93b7597

Browse files
authored
fix(chat): stop email OTP verification from revealing the allow-list (#10498)
Every failed verification on the chat and public-file email gates now returns one 400, and both gates run the code check for every email so latency does not reveal membership either. Chat email auth answers otp_required for any email instead of rejecting unlisted ones.
1 parent e24dcc5 commit 93b7597

7 files changed

Lines changed: 75 additions & 75 deletions

File tree

‎apps/sim/app/api/chat/[identifier]/otp/route.integration.ts‎

Lines changed: 45 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ vi.mock('@/lib/core/config/redis', async (importOriginal) => ({
1717
getRedisClient: () => redisClient.current,
1818
}))
1919

20-
import { MAX_OTP_ATTEMPTS, storeOTP } from '@/lib/core/security/otp'
20+
import { MAX_OTP_ATTEMPTS, storeOTP, verifyOTP } from '@/lib/core/security/otp'
2121
import { PUT } from '@/app/api/chat/[identifier]/otp/route'
2222

2323
const redisUrl = readTestRedisUrl()
@@ -29,15 +29,14 @@ const identifier = `otp-${chatId}`
2929
const email = `${generateId()}@otp.invalid`
3030
const CODE = '246810'
3131
const NEWER_CODE = '135791'
32-
const NO_CODE = 'No verification code found, request a new one'
33-
const INVALID = 'Invalid verification code'
34-
const LOCKED = 'Too many failed attempts. Please request a new code.'
32+
const FAILED = 'Invalid or expired verification code'
33+
const REJECTED = { status: 400, error: FAILED, cookie: null }
3534

36-
async function verify(otp: string) {
35+
async function verify(otp: string, address = email) {
3736
const request = createMockRequest({
3837
method: 'PUT',
3938
url: `/api/chat/${identifier}/otp`,
40-
body: { email, otp },
39+
body: { email: address, otp },
4140
})
4241
const response = await PUT(request, createRouteContext({ identifier }))
4342
const body = (await response.json()) as { error?: string; message?: string }
@@ -111,39 +110,50 @@ describe('chat OTP verification', () => {
111110
.where(eq(chat.id, chatId))
112111
})
113112

114-
it.each([
115-
{
116-
rejection: 'the chat no longer uses email auth',
117-
change: { authType: 'public' },
118-
response: { status: 400, error: 'This chat does not use email authentication' },
119-
},
120-
{
121-
rejection: 'the email is no longer allowed',
122-
change: { allowedEmails: ['someone-else@otp.invalid'] },
123-
response: { status: 403, error: 'Email not authorized' },
124-
},
125-
])('rejects without spending the code when $rejection', async ({ change, response }) => {
126-
await db.update(chat).set(change).where(eq(chat.id, chatId))
113+
it('rejects without spending the code when the chat no longer uses email auth', async () => {
114+
await db.update(chat).set({ authType: 'public' }).where(eq(chat.id, chatId))
127115
for (let attempt = 0; attempt < MAX_OTP_ATTEMPTS; attempt++) {
128-
expect(await verify(CODE)).toMatchObject({ ...response, cookie: null })
116+
expect(await verify(CODE)).toMatchObject({
117+
status: 400,
118+
error: 'This chat does not use email authentication',
119+
cookie: null,
120+
})
129121
}
122+
await db.update(chat).set({ authType: 'email' }).where(eq(chat.id, chatId))
123+
expect(await verify(CODE)).toMatchObject({ status: 200 })
124+
})
125+
126+
it('spends but never accepts a correct code once the email leaves the allow-list', async () => {
130127
await db
131128
.update(chat)
132-
.set({ authType: 'email', allowedEmails: [email] })
129+
.set({ allowedEmails: ['someone-else@otp.invalid'] })
133130
.where(eq(chat.id, chatId))
134-
expect(await verify(CODE)).toMatchObject({ status: 200 })
131+
expect(await verify(CODE)).toMatchObject(REJECTED)
132+
await db
133+
.update(chat)
134+
.set({ allowedEmails: [email] })
135+
.where(eq(chat.id, chatId))
136+
expect(await verify(CODE)).toMatchObject(REJECTED)
135137
})
136138

137139
it('compares at most the attempt limit of guesses however many arrive concurrently', async () => {
138-
const results = await Promise.all(wrongGuesses(30).map(verify))
139-
140-
const compared = results.filter((result) => result.error !== NO_CODE)
141-
expect(compared).toHaveLength(MAX_OTP_ATTEMPTS)
142-
expect(compared.filter((result) => result.error === INVALID)).toHaveLength(
143-
MAX_OTP_ATTEMPTS - 1
140+
const results = await Promise.all(
141+
wrongGuesses(30).map((guess) => verifyOTP('chat', chatId, email, guess))
144142
)
145-
expect(compared.filter((result) => result.error === LOCKED)).toHaveLength(1)
146-
expect(await verify(CODE)).toMatchObject({ status: 400, error: NO_CODE, cookie: null })
143+
144+
expect(results.filter((result) => result === 'invalid')).toHaveLength(MAX_OTP_ATTEMPTS - 1)
145+
expect(results.filter((result) => result === 'locked')).toHaveLength(1)
146+
expect(await verify(CODE)).toMatchObject(REJECTED)
147+
})
148+
149+
it('answers an allow-listed email exactly like an unlisted one on every failure', async () => {
150+
const unlisted = `${generateId()}@elsewhere.invalid`
151+
const unlistedAnswer = await verify('000000', unlisted)
152+
153+
expect(unlistedAnswer).toEqual(REJECTED)
154+
for (const guess of wrongGuesses(MAX_OTP_ATTEMPTS + 1)) {
155+
expect(await verify(guess)).toEqual(unlistedAnswer)
156+
}
147157
})
148158

149159
it('lets only one of several concurrent correct submissions succeed', async () => {
@@ -167,31 +177,31 @@ describe('chat OTP verification', () => {
167177
return evaluate(...args)
168178
})
169179

170-
expect(await verify(CODE)).toMatchObject({ status: 400, error: NO_CODE, cookie: null })
180+
expect(await verify(CODE)).toMatchObject(REJECTED)
171181
expect(await verify(NEWER_CODE)).toMatchObject({ status: 200 })
172182
})
173183

174184
it('treats a code with no expiry as expired', async () => {
175185
const key = `otp:${email}:${chatId}`
176186
await redisClient.current?.set(key, `${CODE}:${MAX_OTP_ATTEMPTS - 1}`)
177-
expect(await verify(CODE)).toMatchObject({ status: 400, error: NO_CODE, cookie: null })
187+
expect(await verify(CODE)).toMatchObject(REJECTED)
178188
expect(await redisClient.current?.exists(key)).toBe(0)
179189
})
180190

181191
it('accepts the correct code on the last remaining attempt and mints the auth cookie', async () => {
182192
for (const guess of wrongGuesses(MAX_OTP_ATTEMPTS - 1)) {
183-
expect(await verify(guess)).toMatchObject({ status: 400, error: INVALID })
193+
expect(await verify(guess)).toMatchObject(REJECTED)
184194
}
185195
const accepted = await verify(CODE)
186196
expect(accepted.status).toBe(200)
187197
expect(accepted.cookie).toContain(`chat_auth_${chatId}=`)
188-
expect(await verify(CODE)).toMatchObject({ status: 400, error: NO_CODE })
198+
expect(await verify(CODE)).toMatchObject(REJECTED)
189199
})
190200

191201
it('keeps the code expiry when a failed attempt is recorded', async () => {
192202
const key = `otp:${email}:${chatId}`
193203
await redisClient.current?.pexpire(key, 900)
194-
expect(await verify('999999')).toMatchObject({ status: 400, error: INVALID })
204+
expect(await verify('999999')).toMatchObject(REJECTED)
195205
const ttl = await redisClient.current?.pttl(key)
196206
expect(ttl).toBeGreaterThan(0)
197207
expect(ttl).toBeLessThanOrEqual(900)

‎apps/sim/app/api/chat/[identifier]/otp/route.ts‎

Lines changed: 4 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import {
1414
OTP_EMAIL_RATE_LIMIT,
1515
OTP_IP_RATE_LIMIT,
1616
OTP_RESOURCE_RATE_LIMIT,
17+
OTP_VERIFICATION_FAILED,
1718
storeOTP,
1819
verifyOTP,
1920
} from '@/lib/core/security/otp'
@@ -188,20 +189,13 @@ export const PUT = withRouteHandler(
188189
if (deployment.authType !== 'email') {
189190
return createCodedErrorResponse('This chat does not use email authentication', 400)
190191
}
191-
if (!isEmailAllowed(email, deployment.allowedEmails)) {
192-
return createCodedErrorResponse('Email not authorized', 403)
193-
}
194-
192+
const allowed = isEmailAllowed(email, deployment.allowedEmails)
195193
const verification = await verifyOTP('chat', deployment.id, email, otp)
196-
if (verification === 'missing') {
197-
return createCodedErrorResponse('No verification code found, request a new one', 400)
198-
}
199194
if (verification === 'locked') {
200195
logger.warn('OTP invalidated after max failed attempts', { chatId: deployment.id })
201-
return createCodedErrorResponse('Too many failed attempts. Please request a new code.', 429)
202196
}
203-
if (verification === 'invalid') {
204-
return createCodedErrorResponse('Invalid verification code', 400)
197+
if (!allowed || verification !== 'valid') {
198+
return createCodedErrorResponse(OTP_VERIFICATION_FAILED, 400)
205199
}
206200

207201
const response = createSuccessResponse({

‎apps/sim/app/api/chat/utils.test.ts‎

Lines changed: 8 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -179,7 +179,7 @@ describe('Chat API Utils', () => {
179179
)
180180
})
181181

182-
it('should check allowed emails for email auth', async () => {
182+
it('answers allowed and unlisted emails alike so the allow-list stays private', async () => {
183183
const deployment = {
184184
id: 'chat-id',
185185
authType: 'email',
@@ -193,25 +193,14 @@ describe('Chat API Utils', () => {
193193
},
194194
} as any
195195

196-
mockIsEmailAllowed.mockReturnValue(true)
197-
const result1 = await validateChatAuth('request-id', deployment, mockRequest, {
198-
email: 'user@example.com',
199-
})
200-
expect(result1.authorized).toBe(false)
201-
expect(result1.error).toBe('otp_required')
202-
203-
const result2 = await validateChatAuth('request-id', deployment, mockRequest, {
204-
email: 'other@company.com',
205-
})
206-
expect(result2.authorized).toBe(false)
207-
expect(result2.error).toBe('otp_required')
196+
mockIsEmailAllowed.mockImplementation((address: string) => address !== 'user@unknown.com')
208197

209-
mockIsEmailAllowed.mockReturnValue(false)
210-
const result3 = await validateChatAuth('request-id', deployment, mockRequest, {
211-
email: 'user@unknown.com',
212-
})
213-
expect(result3.authorized).toBe(false)
214-
expect(result3.error).toBe('Email not authorized')
198+
for (const email of ['user@example.com', 'other@company.com', 'user@unknown.com']) {
199+
expect(await validateChatAuth('request-id', deployment, mockRequest, { email })).toEqual({
200+
authorized: false,
201+
error: 'otp_required',
202+
})
203+
}
215204
})
216205

217206
describe('SSO auth', () => {

‎apps/sim/lib/core/security/deployment-credentials.ts‎

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -194,11 +194,7 @@ export async function validateDeploymentCredentials(
194194
return { authorized: false, error: 'Email is required' }
195195
}
196196

197-
if (isEmailAllowed(email, resource.allowedEmails)) {
198-
return { authorized: false, error: 'otp_required' }
199-
}
200-
201-
return { authorized: false, error: 'Email not authorized' }
197+
return { authorized: false, error: 'otp_required' }
202198
} catch (error) {
203199
logger.error('Error validating email:', error, { requestId })
204200
return { authorized: false, error: 'Authentication error' }

‎apps/sim/lib/core/security/otp.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,14 @@ async function reserveOTPAttempt(
128128

129129
export type OTPVerification = 'valid' | 'invalid' | 'locked' | 'missing'
130130

131+
/**
132+
* The one answer an email-auth gate gives for every failed verification.
133+
* Allow-list misses and missing, wrong, or exhausted codes all share it, and
134+
* callers run {@link verifyOTP} for every email, so neither the response nor
135+
* its latency reveals whether an email is on the deployment's allow-list.
136+
*/
137+
export const OTP_VERIFICATION_FAILED = 'Invalid or expired verification code'
138+
131139
/**
132140
* Checks a submitted code and consumes it on a match. An attempt is reserved
133141
* before the comparison, so at most {@link MAX_OTP_ATTEMPTS} guesses are ever

‎apps/sim/lib/projects/files/__integration__/content-sharing.integration.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -580,7 +580,11 @@ describe('Public file shares against PostgreSQL and private storage', () => {
580580
return value?.split(':')[0]
581581
}
582582
expect(await storedCode('outsider@shared.invalid')).toBeUndefined()
583-
const failure = { authorized: false, status: 400, error: 'Invalid verification code' }
583+
const failure = {
584+
authorized: false,
585+
status: 400,
586+
error: 'Invalid or expired verification code',
587+
}
584588
expect(
585589
await verifyPublicFileShareOtp({
586590
token: share.token,

‎apps/sim/lib/public-shares/application/credentials.ts‎

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import {
77
generateOTP,
88
OTP_EMAIL_RATE_LIMIT,
99
OTP_RESOURCE_RATE_LIMIT,
10+
OTP_VERIFICATION_FAILED,
1011
storeOTP,
1112
verifyOTP,
1213
} from '@/lib/core/security/otp'
@@ -23,7 +24,7 @@ const SSO_RESOURCE_RATE_LIMIT: TokenBucketConfig = {
2324
refillRate: 100,
2425
refillIntervalMs: 15 * 60_000,
2526
}
26-
const OTP_FAILURE = { authorized: false as const, error: 'Invalid verification code', status: 400 }
27+
const OTP_FAILURE = { authorized: false as const, error: OTP_VERIFICATION_FAILED, status: 400 }
2728

2829
/** Exchanges a verified password for a cookie bound to the share's current password slot. */
2930
export async function authenticatePublicFileSharePassword({
@@ -105,13 +106,11 @@ export async function verifyPublicFileShareOtp({
105106
}) {
106107
const normalizedEmail = normalizeEmail(email)
107108
const challenge = await preparePublicFileShareChallenge(token, 'email')
109+
const verification = await verifyOTP('file', challenge.shareId, normalizedEmail, otp)
108110
const allowed = await challenge.withCurrentPolicy(({ share }) =>
109111
isEmailAllowed(normalizedEmail, share.allowedEmails)
110112
)
111-
if (!allowed) return OTP_FAILURE
112-
const verification = await verifyOTP('file', challenge.shareId, normalizedEmail, otp)
113-
await challenge.withCurrentPolicy(() => undefined)
114-
if (verification !== 'valid') return OTP_FAILURE
113+
if (!allowed || verification !== 'valid') return OTP_FAILURE
115114
const resource = await challenge.withCurrentPolicy(({ share }) => share)
116115
const cookie = await createDeploymentAuthCookie({
117116
cookiePrefix: 'file',

0 commit comments

Comments
 (0)