Skip to content

Commit 30afb73

Browse files
authored
fix(webhooks): reject auth that reads an unresolved env-var secret (#10055)
verifyProviderAuth resolved {{VAR}} references in the provider config with the keep-literal default and swallowed env-load failures, so a secret whose variable was missing or unreadable became its literal, guessable placeholder as the expected token or signing key. - env-load failure now returns 500 instead of continuing with an empty env - a delivery is rejected (401) when the handler's auth decision read a field whose reference did not resolve; free-text fields auth never reads (generic responseBody, TwiML) keep working with literal braces - env is read through resolveBackgroundWebhookEnv, matching execution's owner/billing-account identity split
1 parent 1450a88 commit 30afb73

2 files changed

Lines changed: 152 additions & 34 deletions

File tree

‎apps/sim/lib/webhooks/processor.test.ts‎

Lines changed: 86 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ import { idMock, idMockFns } from '@sim/testing/mocks/id.mock'
2424
import { createMockRedis } from '@sim/testing/mocks/redis.mock'
2525
import { redisConfigMockFns, resetRedisConfigMock } from '@sim/testing/mocks/redis-config.mock'
2626
import { NextRequest, NextResponse } from 'next/server'
27-
import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest'
27+
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
2828
import { ADMISSION_REJECTION_CODE } from '@/lib/core/admission/rejection'
2929
import {
3030
ADMISSION_ERROR_CODE,
@@ -38,11 +38,13 @@ type WebhookLookupRow = {
3838
workflow: Pick<WorkflowRecord, 'id'>
3939
}
4040

41-
const { mockEnqueue, mockExecuteWebhookJob, mockProviderHandler } = vi.hoisted(() => ({
42-
mockEnqueue: vi.fn(),
43-
mockExecuteWebhookJob: vi.fn().mockResolvedValue({ success: true }),
44-
mockProviderHandler: { current: {} as Record<string, unknown> },
45-
}))
41+
const { mockEnqueue, mockExecuteWebhookJob, mockProviderHandler, mockResolveBackgroundWebhookEnv } =
42+
vi.hoisted(() => ({
43+
mockEnqueue: vi.fn(),
44+
mockResolveBackgroundWebhookEnv: vi.fn(),
45+
mockExecuteWebhookJob: vi.fn().mockResolvedValue({ success: true }),
46+
mockProviderHandler: { current: {} as Record<string, unknown> },
47+
}))
4648

4749
const mockPreprocessExecution = executionPreprocessingMockFns.mockPreprocessExecution
4850

@@ -85,6 +87,10 @@ vi.mock('@/lib/webhooks/providers', () => ({
8587
getProviderHandler: vi.fn(() => mockProviderHandler.current),
8688
}))
8789

90+
vi.mock('@/lib/webhooks/env-resolver', () => ({
91+
resolveBackgroundWebhookEnv: mockResolveBackgroundWebhookEnv,
92+
}))
93+
8894
vi.mock('@/background/webhook-execution', () => ({
8995
executeWebhookJob: mockExecuteWebhookJob,
9096
}))
@@ -118,7 +124,9 @@ import {
118124
handleWebhookEventFilter,
119125
parseWebhookBody,
120126
processPolledWebhookEvent,
127+
verifyProviderAuth,
121128
} from '@/lib/webhooks/processor'
129+
import { resolveEnvVarReferences } from '@/executor/utils/reference-validation'
122130

123131
const mockGetInlineJobQueue = asyncJobsMockFns.mockGetInlineJobQueue
124132
const mockGetJobQueue = asyncJobsMockFns.mockGetJobQueue
@@ -795,3 +803,75 @@ describe('handleProviderChallenges method gating', () => {
795803
expect(handleChallenge).not.toHaveBeenCalled()
796804
})
797805
})
806+
807+
describe('verifyProviderAuth env-referenced secrets', () => {
808+
const PLACEHOLDER = '{{WEBHOOK_SECRET}}'
809+
810+
const verifyAuth = vi.fn(
811+
({ request, providerConfig }: { request: Request; providerConfig: Record<string, unknown> }) =>
812+
request.headers.get('authorization') === `Bearer ${providerConfig.token}`
813+
? null
814+
: new NextResponse('Unauthorized', { status: 401 })
815+
)
816+
817+
const deliver = (
818+
bearer: string,
819+
providerConfig: Record<string, unknown> = { token: PLACEHOLDER }
820+
) =>
821+
verifyProviderAuth(
822+
{ id: 'webhook-1', provider: 'generic', providerConfig } as never,
823+
{ id: 'workflow-1', userId: 'owner-1', workspaceId: 'workspace-1' } as never,
824+
new NextRequest('http://localhost:3000/api/webhooks/trigger/abc', {
825+
method: 'POST',
826+
headers: { authorization: `Bearer ${bearer}` },
827+
}),
828+
'{}',
829+
'req-1'
830+
)
831+
832+
beforeAll(async () => {
833+
const actual = await vi.importActual<typeof import('@/executor/utils/reference-validation')>(
834+
'@/executor/utils/reference-validation'
835+
)
836+
vi.mocked(resolveEnvVarReferences).mockImplementation(actual.resolveEnvVarReferences)
837+
})
838+
839+
afterAll(() => {
840+
vi.mocked(resolveEnvVarReferences).mockImplementation((value) => value)
841+
})
842+
843+
beforeEach(() => {
844+
verifyAuth.mockClear()
845+
mockResolveBackgroundWebhookEnv.mockReset()
846+
mockProviderHandler.current = { verifyAuth }
847+
})
848+
849+
it('authenticates with the resolved secret, read through the background webhook env', async () => {
850+
mockResolveBackgroundWebhookEnv.mockImplementation(async (userId, workspaceId) =>
851+
userId === 'owner-1' && workspaceId === 'workspace-1'
852+
? { WEBHOOK_SECRET: 'correct-horse' }
853+
: {}
854+
)
855+
856+
await expect(deliver('correct-horse')).resolves.toBeNull()
857+
})
858+
859+
it('rejects the literal placeholder when the referenced variable no longer exists', async () => {
860+
mockResolveBackgroundWebhookEnv.mockResolvedValue({})
861+
862+
expect((await deliver(PLACEHOLDER))?.status).toBe(401)
863+
})
864+
865+
it('ignores unresolved braces in a field auth never reads', async () => {
866+
mockResolveBackgroundWebhookEnv.mockResolvedValue({ WEBHOOK_SECRET: 'correct-horse' })
867+
868+
const providerConfig = { token: PLACEHOLDER, responseBody: '{"greeting": "{{name}}"}' }
869+
await expect(deliver('correct-horse', providerConfig)).resolves.toBeNull()
870+
})
871+
872+
it('rejects the literal placeholder when the env cannot be loaded', async () => {
873+
mockResolveBackgroundWebhookEnv.mockRejectedValue(new Error('Access denied to workspace'))
874+
875+
expect((await deliver(PLACEHOLDER))?.status).toBe(500)
876+
})
877+
})

‎apps/sim/lib/webhooks/processor.ts‎

Lines changed: 66 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -24,10 +24,10 @@ import {
2424
isPayloadSizeLimitError,
2525
readStreamToBufferWithLimit,
2626
} from '@/lib/core/utils/stream-limits'
27-
import { getEffectiveDecryptedEnv } from '@/lib/environment/utils'
2827
import { preprocessExecution } from '@/lib/execution/preprocessing'
2928
import { WEBHOOK_MAX_BODY_BYTES } from '@/lib/webhooks/constants'
3029
import { deliverableWebhookPredicate } from '@/lib/webhooks/delivery-predicate'
30+
import { resolveBackgroundWebhookEnv } from '@/lib/webhooks/env-resolver'
3131
import { createWebhookExecutionPrincipal } from '@/lib/webhooks/execution-principal'
3232
import {
3333
getPendingWebhookVerification,
@@ -530,10 +530,6 @@ export async function findWebhooksByRoutingKey(
530530
return results
531531
}
532532

533-
function resolveEnvVars(value: string, envVars: Record<string, string>): string {
534-
return resolveEnvVarReferences(value, envVars) as string
535-
}
536-
537533
/** True when any string value in the provider config contains an env-var reference (`{{VAR}}`). */
538534
function providerConfigReferencesEnvVars(config: Record<string, unknown>): boolean {
539535
for (const value of Object.values(config)) {
@@ -544,24 +540,46 @@ function providerConfigReferencesEnvVars(config: Record<string, unknown>): boole
544540
return false
545541
}
546542

547-
function resolveProviderConfigEnvVars(
543+
/**
544+
* Resolves the env-var references in the provider config's top-level string values for auth.
545+
*
546+
* A value whose reference has no variable keeps its literal `{{VAR}}` text and is exposed through
547+
* a getter that records the read in `unresolvedReads`. Fields auth never reads, like a response
548+
* body that legitimately contains braces, cannot affect the outcome; a handler that enumerates
549+
* the config reads every field, so it errs toward rejecting.
550+
*/
551+
function resolveAuthProviderConfig(
548552
config: Record<string, unknown>,
549553
envVars: Record<string, string>
550-
): Record<string, unknown> {
554+
): { config: Record<string, unknown>; unresolvedReads: Set<string> } {
551555
const resolved: Record<string, unknown> = {}
556+
const unresolvedReads = new Set<string>()
552557
for (const [key, value] of Object.entries(config)) {
553-
if (typeof value === 'string') {
554-
resolved[key] = resolveEnvVars(value, envVars)
555-
} else {
556-
resolved[key] = value
558+
const missingKeys: string[] = []
559+
const resolvedValue =
560+
typeof value === 'string' ? resolveEnvVarReferences(value, envVars, { missingKeys }) : value
561+
if (missingKeys.length === 0) {
562+
resolved[key] = resolvedValue
563+
continue
557564
}
565+
Object.defineProperty(resolved, key, {
566+
enumerable: true,
567+
get: () => {
568+
unresolvedReads.add(key)
569+
return resolvedValue
570+
},
571+
})
558572
}
559-
return resolved
573+
return { config: resolved, unresolvedReads }
560574
}
561575

562576
/**
563577
* Verify webhook provider authentication and signatures.
564578
* Delegates to the provider handler registry.
579+
*
580+
* Fails closed when the env vars the config references cannot be loaded, or when the handler's
581+
* decision read a field whose reference did not resolve: that field still holds its literal
582+
* `{{VAR}}` text, which would make a guessable placeholder the expected token or signing key.
565583
*/
566584
export async function verifyProviderAuth(
567585
foundWebhook: WebhookRecord,
@@ -575,37 +593,57 @@ export async function verifyProviderAuth(
575593
}
576594

577595
const handler = getProviderHandler(foundWebhook.provider)
596+
if (!handler.verifyAuth) return null
597+
578598
const rawProviderConfig = parseProviderConfig(foundWebhook.providerConfig)
579599

580600
/**
581-
* Only fetch + decrypt the effective env when there is auth to verify AND the
582-
* provider config actually references env vars (`{{VAR}}`). This avoids a DB
583-
* read and decryption on the synchronous pre-ack path for the common case.
601+
* Only fetch + decrypt the env when the provider config actually references env vars
602+
* (`{{VAR}}`). This avoids a DB read and decryption on the synchronous pre-ack path for the
603+
* common case.
584604
*/
585-
let decryptedEnvVars: Record<string, string> = {}
586-
if (handler.verifyAuth && providerConfigReferencesEnvVars(rawProviderConfig)) {
605+
let envVars: Record<string, string> = {}
606+
if (providerConfigReferencesEnvVars(rawProviderConfig)) {
587607
try {
588-
decryptedEnvVars = await getEffectiveDecryptedEnv(
608+
envVars = await resolveBackgroundWebhookEnv(
589609
foundWorkflow.userId,
590610
foundWorkflow.workspaceId ?? undefined
591611
)
592612
} catch (error) {
593-
logger.error('Failed to fetch environment variables', { requestId, error })
613+
logger.error('Failed to load environment variables for webhook auth', {
614+
requestId,
615+
webhookId: foundWebhook.id,
616+
error,
617+
})
618+
return NextResponse.json(
619+
{ error: 'Failed to verify webhook authentication' },
620+
{ status: 500 }
621+
)
594622
}
595623
}
596624

597-
const providerConfig = resolveProviderConfigEnvVars(rawProviderConfig, decryptedEnvVars)
625+
const { config: providerConfig, unresolvedReads } = resolveAuthProviderConfig(
626+
rawProviderConfig,
627+
envVars
628+
)
629+
630+
const authResult = await handler.verifyAuth({
631+
webhook: { ...foundWebhook },
632+
workflow: { ...foundWorkflow },
633+
request,
634+
rawBody,
635+
requestId,
636+
providerConfig,
637+
})
638+
if (authResult) return authResult
598639

599-
if (handler.verifyAuth) {
600-
const authResult = await handler.verifyAuth({
601-
webhook: { ...foundWebhook },
602-
workflow: { ...foundWorkflow },
603-
request,
604-
rawBody,
640+
if (unresolvedReads.size > 0) {
641+
logger.warn('Webhook auth rejected: it read config fields with unresolved env vars', {
605642
requestId,
606-
providerConfig,
643+
webhookId: foundWebhook.id,
644+
fields: [...unresolvedReads],
607645
})
608-
if (authResult) return authResult
646+
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
609647
}
610648

611649
return null

0 commit comments

Comments
 (0)