|
| 1 | +/** |
| 2 | + * @file webhookDispatcher.test.js |
| 3 | + * @description Integration test suite for the OpenSign Enterprise Webhook Dispatcher. |
| 4 | + * Tests are written using Jest with ESM module support. |
| 5 | + * Run with: node --experimental-vm-modules node_modules/.bin/jest webhookDispatcher.test.js |
| 6 | + */ |
| 7 | + |
| 8 | +import { jest } from '@jest/globals'; |
| 9 | +import { generateSignature, dispatchWithBackoff } from './webhookDispatcher.js'; |
| 10 | + |
| 11 | +// ─── Mock axios at the module level ─────────────────────────────────────────── |
| 12 | +jest.mock('axios', () => ({ |
| 13 | + default: { |
| 14 | + post: jest.fn(), |
| 15 | + }, |
| 16 | +})); |
| 17 | + |
| 18 | +import axios from 'axios'; |
| 19 | +const mockPost = /** @type {jest.MockedFunction<typeof axios.post>} */ (axios.post); |
| 20 | + |
| 21 | +// ─── Shared Test Fixtures ────────────────────────────────────────────────────── |
| 22 | +const MOCK_SECRET = 'os_secret_test_123'; |
| 23 | +const MOCK_URL = 'https://client-endpoint.example.com/webhook'; |
| 24 | + |
| 25 | +/** @type {import('./webhookDispatcher.js').WebhookPayload} */ |
| 26 | +const MOCK_PAYLOAD = { |
| 27 | + eventId: 'evt_abc123', |
| 28 | + event: 'document.signed', |
| 29 | + documentId: 'doc_999', |
| 30 | + status: 'COMPLETED', |
| 31 | + timestamp: '2026-04-17T00:00:00.000Z', |
| 32 | + data: { signerEmail: 'john@example.com' }, |
| 33 | +}; |
| 34 | + |
| 35 | +// ─── Helper to create an Axios-like error ──────────────────────────────────── |
| 36 | +function axiosError(status, message = 'Request failed') { |
| 37 | + return Object.assign(new Error(message), { |
| 38 | + isAxiosError: true, |
| 39 | + message, |
| 40 | + response: status ? { status } : undefined, |
| 41 | + }); |
| 42 | +} |
| 43 | + |
| 44 | +// ─── Test Suite ─────────────────────────────────────────────────────────────── |
| 45 | +describe('webhookDispatcher', () => { |
| 46 | + beforeEach(() => { |
| 47 | + jest.clearAllMocks(); |
| 48 | + jest.useFakeTimers(); |
| 49 | + }); |
| 50 | + |
| 51 | + afterEach(() => { |
| 52 | + jest.useRealTimers(); |
| 53 | + }); |
| 54 | + |
| 55 | + // ─── 1. HMAC Signature Integrity ──────────────────────────────────────── |
| 56 | + describe('generateSignature', () => { |
| 57 | + it('produces a 64-character hexadecimal SHA-256 HMAC digest', () => { |
| 58 | + const sig = generateSignature('test-payload', MOCK_SECRET); |
| 59 | + expect(sig).toHaveLength(64); |
| 60 | + expect(sig).toMatch(/^[a-f0-9]{64}$/); |
| 61 | + }); |
| 62 | + |
| 63 | + it('is deterministic — same input always produces the same signature', () => { |
| 64 | + const sig1 = generateSignature('payload', MOCK_SECRET); |
| 65 | + const sig2 = generateSignature('payload', MOCK_SECRET); |
| 66 | + expect(sig1).toBe(sig2); |
| 67 | + }); |
| 68 | + |
| 69 | + it('produces distinct signatures for different secrets', () => { |
| 70 | + const sig1 = generateSignature('payload', 'secret-A'); |
| 71 | + const sig2 = generateSignature('payload', 'secret-B'); |
| 72 | + expect(sig1).not.toBe(sig2); |
| 73 | + }); |
| 74 | + |
| 75 | + it('produces distinct signatures for different payloads', () => { |
| 76 | + const sig1 = generateSignature('payload-A', MOCK_SECRET); |
| 77 | + const sig2 = generateSignature('payload-B', MOCK_SECRET); |
| 78 | + expect(sig1).not.toBe(sig2); |
| 79 | + }); |
| 80 | + }); |
| 81 | + |
| 82 | + // ─── 2. Successful First-Attempt Delivery ──────────────────────────────── |
| 83 | + describe('dispatchWithBackoff — successful delivery', () => { |
| 84 | + it('delivers webhook successfully on first attempt', async () => { |
| 85 | + mockPost.mockResolvedValueOnce({ status: 200 }); |
| 86 | + |
| 87 | + const result = await dispatchWithBackoff(MOCK_URL, MOCK_PAYLOAD, MOCK_SECRET); |
| 88 | + |
| 89 | + expect(result.success).toBe(true); |
| 90 | + expect(result.attempts).toBe(1); |
| 91 | + expect(result.statusCode).toBe(200); |
| 92 | + expect(result.isRetryable).toBe(false); |
| 93 | + expect(mockPost).toHaveBeenCalledTimes(1); |
| 94 | + }); |
| 95 | + |
| 96 | + it('sends the correct headers including HMAC signature and idempotency key', async () => { |
| 97 | + mockPost.mockResolvedValueOnce({ status: 200 }); |
| 98 | + |
| 99 | + await dispatchWithBackoff(MOCK_URL, MOCK_PAYLOAD, MOCK_SECRET); |
| 100 | + |
| 101 | + expect(mockPost).toHaveBeenCalledWith( |
| 102 | + MOCK_URL, |
| 103 | + JSON.stringify(MOCK_PAYLOAD), |
| 104 | + expect.objectContaining({ |
| 105 | + headers: expect.objectContaining({ |
| 106 | + 'Content-Type': 'application/json', |
| 107 | + 'X-OpenSign-Signature': expect.stringMatching(/^[a-f0-9]{64}$/), |
| 108 | + 'X-OpenSign-Event': 'document.signed', |
| 109 | + 'Idempotency-Key': 'os_evt_evt_abc123_attempt_1', |
| 110 | + 'X-OpenSign-Delivery-Attempt': '1', |
| 111 | + }), |
| 112 | + }) |
| 113 | + ); |
| 114 | + }); |
| 115 | + |
| 116 | + it('the outgoing signature matches a locally computed HMAC', async () => { |
| 117 | + mockPost.mockResolvedValueOnce({ status: 200 }); |
| 118 | + await dispatchWithBackoff(MOCK_URL, MOCK_PAYLOAD, MOCK_SECRET); |
| 119 | + |
| 120 | + const [[, , callOptions]] = mockPost.mock.calls; |
| 121 | + const outgoingSignature = callOptions.headers['X-OpenSign-Signature']; |
| 122 | + const expectedSignature = generateSignature(JSON.stringify(MOCK_PAYLOAD), MOCK_SECRET); |
| 123 | + |
| 124 | + expect(outgoingSignature).toBe(expectedSignature); |
| 125 | + }); |
| 126 | + }); |
| 127 | + |
| 128 | + // ─── 3. Smart Retry on 5xx Server Error ────────────────────────────────── |
| 129 | + describe('dispatchWithBackoff — smart retries', () => { |
| 130 | + it('retries on HTTP 500 and succeeds on second attempt', async () => { |
| 131 | + mockPost |
| 132 | + .mockRejectedValueOnce(axiosError(500, 'Internal Server Error')) |
| 133 | + .mockResolvedValueOnce({ status: 200 }); |
| 134 | + |
| 135 | + const promise = dispatchWithBackoff(MOCK_URL, MOCK_PAYLOAD, MOCK_SECRET); |
| 136 | + await jest.runAllTimersAsync(); |
| 137 | + const result = await promise; |
| 138 | + |
| 139 | + expect(result.success).toBe(true); |
| 140 | + expect(result.attempts).toBe(2); |
| 141 | + expect(mockPost).toHaveBeenCalledTimes(2); |
| 142 | + }); |
| 143 | + |
| 144 | + it('retries on network timeout (no response status)', async () => { |
| 145 | + mockPost |
| 146 | + .mockRejectedValueOnce(axiosError(undefined, 'timeout of 5000ms exceeded')) |
| 147 | + .mockResolvedValueOnce({ status: 200 }); |
| 148 | + |
| 149 | + const promise = dispatchWithBackoff(MOCK_URL, MOCK_PAYLOAD, MOCK_SECRET); |
| 150 | + await jest.runAllTimersAsync(); |
| 151 | + const result = await promise; |
| 152 | + |
| 153 | + expect(result.success).toBe(true); |
| 154 | + expect(result.attempts).toBe(2); |
| 155 | + }); |
| 156 | + |
| 157 | + it('retries on HTTP 429 Too Many Requests (rate-limited, not a permanent client error)', async () => { |
| 158 | + mockPost |
| 159 | + .mockRejectedValueOnce(axiosError(429, 'Too Many Requests')) |
| 160 | + .mockResolvedValueOnce({ status: 200 }); |
| 161 | + |
| 162 | + const promise = dispatchWithBackoff(MOCK_URL, MOCK_PAYLOAD, MOCK_SECRET); |
| 163 | + await jest.runAllTimersAsync(); |
| 164 | + const result = await promise; |
| 165 | + |
| 166 | + expect(result.success).toBe(true); |
| 167 | + expect(result.attempts).toBe(2); |
| 168 | + }); |
| 169 | + }); |
| 170 | + |
| 171 | + // ─── 4. Non-Retryable 4xx Error Blocking ───────────────────────────────── |
| 172 | + describe('dispatchWithBackoff — non-retryable errors', () => { |
| 173 | + it.each([400, 401, 403, 404, 422])( |
| 174 | + 'does NOT retry on HTTP %i (client error)', |
| 175 | + async (status) => { |
| 176 | + mockPost.mockRejectedValueOnce(axiosError(status)); |
| 177 | + |
| 178 | + const result = await dispatchWithBackoff(MOCK_URL, MOCK_PAYLOAD, MOCK_SECRET); |
| 179 | + |
| 180 | + expect(result.success).toBe(false); |
| 181 | + expect(result.attempts).toBe(1); |
| 182 | + expect(result.isRetryable).toBe(false); |
| 183 | + expect(mockPost).toHaveBeenCalledTimes(1); |
| 184 | + } |
| 185 | + ); |
| 186 | + }); |
| 187 | + |
| 188 | + // ─── 5. Permanent Failure After MAX_RETRIES ─────────────────────────────── |
| 189 | + describe('dispatchWithBackoff — exhaustion', () => { |
| 190 | + it('fails permanently after 3 consecutive 503 errors (MAX_RETRIES)', async () => { |
| 191 | + mockPost.mockRejectedValue(axiosError(503, 'Service Unavailable')); |
| 192 | + |
| 193 | + const promise = dispatchWithBackoff(MOCK_URL, MOCK_PAYLOAD, MOCK_SECRET); |
| 194 | + await jest.runAllTimersAsync(); |
| 195 | + await jest.runAllTimersAsync(); |
| 196 | + const result = await promise; |
| 197 | + |
| 198 | + expect(result.success).toBe(false); |
| 199 | + expect(result.attempts).toBe(3); |
| 200 | + expect(result.isRetryable).toBe(true); |
| 201 | + expect(mockPost).toHaveBeenCalledTimes(3); |
| 202 | + }); |
| 203 | + }); |
| 204 | + |
| 205 | + // ─── 6. Idempotency Key Increment ──────────────────────────────────────── |
| 206 | + describe('dispatchWithBackoff — idempotency', () => { |
| 207 | + it('increments the idempotency key suffix with each retry attempt', async () => { |
| 208 | + mockPost.mockRejectedValue(axiosError(504, 'Gateway Timeout')); |
| 209 | + |
| 210 | + const promise = dispatchWithBackoff(MOCK_URL, MOCK_PAYLOAD, MOCK_SECRET); |
| 211 | + await jest.runAllTimersAsync(); |
| 212 | + await jest.runAllTimersAsync(); |
| 213 | + await promise; |
| 214 | + |
| 215 | + expect(mockPost).toHaveBeenNthCalledWith( |
| 216 | + 1, |
| 217 | + expect.any(String), |
| 218 | + expect.any(String), |
| 219 | + expect.objectContaining({ |
| 220 | + headers: expect.objectContaining({ 'Idempotency-Key': 'os_evt_evt_abc123_attempt_1' }), |
| 221 | + }) |
| 222 | + ); |
| 223 | + expect(mockPost).toHaveBeenNthCalledWith( |
| 224 | + 2, |
| 225 | + expect.any(String), |
| 226 | + expect.any(String), |
| 227 | + expect.objectContaining({ |
| 228 | + headers: expect.objectContaining({ 'Idempotency-Key': 'os_evt_evt_abc123_attempt_2' }), |
| 229 | + }) |
| 230 | + ); |
| 231 | + expect(mockPost).toHaveBeenNthCalledWith( |
| 232 | + 3, |
| 233 | + expect.any(String), |
| 234 | + expect.any(String), |
| 235 | + expect.objectContaining({ |
| 236 | + headers: expect.objectContaining({ 'Idempotency-Key': 'os_evt_evt_abc123_attempt_3' }), |
| 237 | + }) |
| 238 | + ); |
| 239 | + }); |
| 240 | + }); |
| 241 | +}); |
0 commit comments