-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathtest-webhook-hmac.js
More file actions
292 lines (253 loc) · 8.76 KB
/
test-webhook-hmac.js
File metadata and controls
292 lines (253 loc) · 8.76 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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
/**
* test-webhook-hmac.js
*
* Test suite for HMAC signature verification on webhook endpoints.
*
* Run with: node test-webhook-hmac.js
*
* Prerequisites:
* - Server running on localhost:3000
* - WEBHOOK_SECRET environment variable set
* - ADMIN_API_KEY environment variable set for JWT
*/
const http = require('http');
const crypto = require('crypto');
// Configuration
const WEBHOOK_SECRET = process.env.WEBHOOK_SECRET || 'your_webhook_secret_key_change_me';
const SERVER_HOST = 'localhost';
const SERVER_PORT = 3000;
const WEBHOOK_PATH = '/api/v1/webhook/soroban';
// Sample event payload
const eventPayload = {
eventId: 'evt_123456789',
type: 'swap',
contractId: 'CAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABSC4',
timestamp: new Date().toISOString(),
data: {
pool: 'POOL_ABC123',
amountIn: '1000',
amountOut: '950',
trader: 'TRADER_XYZ789'
}
};
/**
* Generate HMAC-SHA256 signature for a payload
* @param {string} payload - Raw request body as string
* @param {string} secret - WEBHOOK_SECRET key
* @returns {string} - Hex-encoded HMAC signature
*/
function generateSignature(payload, secret) {
return crypto
.createHmac('sha256', secret)
.update(payload)
.digest('hex');
}
/**
* Make HTTP request with HMAC signature verification
* @param {Object} options - Request configuration
* @returns {Promise} - Resolves with response data
*/
function makeRequest(options) {
return new Promise((resolve, reject) => {
const req = http.request(options, (res) => {
let data = '';
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
resolve({
statusCode: res.statusCode,
headers: res.headers,
body: data,
parsedBody: (() => {
try {
return JSON.parse(data);
} catch {
return null;
}
})()
});
});
});
req.on('error', reject);
if (options.body) {
req.write(options.body);
}
req.end();
});
}
/**
* Test Case 1: Valid signature - Should succeed (200)
*/
async function testValidSignature() {
console.log('\n' + '='.repeat(60));
console.log('TEST 1: Valid HMAC Signature');
console.log('='.repeat(60));
const payload = JSON.stringify(eventPayload);
const signature = generateSignature(payload, WEBHOOK_SECRET);
console.log(`✓ Generated signature: ${signature.substring(0, 16)}...`);
console.log(`✓ Payload size: ${payload.length} bytes`);
const requestOptions = {
hostname: SERVER_HOST,
port: SERVER_PORT,
path: WEBHOOK_PATH,
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-signature': signature,
'Authorization': 'Bearer valid-jwt-token',
'Content-Length': Buffer.byteLength(payload)
},
body: payload
};
try {
const response = await makeRequest(requestOptions);
console.log(`\n✓ Status: ${response.statusCode}`);
console.log(`✓ Response: ${JSON.stringify(response.parsedBody, null, 2)}`);
if (response.statusCode === 200) {
console.log('\n✅ TEST PASSED: Valid signature accepted');
} else {
console.log('\n❌ TEST FAILED: Expected 200, got ' + response.statusCode);
}
} catch (error) {
console.error('❌ TEST FAILED:', error.message);
}
}
/**
* Test Case 2: Invalid signature - Should fail (401)
*/
async function testInvalidSignature() {
console.log('\n' + '='.repeat(60));
console.log('TEST 2: Invalid HMAC Signature');
console.log('='.repeat(60));
const payload = JSON.stringify(eventPayload);
const invalidSignature = 'invalid_signature_1234567890abcdef1234567890abcdef1234567890ab';
console.log(`✓ Using invalid signature: ${invalidSignature}`);
console.log(`✓ Payload size: ${payload.length} bytes`);
const requestOptions = {
hostname: SERVER_HOST,
port: SERVER_PORT,
path: WEBHOOK_PATH,
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-signature': invalidSignature,
'Authorization': 'Bearer valid-jwt-token',
'Content-Length': Buffer.byteLength(payload)
},
body: payload
};
try {
const response = await makeRequest(requestOptions);
console.log(`\n✓ Status: ${response.statusCode}`);
console.log(`✓ Response: ${JSON.stringify(response.parsedBody, null, 2)}`);
if (response.statusCode === 401) {
console.log('\n✅ TEST PASSED: Invalid signature rejected with 401');
} else {
console.log('\n⚠️ TEST WARNING: Expected 401, got ' + response.statusCode);
}
} catch (error) {
console.error('❌ TEST FAILED:', error.message);
}
}
/**
* Test Case 3: Missing X-Signature header - Should fail (400)
*/
async function testMissingSignatureHeader() {
console.log('\n' + '='.repeat(60));
console.log('TEST 3: Missing X-Signature Header');
console.log('='.repeat(60));
const payload = JSON.stringify(eventPayload);
console.log(`✓ Omitting X-Signature header in request`);
console.log(`✓ Payload size: ${payload.length} bytes`);
const requestOptions = {
hostname: SERVER_HOST,
port: SERVER_PORT,
path: WEBHOOK_PATH,
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer valid-jwt-token',
'Content-Length': Buffer.byteLength(payload)
},
body: payload
};
try {
const response = await makeRequest(requestOptions);
console.log(`\n✓ Status: ${response.statusCode}`);
console.log(`✓ Response: ${JSON.stringify(response.parsedBody, null, 2)}`);
if (response.statusCode === 400 || response.statusCode === 401) {
console.log('\n✅ TEST PASSED: Missing header rejected with 400/401');
} else {
console.log('\n⚠️ TEST WARNING: Expected 400/401, got ' + response.statusCode);
}
} catch (error) {
console.error('❌ TEST FAILED:', error.message);
}
}
/**
* Test Case 4: Tampered payload - Should fail (401)
*/
async function testTamperedPayload() {
console.log('\n' + '='.repeat(60));
console.log('TEST 4: Tampered Payload (Signature Mismatch)');
console.log('='.repeat(60));
const originalPayload = JSON.stringify(eventPayload);
const signature = generateSignature(originalPayload, WEBHOOK_SECRET);
// Tamper with the payload
const tamperedEvent = { ...eventPayload, data: { ...eventPayload.data, amountOut: '500' } };
const tamperedPayload = JSON.stringify(tamperedEvent);
console.log(`✓ Original amount: ${eventPayload.data.amountOut}`);
console.log(`✓ Tampered amount: ${tamperedEvent.data.amountOut}`);
console.log(`✓ Using signature from original payload`);
console.log(`✓ Original payload size: ${originalPayload.length} bytes`);
console.log(`✓ Tampered payload size: ${tamperedPayload.length} bytes`);
const requestOptions = {
hostname: SERVER_HOST,
port: SERVER_PORT,
path: WEBHOOK_PATH,
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-signature': signature,
'Authorization': 'Bearer valid-jwt-token',
'Content-Length': Buffer.byteLength(tamperedPayload)
},
body: tamperedPayload
};
try {
const response = await makeRequest(requestOptions);
console.log(`\n✓ Status: ${response.statusCode}`);
console.log(`✓ Response: ${JSON.stringify(response.parsedBody, null, 2)}`);
if (response.statusCode === 401) {
console.log('\n✅ TEST PASSED: Tampered payload detected and rejected');
} else {
console.log('\n⚠️ TEST WARNING: Expected 401, got ' + response.statusCode);
}
} catch (error) {
console.error('❌ TEST FAILED:', error.message);
}
}
/**
* Main test runner
*/
async function runAllTests() {
console.log('\n');
console.log('╔════════════════════════════════════════════════════════════╗');
console.log('║ WEBHOOK HMAC SIGNATURE VERIFICATION TESTS ║');
console.log('╚════════════════════════════════════════════════════════════╝');
console.log(`\nServer: http://${SERVER_HOST}:${SERVER_PORT}`);
console.log(`Endpoint: ${WEBHOOK_PATH}`);
console.log(`WEBHOOK_SECRET: ${WEBHOOK_SECRET.substring(0, 10)}...`);
await testValidSignature();
await testInvalidSignature();
await testMissingSignatureHeader();
await testTamperedPayload();
console.log('\n' + '='.repeat(60));
console.log('Test suite completed!');
console.log('='.repeat(60));
console.log('\nNOTE: Tests expect the server to be running with proper JWT');
console.log('authentication. Adjust Authorization header as needed.\n');
}
// Run tests
runAllTests().catch(console.error);