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