diff --git a/.changeset/constant-time-webhook-signature.md b/.changeset/constant-time-webhook-signature.md new file mode 100644 index 00000000..35abb7bf --- /dev/null +++ b/.changeset/constant-time-webhook-signature.md @@ -0,0 +1,5 @@ +--- +'@fingerprint/node-sdk': patch +--- + +**webhooks**: `isValidWebhookSignature` compares signatures in constant time. diff --git a/src/webhook.ts b/src/webhook.ts index c3741353..2f1a45a1 100644 --- a/src/webhook.ts +++ b/src/webhook.ts @@ -1,7 +1,17 @@ import crypto from 'crypto' -function isValidHmacSignature(signature: string, data: Buffer, secret: string) { - return signature === crypto.createHmac('sha256', secret).update(data).digest('hex') +function isValidHmacSignature(signature: string | undefined, data: Buffer, secret: string) { + if (signature === undefined) { + return false + } + const received = Buffer.from(signature) + const expected = Buffer.from(crypto.createHmac('sha256', secret).update(data).digest('hex')) + // timingSafeEqual throws on buffers of different lengths. Compare byte lengths, not string + // lengths, because a multibyte character makes the buffer longer than the string. + if (received.length !== expected.length) { + return false + } + return crypto.timingSafeEqual(received, expected) } export interface IsValidWebhookSignatureParams { diff --git a/tests/unit-tests/webhookTests.spec.ts b/tests/unit-tests/webhookTests.spec.ts index 51c467b5..38067662 100644 --- a/tests/unit-tests/webhookTests.spec.ts +++ b/tests/unit-tests/webhookTests.spec.ts @@ -1,4 +1,5 @@ -import { describe, expect, it } from 'vitest' +import crypto from 'crypto' +import { describe, expect, it, vi } from 'vitest' import { isValidWebhookSignature } from '../../src' const secret = 'secret' @@ -30,4 +31,31 @@ describe('Is valid webhook signature', () => { it('with empty data', () => { expect(isValidWebhookSignature({ header: validHeader, data: Buffer.from(''), secret: secret })).toEqual(false) }) + + it('with valid signature after an invalid v1 signature', () => { + const header = `v1=invalid,${validHeader}` + expect(isValidWebhookSignature({ header, data, secret })).toEqual(true) + }) + + it('with truncated signature', () => { + const header = validHeader.slice(0, -1) + expect(isValidWebhookSignature({ header, data, secret })).toEqual(false) + }) + + it('with wrong signature of the same length, compared in constant time', () => { + const timingSafeEqual = vi.spyOn(crypto, 'timingSafeEqual') + const header = `v1=${'0'.repeat(64)}` + expect(isValidWebhookSignature({ header, data, secret })).toEqual(false) + expect(timingSafeEqual).toHaveBeenCalledOnce() + timingSafeEqual.mockRestore() + }) + + it('with v1 entry without a signature', () => { + expect(isValidWebhookSignature({ header: 'v1', data, secret })).toEqual(false) + }) + + it('with multibyte signature of the same string length', () => { + const header = `v1=${'é'.repeat(64)}` + expect(isValidWebhookSignature({ header, data, secret })).toEqual(false) + }) })