Skip to content

Commit c283160

Browse files
authored
fix(security): answer malformed sign-in bodies with 400, trim provider error logs, 409 on reused desktop requests (#10471)
- auth before-hook narrows body.email to a string before lowercasing, so a non-string email reaches Better Auth's body validation (400) instead of throwing a TypeError (500); the signup MX check uses the same narrowed value - credential validators log at most 200 characters of an upstream error body, with control characters collapsed, through one helper shared by readProviderErrorSnippet and the JSON path in validators/http.ts - preparing a desktop source-connect request with an id already in use throws OrchestrationError('conflict') (409) instead of a plain Error (500); the original request is kept
1 parent d5a727d commit c283160

7 files changed

Lines changed: 55 additions & 10 deletions

File tree

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

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1154,7 +1154,9 @@ export const auth = betterAuth({
11541154

11551155
if (isSignIn || isSignUp) {
11561156
const accessControl = await getAccessControlConfig()
1157-
const requestEmail = ctx.body?.email?.toLowerCase()
1157+
// Better Auth validates the body after this hook; a non-string email falls through to its 400.
1158+
const requestEmail =
1159+
typeof ctx.body?.email === 'string' ? ctx.body.email.toLowerCase() : undefined
11581160

11591161
// Banning an existing account is owned by better-auth's admin plugin (a
11601162
// `session.create.before` hook that blocks banned users at sign-in across
@@ -1187,10 +1189,10 @@ export const auth = betterAuth({
11871189
if (
11881190
isSignupMxValidationEnabled &&
11891191
ctx.path.startsWith('/sign-up/email') &&
1190-
ctx.body?.email
1192+
requestEmail
11911193
) {
11921194
const mxCheck = await validateSignupEmailMx(
1193-
ctx.body.email,
1195+
requestEmail,
11941196
accessControl.blockedEmailMxHosts
11951197
)
11961198
if (!mxCheck.allowed) {

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

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -198,6 +198,13 @@ describe('authentication audit history in PostgreSQL', () => {
198198
expect((await history()).some((entry) => entry.action === 'auth.login_succeeded')).toBe(false)
199199
})
200200

201+
it('answers a non-string email with a validation error instead of crashing the sign-in hook', async () => {
202+
const response = await auth.handler(
203+
request('/sign-in/email', { email: { $ne: null }, password: fixturePassword })
204+
)
205+
expect(response.status).toBe(400)
206+
})
207+
201208
it('records suspended-account denial without claiming a successful login', async () => {
202209
await db.update(user).set({ suspendedAt: new Date() }).where(eq(user.id, userId))
203210
const response = await auth.handler(

‎apps/sim/lib/credentials/token-service-accounts/errors.test.ts‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -189,12 +189,18 @@ describe('token service-account error helpers', () => {
189189
})
190190

191191
describe('readProviderErrorSnippet', () => {
192-
it('truncates the body to 500 characters', async () => {
192+
it('collapses control characters so a provider body cannot forge log lines', async () => {
193+
const res = new Response('bad key\r\n{"level":"INFO"}\u0000end', { status: 401 })
194+
195+
await expect(readProviderErrorSnippet(res)).resolves.toBe('bad key {"level":"INFO"} end')
196+
})
197+
198+
it('truncates the body to 200 characters', async () => {
193199
const res = new Response('x'.repeat(2000), { status: 500 })
194200

195201
const snippet = await readProviderErrorSnippet(res)
196202

197-
expect(snippet).toBe(`${'x'.repeat(500)}...`)
203+
expect(snippet).toBe(`${'x'.repeat(200)}...`)
198204
})
199205

200206
it('stops reading an oversized error body instead of buffering all of it', async () => {

‎apps/sim/lib/credentials/token-service-accounts/errors.ts‎

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,17 @@ export class TokenServiceAccountValidationError extends Error {
8585
}
8686
}
8787

88-
const ERROR_SNIPPET_MAX_LENGTH = 500
88+
const ERROR_SNIPPET_MAX_LENGTH = 200
89+
const CONTROL_CHARACTERS_GLOBAL = /[\u0000-\u001f\u007f]+/g
90+
91+
/**
92+
* Bounds a provider error body for server logs. Validators reach hosts the user typed, so the
93+
* text is attacker-controlled: keep enough to diagnose a real provider failure, with control
94+
* characters collapsed so it cannot forge log structure.
95+
*/
96+
export function toProviderErrorLogSnippet(text: string): string {
97+
return truncate(text.replace(CONTROL_CHARACTERS_GLOBAL, ' '), ERROR_SNIPPET_MAX_LENGTH)
98+
}
8999

90100
/**
91101
* Narrows the optional `clientSecret` for the single-grant client-credential
@@ -290,7 +300,7 @@ export async function readProviderErrorSnippet(res: ProviderResponse): Promise<s
290300
maxBytes: DEFAULT_MAX_ERROR_BODY_BYTES,
291301
label: 'provider error response',
292302
})
293-
return truncate(text, ERROR_SNIPPET_MAX_LENGTH)
303+
return toProviderErrorLogSnippet(text)
294304
} catch {
295305
return ''
296306
}

‎apps/sim/lib/credentials/token-service-accounts/validators/http.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
import { truncate } from '@sim/utils/string'
21
import { EgressRefusedError } from '@/lib/core/network/transport.server'
32
import type { EgressProfile } from '@/lib/core/security/egress/profiles'
43
import {
@@ -14,6 +13,7 @@ import {
1413
providerFailureCode,
1514
TokenServiceAccountValidationError,
1615
throwForProviderResponse,
16+
toProviderErrorLogSnippet,
1717
} from '@/lib/credentials/token-service-accounts/errors'
1818
import type {
1919
TokenServiceAccountFields,
@@ -289,7 +289,7 @@ export function tokenCheckValidator(check: TokenCheck): TokenServiceAccountValid
289289
body:
290290
errorBody === unreadable || check.errorBodyEchoesToken
291291
? ''
292-
: truncate(JSON.stringify(errorBody) ?? '', 500),
292+
: toProviderErrorLogSnippet(JSON.stringify(errorBody) ?? ''),
293293
}
294294
)
295295
}

‎apps/sim/lib/desktop/application/source-requests.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,8 @@ export const createDesktopSourceRequest = defineAuthorizedCredentialUserUseCase(
4848
REQUEST_TTL_SECONDS,
4949
'NX'
5050
)
51-
if (saved !== 'OK') throw new Error('Could not prepare the connection request')
51+
if (saved !== 'OK')
52+
throw new OrchestrationError('conflict', 'This connection request was already prepared')
5253
return { requestId }
5354
},
5455
})

‎apps/sim/lib/desktop/source-request.integration.ts‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,25 @@ describe('desktop source request transport', () => {
6262
).rejects.toThrow('Connection request expired')
6363
})
6464

65+
it('refuses a reused request id as a conflict and keeps the original request', async () => {
66+
const principal = {
67+
kind: 'session' as const,
68+
userId: generateId(),
69+
sessionId: 'desktop-fixture',
70+
}
71+
const requestId = generateShortId(32)
72+
await createDesktopSourceRequest.execute({
73+
principal,
74+
input: { requestId, payload: '{"n":1}' },
75+
})
76+
await expect(
77+
createDesktopSourceRequest.execute({ principal, input: { requestId, payload: '{"n":2}' } })
78+
).rejects.toMatchObject({ code: 'conflict' })
79+
await expect(
80+
consumeDesktopSourceRequest.execute({ principal, input: { requestId } })
81+
).resolves.toEqual({ payload: '{"n":1}' })
82+
})
83+
6584
it('rejects non-session callers and oversized requests', async () => {
6685
await expect(
6786
createDesktopSourceRequest.execute({

0 commit comments

Comments
 (0)