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
8 changes: 5 additions & 3 deletions apps/sim/lib/auth/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1154,7 +1154,9 @@ export const auth = betterAuth({

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

// Banning an existing account is owned by better-auth's admin plugin (a
// `session.create.before` hook that blocks banned users at sign-in across
Expand Down Expand Up @@ -1187,10 +1189,10 @@ export const auth = betterAuth({
if (
isSignupMxValidationEnabled &&
ctx.path.startsWith('/sign-up/email') &&
ctx.body?.email
requestEmail
) {
const mxCheck = await validateSignupEmailMx(
ctx.body.email,
requestEmail,
accessControl.blockedEmailMxHosts
)
if (!mxCheck.allowed) {
Expand Down
7 changes: 7 additions & 0 deletions apps/sim/lib/auth/lifecycle-audit.integration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,13 @@ describe('authentication audit history in PostgreSQL', () => {
expect((await history()).some((entry) => entry.action === 'auth.login_succeeded')).toBe(false)
})

it('answers a non-string email with a validation error instead of crashing the sign-in hook', async () => {
const response = await auth.handler(
request('/sign-in/email', { email: { $ne: null }, password: fixturePassword })
)
expect(response.status).toBe(400)
})

it('records suspended-account denial without claiming a successful login', async () => {
await db.update(user).set({ suspendedAt: new Date() }).where(eq(user.id, userId))
const response = await auth.handler(
Expand Down
10 changes: 8 additions & 2 deletions apps/sim/lib/credentials/token-service-accounts/errors.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -189,12 +189,18 @@ describe('token service-account error helpers', () => {
})

describe('readProviderErrorSnippet', () => {
it('truncates the body to 500 characters', async () => {
it('collapses control characters so a provider body cannot forge log lines', async () => {
const res = new Response('bad key\r\n{"level":"INFO"}\u0000end', { status: 401 })

await expect(readProviderErrorSnippet(res)).resolves.toBe('bad key {"level":"INFO"} end')
})

it('truncates the body to 200 characters', async () => {
const res = new Response('x'.repeat(2000), { status: 500 })

const snippet = await readProviderErrorSnippet(res)

expect(snippet).toBe(`${'x'.repeat(500)}...`)
expect(snippet).toBe(`${'x'.repeat(200)}...`)
})

it('stops reading an oversized error body instead of buffering all of it', async () => {
Expand Down
14 changes: 12 additions & 2 deletions apps/sim/lib/credentials/token-service-accounts/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,17 @@ export class TokenServiceAccountValidationError extends Error {
}
}

const ERROR_SNIPPET_MAX_LENGTH = 500
const ERROR_SNIPPET_MAX_LENGTH = 200
const CONTROL_CHARACTERS_GLOBAL = /[\u0000-\u001f\u007f]+/g

/**
* Bounds a provider error body for server logs. Validators reach hosts the user typed, so the
* text is attacker-controlled: keep enough to diagnose a real provider failure, with control
* characters collapsed so it cannot forge log structure.
*/
export function toProviderErrorLogSnippet(text: string): string {
return truncate(text.replace(CONTROL_CHARACTERS_GLOBAL, ' '), ERROR_SNIPPET_MAX_LENGTH)
}

/**
* Narrows the optional `clientSecret` for the single-grant client-credential
Expand Down Expand Up @@ -290,7 +300,7 @@ export async function readProviderErrorSnippet(res: ProviderResponse): Promise<s
maxBytes: DEFAULT_MAX_ERROR_BODY_BYTES,
label: 'provider error response',
})
return truncate(text, ERROR_SNIPPET_MAX_LENGTH)
return toProviderErrorLogSnippet(text)
} catch {
return ''
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { truncate } from '@sim/utils/string'
import { EgressRefusedError } from '@/lib/core/network/transport.server'
import type { EgressProfile } from '@/lib/core/security/egress/profiles'
import {
Expand All @@ -14,6 +13,7 @@ import {
providerFailureCode,
TokenServiceAccountValidationError,
throwForProviderResponse,
toProviderErrorLogSnippet,
} from '@/lib/credentials/token-service-accounts/errors'
import type {
TokenServiceAccountFields,
Expand Down Expand Up @@ -289,7 +289,7 @@ export function tokenCheckValidator(check: TokenCheck): TokenServiceAccountValid
body:
errorBody === unreadable || check.errorBodyEchoesToken
? ''
: truncate(JSON.stringify(errorBody) ?? '', 500),
: toProviderErrorLogSnippet(JSON.stringify(errorBody) ?? ''),
}
)
}
Expand Down
3 changes: 2 additions & 1 deletion apps/sim/lib/desktop/application/source-requests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,8 @@ export const createDesktopSourceRequest = defineAuthorizedCredentialUserUseCase(
REQUEST_TTL_SECONDS,
'NX'
)
if (saved !== 'OK') throw new Error('Could not prepare the connection request')
if (saved !== 'OK')
throw new OrchestrationError('conflict', 'This connection request was already prepared')
return { requestId }
},
})
Expand Down
19 changes: 19 additions & 0 deletions apps/sim/lib/desktop/source-request.integration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,25 @@ describe('desktop source request transport', () => {
).rejects.toThrow('Connection request expired')
})

it('refuses a reused request id as a conflict and keeps the original request', async () => {
const principal = {
kind: 'session' as const,
userId: generateId(),
sessionId: 'desktop-fixture',
}
const requestId = generateShortId(32)
await createDesktopSourceRequest.execute({
principal,
input: { requestId, payload: '{"n":1}' },
})
await expect(
createDesktopSourceRequest.execute({ principal, input: { requestId, payload: '{"n":2}' } })
).rejects.toMatchObject({ code: 'conflict' })
await expect(
consumeDesktopSourceRequest.execute({ principal, input: { requestId } })
).resolves.toEqual({ payload: '{"n":1}' })
})

it('rejects non-session callers and oversized requests', async () => {
await expect(
createDesktopSourceRequest.execute({
Expand Down
Loading