tr-apisrv 1.0.0 → 3.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +416 -62
- package/index.js +974 -91
- package/package.json +1 -1
- package/test/test.js +1570 -10
package/test/test.js
CHANGED
|
@@ -17,7 +17,7 @@ function httpRequest(port, { method = 'GET', path = '/', headers = {}, body } =
|
|
|
17
17
|
}, (res) => {
|
|
18
18
|
let data = '';
|
|
19
19
|
res.on('data', (d) => data += d);
|
|
20
|
-
res.on('end', () => resolve({ status: res.statusCode, data }));
|
|
20
|
+
res.on('end', () => resolve({ status: res.statusCode, data, headers: res.headers }));
|
|
21
21
|
});
|
|
22
22
|
req.on('error', reject);
|
|
23
23
|
if (body) {
|
|
@@ -45,12 +45,24 @@ test('handles GET requests', async () => {
|
|
|
45
45
|
const port = 12350;
|
|
46
46
|
const srv = new ApiSrv({
|
|
47
47
|
port,
|
|
48
|
-
callback: (r) => r.jsonResponse({
|
|
48
|
+
callback: (r) => r.jsonResponse({
|
|
49
|
+
method: r.method,
|
|
50
|
+
params: r.params,
|
|
51
|
+
pathParams: r.pathParams,
|
|
52
|
+
urlParams: r.urlParams,
|
|
53
|
+
bodyParams: r.bodyParams
|
|
54
|
+
})
|
|
49
55
|
});
|
|
50
56
|
try {
|
|
51
57
|
const res = await httpRequest(port, { method: 'GET', path: '/?a=1' });
|
|
52
58
|
assert.strictEqual(res.status, 200);
|
|
53
|
-
assert.deepStrictEqual(JSON.parse(res.data), {
|
|
59
|
+
assert.deepStrictEqual(JSON.parse(res.data), {
|
|
60
|
+
method: 'GET',
|
|
61
|
+
params: { a: '1' },
|
|
62
|
+
pathParams: {},
|
|
63
|
+
urlParams: { a: '1' },
|
|
64
|
+
bodyParams: {}
|
|
65
|
+
});
|
|
54
66
|
} finally {
|
|
55
67
|
await srv.shutdown();
|
|
56
68
|
}
|
|
@@ -60,7 +72,13 @@ test('handles POST requests', async () => {
|
|
|
60
72
|
const port = 12351;
|
|
61
73
|
const srv = new ApiSrv({
|
|
62
74
|
port,
|
|
63
|
-
callback: (r) => r.jsonResponse({
|
|
75
|
+
callback: (r) => r.jsonResponse({
|
|
76
|
+
method: r.method,
|
|
77
|
+
params: r.params,
|
|
78
|
+
pathParams: r.pathParams,
|
|
79
|
+
urlParams: r.urlParams,
|
|
80
|
+
bodyParams: r.bodyParams
|
|
81
|
+
})
|
|
64
82
|
});
|
|
65
83
|
try {
|
|
66
84
|
const res = await httpRequest(port, {
|
|
@@ -70,7 +88,13 @@ test('handles POST requests', async () => {
|
|
|
70
88
|
body: JSON.stringify({ a: 1 })
|
|
71
89
|
});
|
|
72
90
|
assert.strictEqual(res.status, 200);
|
|
73
|
-
assert.deepStrictEqual(JSON.parse(res.data), {
|
|
91
|
+
assert.deepStrictEqual(JSON.parse(res.data), {
|
|
92
|
+
method: 'POST',
|
|
93
|
+
params: { a: 1 },
|
|
94
|
+
pathParams: {},
|
|
95
|
+
urlParams: {},
|
|
96
|
+
bodyParams: { a: 1 }
|
|
97
|
+
});
|
|
74
98
|
} finally {
|
|
75
99
|
await srv.shutdown();
|
|
76
100
|
}
|
|
@@ -80,7 +104,13 @@ test('handles PUT requests', async () => {
|
|
|
80
104
|
const port = 12352;
|
|
81
105
|
const srv = new ApiSrv({
|
|
82
106
|
port,
|
|
83
|
-
callback: (r) => r.jsonResponse({
|
|
107
|
+
callback: (r) => r.jsonResponse({
|
|
108
|
+
method: r.method,
|
|
109
|
+
params: r.params,
|
|
110
|
+
pathParams: r.pathParams,
|
|
111
|
+
urlParams: r.urlParams,
|
|
112
|
+
bodyParams: r.bodyParams
|
|
113
|
+
})
|
|
84
114
|
});
|
|
85
115
|
try {
|
|
86
116
|
const res = await httpRequest(port, {
|
|
@@ -90,7 +120,13 @@ test('handles PUT requests', async () => {
|
|
|
90
120
|
body: 'a=1'
|
|
91
121
|
});
|
|
92
122
|
assert.strictEqual(res.status, 200);
|
|
93
|
-
assert.deepStrictEqual(JSON.parse(res.data), {
|
|
123
|
+
assert.deepStrictEqual(JSON.parse(res.data), {
|
|
124
|
+
method: 'PUT',
|
|
125
|
+
params: { a: '1' },
|
|
126
|
+
pathParams: {},
|
|
127
|
+
urlParams: {},
|
|
128
|
+
bodyParams: { a: '1' }
|
|
129
|
+
});
|
|
94
130
|
} finally {
|
|
95
131
|
await srv.shutdown();
|
|
96
132
|
}
|
|
@@ -100,12 +136,916 @@ test('handles DELETE requests', async () => {
|
|
|
100
136
|
const port = 12353;
|
|
101
137
|
const srv = new ApiSrv({
|
|
102
138
|
port,
|
|
103
|
-
callback: (r) => r.jsonResponse({
|
|
139
|
+
callback: (r) => r.jsonResponse({
|
|
140
|
+
method: r.method,
|
|
141
|
+
params: r.params,
|
|
142
|
+
pathParams: r.pathParams,
|
|
143
|
+
urlParams: r.urlParams,
|
|
144
|
+
bodyParams: r.bodyParams
|
|
145
|
+
})
|
|
104
146
|
});
|
|
105
147
|
try {
|
|
106
148
|
const res = await httpRequest(port, { method: 'DELETE', path: '/?a=1' });
|
|
107
149
|
assert.strictEqual(res.status, 200);
|
|
108
|
-
assert.deepStrictEqual(JSON.parse(res.data), {
|
|
150
|
+
assert.deepStrictEqual(JSON.parse(res.data), {
|
|
151
|
+
method: 'DELETE',
|
|
152
|
+
params: { a: '1' },
|
|
153
|
+
pathParams: {},
|
|
154
|
+
urlParams: { a: '1' },
|
|
155
|
+
bodyParams: {}
|
|
156
|
+
});
|
|
157
|
+
} finally {
|
|
158
|
+
await srv.shutdown();
|
|
159
|
+
}
|
|
160
|
+
});
|
|
161
|
+
|
|
162
|
+
test('handlers can respond with JSON errors via errorResponse', async () => {
|
|
163
|
+
const port = 12354;
|
|
164
|
+
const srv = new ApiSrv({
|
|
165
|
+
port,
|
|
166
|
+
requestHandlers: {
|
|
167
|
+
POST: {
|
|
168
|
+
'/items': (r) => r.errorResponse(400, 'Input data is too complex')
|
|
169
|
+
},
|
|
170
|
+
GET: {
|
|
171
|
+
'/items': (r) => r.errorResponse(404)
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
});
|
|
175
|
+
try {
|
|
176
|
+
const invalid = await httpRequest(port, {
|
|
177
|
+
method: 'POST',
|
|
178
|
+
path: '/items',
|
|
179
|
+
headers: { 'Content-Type': 'application/json' },
|
|
180
|
+
body: '{}'
|
|
181
|
+
});
|
|
182
|
+
assert.strictEqual(invalid.status, 400);
|
|
183
|
+
const invalidBody = JSON.parse(invalid.data);
|
|
184
|
+
assert.strictEqual(invalidBody.code, 400);
|
|
185
|
+
assert.strictEqual(invalidBody.message, 'Bad Request (Input data is too complex)');
|
|
186
|
+
|
|
187
|
+
const missing = await httpRequest(port, { method: 'GET', path: '/items' });
|
|
188
|
+
assert.strictEqual(missing.status, 404);
|
|
189
|
+
const missingBody = JSON.parse(missing.data);
|
|
190
|
+
assert.strictEqual(missingBody.code, 404);
|
|
191
|
+
assert.strictEqual(missingBody.message, 'Not Found');
|
|
192
|
+
} finally {
|
|
193
|
+
await srv.shutdown();
|
|
194
|
+
}
|
|
195
|
+
});
|
|
196
|
+
|
|
197
|
+
test('requestHandlers take precedence over callback', async () => {
|
|
198
|
+
const port = 12361;
|
|
199
|
+
const srv = new ApiSrv({
|
|
200
|
+
port,
|
|
201
|
+
callback: (r) => r.jsonResponse({ handled: 'callback' }),
|
|
202
|
+
requestHandlers: {
|
|
203
|
+
GET: {
|
|
204
|
+
'/': (r) => r.jsonResponse({ handled: 'requestHandlers' })
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
});
|
|
208
|
+
try {
|
|
209
|
+
const res = await httpRequest(port, { method: 'GET', path: '/' });
|
|
210
|
+
assert.strictEqual(res.status, 200);
|
|
211
|
+
assert.deepStrictEqual(JSON.parse(res.data), { handled: 'requestHandlers' });
|
|
212
|
+
} finally {
|
|
213
|
+
await srv.shutdown();
|
|
214
|
+
}
|
|
215
|
+
});
|
|
216
|
+
|
|
217
|
+
test('requestHandlers support path templates', async (t) => {
|
|
218
|
+
const port = 12362;
|
|
219
|
+
const warnings = [];
|
|
220
|
+
const warnMock = t.mock.method(console, 'warn', (...args) => warnings.push(args.join(' ')));
|
|
221
|
+
const srv = new ApiSrv({
|
|
222
|
+
port,
|
|
223
|
+
callback: (r) => r.jsonResponse({ handled: 'callback' }),
|
|
224
|
+
requestHandlers: {
|
|
225
|
+
GET: {
|
|
226
|
+
'/user/{userId}': (r) => r.jsonResponse({
|
|
227
|
+
handled: 'requestHandlers',
|
|
228
|
+
params: r.params,
|
|
229
|
+
pathParams: r.pathParams,
|
|
230
|
+
urlParams: r.urlParams,
|
|
231
|
+
bodyParams: r.bodyParams
|
|
232
|
+
})
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
});
|
|
236
|
+
try {
|
|
237
|
+
const res = await httpRequest(port, { method: 'GET', path: '/user/123?foo=bar&userId=query' });
|
|
238
|
+
assert.strictEqual(res.status, 200);
|
|
239
|
+
assert.deepStrictEqual(JSON.parse(res.data), {
|
|
240
|
+
handled: 'requestHandlers',
|
|
241
|
+
params: { foo: 'bar', userId: '123' },
|
|
242
|
+
pathParams: { userId: '123' },
|
|
243
|
+
urlParams: { foo: 'bar', userId: 'query' },
|
|
244
|
+
bodyParams: {}
|
|
245
|
+
});
|
|
246
|
+
assert.strictEqual(warnings.length, 1);
|
|
247
|
+
assert.match(warnings[0], /userId/);
|
|
248
|
+
assert.match(warnings[0], /query string/);
|
|
249
|
+
} finally {
|
|
250
|
+
t.mock.restoreAll();
|
|
251
|
+
await srv.shutdown();
|
|
252
|
+
}
|
|
253
|
+
});
|
|
254
|
+
|
|
255
|
+
test('requestHandlers match trailing slash when template omits it', async () => {
|
|
256
|
+
const port = 12370;
|
|
257
|
+
const srv = new ApiSrv({
|
|
258
|
+
port,
|
|
259
|
+
requestHandlers: {
|
|
260
|
+
GET: {
|
|
261
|
+
'/slashless': (r) => r.jsonResponse({ handled: 'slashless', path: r.url })
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
});
|
|
265
|
+
try {
|
|
266
|
+
let res = await httpRequest(port, { method: 'GET', path: '/slashless' });
|
|
267
|
+
assert.strictEqual(res.status, 200);
|
|
268
|
+
assert.deepStrictEqual(JSON.parse(res.data), { handled: 'slashless', path: '/slashless' });
|
|
269
|
+
|
|
270
|
+
res = await httpRequest(port, { method: 'GET', path: '/slashless/' });
|
|
271
|
+
assert.strictEqual(res.status, 200);
|
|
272
|
+
assert.deepStrictEqual(JSON.parse(res.data), { handled: 'slashless', path: '/slashless/' });
|
|
273
|
+
} finally {
|
|
274
|
+
await srv.shutdown();
|
|
275
|
+
}
|
|
276
|
+
});
|
|
277
|
+
|
|
278
|
+
test('requestHandlers require trailing slash when template includes it', async () => {
|
|
279
|
+
const port = 12371;
|
|
280
|
+
const srv = new ApiSrv({
|
|
281
|
+
port,
|
|
282
|
+
requestHandlers: {
|
|
283
|
+
GET: {
|
|
284
|
+
'/needs-slash/': (r) => r.jsonResponse({ handled: 'needs-slash' })
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
});
|
|
288
|
+
try {
|
|
289
|
+
const withSlash = await httpRequest(port, { method: 'GET', path: '/needs-slash/' });
|
|
290
|
+
assert.strictEqual(withSlash.status, 200);
|
|
291
|
+
assert.deepStrictEqual(JSON.parse(withSlash.data), { handled: 'needs-slash' });
|
|
292
|
+
|
|
293
|
+
const withoutSlash = await httpRequest(port, { method: 'GET', path: '/needs-slash' });
|
|
294
|
+
assert.strictEqual(withoutSlash.status, 404);
|
|
295
|
+
const body = JSON.parse(withoutSlash.data);
|
|
296
|
+
assert.strictEqual(body.code, 404);
|
|
297
|
+
assert.strictEqual(body.message, 'Not Found');
|
|
298
|
+
} finally {
|
|
299
|
+
await srv.shutdown();
|
|
300
|
+
}
|
|
301
|
+
});
|
|
302
|
+
|
|
303
|
+
test('dynamic template without trailing slash matches both forms', async () => {
|
|
304
|
+
const port = 12372;
|
|
305
|
+
const srv = new ApiSrv({
|
|
306
|
+
port,
|
|
307
|
+
requestHandlers: {
|
|
308
|
+
GET: {
|
|
309
|
+
'/user/{userId}': (r) => r.jsonResponse({
|
|
310
|
+
params: r.params,
|
|
311
|
+
pathParams: r.pathParams,
|
|
312
|
+
urlParams: r.urlParams,
|
|
313
|
+
bodyParams: r.bodyParams
|
|
314
|
+
})
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
});
|
|
318
|
+
try {
|
|
319
|
+
let res = await httpRequest(port, { method: 'GET', path: '/user/abc' });
|
|
320
|
+
assert.strictEqual(res.status, 200);
|
|
321
|
+
assert.deepStrictEqual(JSON.parse(res.data), {
|
|
322
|
+
params: { userId: 'abc' },
|
|
323
|
+
pathParams: { userId: 'abc' },
|
|
324
|
+
urlParams: {},
|
|
325
|
+
bodyParams: {}
|
|
326
|
+
});
|
|
327
|
+
|
|
328
|
+
res = await httpRequest(port, { method: 'GET', path: '/user/abc/' });
|
|
329
|
+
assert.strictEqual(res.status, 200);
|
|
330
|
+
assert.deepStrictEqual(JSON.parse(res.data), {
|
|
331
|
+
params: { userId: 'abc' },
|
|
332
|
+
pathParams: { userId: 'abc' },
|
|
333
|
+
urlParams: {},
|
|
334
|
+
bodyParams: {}
|
|
335
|
+
});
|
|
336
|
+
} finally {
|
|
337
|
+
await srv.shutdown();
|
|
338
|
+
}
|
|
339
|
+
});
|
|
340
|
+
|
|
341
|
+
test('dynamic template with trailing slash requires trailing slash in request', async () => {
|
|
342
|
+
const port = 12373;
|
|
343
|
+
const srv = new ApiSrv({
|
|
344
|
+
port,
|
|
345
|
+
requestHandlers: {
|
|
346
|
+
GET: {
|
|
347
|
+
'/user/{userId}/': (r) => r.jsonResponse({ params: r.params })
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
});
|
|
351
|
+
try {
|
|
352
|
+
const withSlash = await httpRequest(port, { method: 'GET', path: '/user/abc/' });
|
|
353
|
+
assert.strictEqual(withSlash.status, 200);
|
|
354
|
+
assert.deepStrictEqual(JSON.parse(withSlash.data), { params: { userId: 'abc' } });
|
|
355
|
+
|
|
356
|
+
const withoutSlash = await httpRequest(port, { method: 'GET', path: '/user/abc' });
|
|
357
|
+
assert.strictEqual(withoutSlash.status, 404);
|
|
358
|
+
const body = JSON.parse(withoutSlash.data);
|
|
359
|
+
assert.strictEqual(body.code, 404);
|
|
360
|
+
assert.strictEqual(body.message, 'Not Found');
|
|
361
|
+
} finally {
|
|
362
|
+
await srv.shutdown();
|
|
363
|
+
}
|
|
364
|
+
});
|
|
365
|
+
|
|
366
|
+
test('requestHandlers reject invalid path parameter names', () => {
|
|
367
|
+
assert.throws(() => {
|
|
368
|
+
new ApiSrv({
|
|
369
|
+
port: 12394,
|
|
370
|
+
requestHandlers: {
|
|
371
|
+
GET: {
|
|
372
|
+
'/users/{1bad}': () => {}
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
});
|
|
376
|
+
}, /Invalid path parameter name/);
|
|
377
|
+
|
|
378
|
+
assert.throws(() => {
|
|
379
|
+
new ApiSrv({
|
|
380
|
+
port: 12395,
|
|
381
|
+
requestHandlers: {
|
|
382
|
+
GET: {
|
|
383
|
+
'/files/[bad-name]': () => {}
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
});
|
|
387
|
+
}, /Invalid path parameter name|Invalid path parameter segment/);
|
|
388
|
+
});
|
|
389
|
+
|
|
390
|
+
test('requestHandlers reject invalid array constraints', () => {
|
|
391
|
+
assert.throws(() => {
|
|
392
|
+
new ApiSrv({
|
|
393
|
+
port: 12396,
|
|
394
|
+
requestHandlers: {
|
|
395
|
+
GET: {
|
|
396
|
+
'/files/[segments:0]': () => {}
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
});
|
|
400
|
+
}, /Invalid minimum length/);
|
|
401
|
+
|
|
402
|
+
assert.throws(() => {
|
|
403
|
+
new ApiSrv({
|
|
404
|
+
port: 12397,
|
|
405
|
+
requestHandlers: {
|
|
406
|
+
GET: {
|
|
407
|
+
'/files/[segments:5:2]': () => {}
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
});
|
|
411
|
+
}, /Invalid length range/);
|
|
412
|
+
|
|
413
|
+
assert.throws(() => {
|
|
414
|
+
new ApiSrv({
|
|
415
|
+
port: 12398,
|
|
416
|
+
requestHandlers: {
|
|
417
|
+
GET: {
|
|
418
|
+
'/files/[segments:4:four]': () => {}
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
});
|
|
422
|
+
}, /Invalid path parameter segment/);
|
|
423
|
+
});
|
|
424
|
+
|
|
425
|
+
test('falls back to callback when requestHandlers do not match', async () => {
|
|
426
|
+
const port = 12363;
|
|
427
|
+
const srv = new ApiSrv({
|
|
428
|
+
port,
|
|
429
|
+
callback: (r) => r.jsonResponse({ handled: 'callback' }),
|
|
430
|
+
requestHandlers: {
|
|
431
|
+
GET: {
|
|
432
|
+
'/foo': (r) => r.jsonResponse({ handled: 'requestHandlers' })
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
});
|
|
436
|
+
try {
|
|
437
|
+
const res = await httpRequest(port, { method: 'GET', path: '/' });
|
|
438
|
+
assert.strictEqual(res.status, 200);
|
|
439
|
+
assert.deepStrictEqual(JSON.parse(res.data), { handled: 'callback' });
|
|
440
|
+
} finally {
|
|
441
|
+
await srv.shutdown();
|
|
442
|
+
}
|
|
443
|
+
});
|
|
444
|
+
|
|
445
|
+
test('request handler definition objects apply validators', async () => {
|
|
446
|
+
const port = 12376;
|
|
447
|
+
const srv = new ApiSrv({
|
|
448
|
+
port,
|
|
449
|
+
requestHandlers: {
|
|
450
|
+
GET: {
|
|
451
|
+
'/validate/{userId}': {
|
|
452
|
+
callback: (r) => r.jsonResponse({
|
|
453
|
+
params: r.params,
|
|
454
|
+
pathParams: r.pathParams,
|
|
455
|
+
urlParams: r.urlParams
|
|
456
|
+
}),
|
|
457
|
+
options: {
|
|
458
|
+
pathParamsValidator: (pathParams) => ({ userId: Number(pathParams.userId) }),
|
|
459
|
+
urlParamsValidator: async (urlParams) => ({ limit: Number(urlParams.limit) }),
|
|
460
|
+
paramsValidator: async (params) => ({ ...params, validated: true })
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
});
|
|
466
|
+
try {
|
|
467
|
+
const res = await httpRequest(port, { method: 'GET', path: '/validate/42?limit=5' });
|
|
468
|
+
assert.strictEqual(res.status, 200);
|
|
469
|
+
assert.deepStrictEqual(JSON.parse(res.data), {
|
|
470
|
+
params: { limit: 5, userId: 42, validated: true },
|
|
471
|
+
pathParams: { userId: 42 },
|
|
472
|
+
urlParams: { limit: 5 }
|
|
473
|
+
});
|
|
474
|
+
} finally {
|
|
475
|
+
await srv.shutdown();
|
|
476
|
+
}
|
|
477
|
+
});
|
|
478
|
+
|
|
479
|
+
test('requestHandlers capture array segments with [variable]', async () => {
|
|
480
|
+
const port = 12367;
|
|
481
|
+
const srv = new ApiSrv({
|
|
482
|
+
port,
|
|
483
|
+
requestHandlers: {
|
|
484
|
+
GET: {
|
|
485
|
+
'/files/[pathParts]': (r) => r.jsonResponse({ params: r.params, pathParams: r.pathParams })
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
});
|
|
489
|
+
try {
|
|
490
|
+
const res = await httpRequest(port, { method: 'GET', path: '/files/foo/bar/baz' });
|
|
491
|
+
assert.strictEqual(res.status, 200);
|
|
492
|
+
assert.deepStrictEqual(JSON.parse(res.data), {
|
|
493
|
+
params: { pathParts: ['foo', 'bar', 'baz'] },
|
|
494
|
+
pathParams: { pathParts: ['foo', 'bar', 'baz'] }
|
|
495
|
+
});
|
|
496
|
+
} finally {
|
|
497
|
+
await srv.shutdown();
|
|
498
|
+
}
|
|
499
|
+
});
|
|
500
|
+
|
|
501
|
+
test('requestHandlers capture [variable] segments in the middle of a template', async () => {
|
|
502
|
+
const port = 12368;
|
|
503
|
+
const srv = new ApiSrv({
|
|
504
|
+
port,
|
|
505
|
+
requestHandlers: {
|
|
506
|
+
GET: {
|
|
507
|
+
'/{cmd}/[zap]/{bar}/{pup}': (r) => r.jsonResponse({ params: r.params, pathParams: r.pathParams })
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
});
|
|
511
|
+
try {
|
|
512
|
+
const res = await httpRequest(port, { method: 'GET', path: '/do/one/two/three/four' });
|
|
513
|
+
assert.strictEqual(res.status, 200);
|
|
514
|
+
assert.deepStrictEqual(JSON.parse(res.data), {
|
|
515
|
+
params: {
|
|
516
|
+
cmd: 'do',
|
|
517
|
+
zap: ['one', 'two'],
|
|
518
|
+
bar: 'three',
|
|
519
|
+
pup: 'four'
|
|
520
|
+
},
|
|
521
|
+
pathParams: {
|
|
522
|
+
cmd: 'do',
|
|
523
|
+
zap: ['one', 'two'],
|
|
524
|
+
bar: 'three',
|
|
525
|
+
pup: 'four'
|
|
526
|
+
}
|
|
527
|
+
});
|
|
528
|
+
} finally {
|
|
529
|
+
await srv.shutdown();
|
|
530
|
+
}
|
|
531
|
+
});
|
|
532
|
+
|
|
533
|
+
test('array path parameter enforces default length constraints', async () => {
|
|
534
|
+
const port = 12390;
|
|
535
|
+
const srv = new ApiSrv({
|
|
536
|
+
port,
|
|
537
|
+
requestHandlers: {
|
|
538
|
+
GET: {
|
|
539
|
+
'/files/[segments]': (r) => r.jsonResponse({ pathParams: r.pathParams })
|
|
540
|
+
}
|
|
541
|
+
}
|
|
542
|
+
});
|
|
543
|
+
const exactly32 = Array.from({ length: 32 }, (_, i) => `part${i}`);
|
|
544
|
+
const tooMany = Array.from({ length: 33 }, (_, i) => `part${i}`);
|
|
545
|
+
try {
|
|
546
|
+
const within = await httpRequest(port, { method: 'GET', path: `/files/${exactly32.join('/')}` });
|
|
547
|
+
assert.strictEqual(within.status, 200);
|
|
548
|
+
const parsedWithin = JSON.parse(within.data);
|
|
549
|
+
assert.deepStrictEqual(parsedWithin.pathParams.segments, exactly32);
|
|
550
|
+
|
|
551
|
+
const overLimit = await httpRequest(port, { method: 'GET', path: `/files/${tooMany.join('/')}` });
|
|
552
|
+
assert.strictEqual(overLimit.status, 404);
|
|
553
|
+
const body = JSON.parse(overLimit.data);
|
|
554
|
+
assert.strictEqual(body.code, 404);
|
|
555
|
+
assert.strictEqual(body.message, 'Not Found');
|
|
556
|
+
} finally {
|
|
557
|
+
await srv.shutdown();
|
|
558
|
+
}
|
|
559
|
+
});
|
|
560
|
+
|
|
561
|
+
test('array path parameter enforces exact length constraint', async () => {
|
|
562
|
+
const port = 12391;
|
|
563
|
+
const srv = new ApiSrv({
|
|
564
|
+
port,
|
|
565
|
+
requestHandlers: {
|
|
566
|
+
GET: {
|
|
567
|
+
'/files/[segments:4]': (r) => r.jsonResponse({ pathParams: r.pathParams })
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
});
|
|
571
|
+
const exactlyFour = Array.from({ length: 4 }, (_, i) => `p${i}`);
|
|
572
|
+
const three = exactlyFour.slice(0, 3);
|
|
573
|
+
const five = [...exactlyFour, 'extra'];
|
|
574
|
+
try {
|
|
575
|
+
const exact = await httpRequest(port, { method: 'GET', path: `/files/${exactlyFour.join('/')}` });
|
|
576
|
+
assert.strictEqual(exact.status, 200);
|
|
577
|
+
const parsedExact = JSON.parse(exact.data);
|
|
578
|
+
assert.deepStrictEqual(parsedExact.pathParams.segments, exactlyFour);
|
|
579
|
+
|
|
580
|
+
const tooFew = await httpRequest(port, { method: 'GET', path: `/files/${three.join('/')}` });
|
|
581
|
+
assert.strictEqual(tooFew.status, 404);
|
|
582
|
+
const bodyFew = JSON.parse(tooFew.data);
|
|
583
|
+
assert.strictEqual(bodyFew.code, 404);
|
|
584
|
+
assert.strictEqual(bodyFew.message, 'Not Found');
|
|
585
|
+
|
|
586
|
+
const tooMany = await httpRequest(port, { method: 'GET', path: `/files/${five.join('/')}` });
|
|
587
|
+
assert.strictEqual(tooMany.status, 404);
|
|
588
|
+
const bodyMany = JSON.parse(tooMany.data);
|
|
589
|
+
assert.strictEqual(bodyMany.code, 404);
|
|
590
|
+
assert.strictEqual(bodyMany.message, 'Not Found');
|
|
591
|
+
} finally {
|
|
592
|
+
await srv.shutdown();
|
|
593
|
+
}
|
|
594
|
+
});
|
|
595
|
+
|
|
596
|
+
test('array path parameter enforces min and max constraints', async () => {
|
|
597
|
+
const port = 12392;
|
|
598
|
+
const srv = new ApiSrv({
|
|
599
|
+
port,
|
|
600
|
+
requestHandlers: {
|
|
601
|
+
GET: {
|
|
602
|
+
'/files/[segments:2:4]': (r) => r.jsonResponse({ pathParams: r.pathParams })
|
|
603
|
+
}
|
|
604
|
+
}
|
|
605
|
+
});
|
|
606
|
+
const two = ['a', 'b'];
|
|
607
|
+
const four = ['a', 'b', 'c', 'd'];
|
|
608
|
+
try {
|
|
609
|
+
const minOk = await httpRequest(port, { method: 'GET', path: `/files/${two.join('/')}` });
|
|
610
|
+
assert.strictEqual(minOk.status, 200);
|
|
611
|
+
const parsedMin = JSON.parse(minOk.data);
|
|
612
|
+
assert.deepStrictEqual(parsedMin.pathParams.segments, two);
|
|
613
|
+
|
|
614
|
+
const maxOk = await httpRequest(port, { method: 'GET', path: `/files/${four.join('/')}` });
|
|
615
|
+
assert.strictEqual(maxOk.status, 200);
|
|
616
|
+
const parsedMax = JSON.parse(maxOk.data);
|
|
617
|
+
assert.deepStrictEqual(parsedMax.pathParams.segments, four);
|
|
618
|
+
|
|
619
|
+
const tooFew = await httpRequest(port, { method: 'GET', path: '/files/a' });
|
|
620
|
+
assert.strictEqual(tooFew.status, 404);
|
|
621
|
+
const bodyFew = JSON.parse(tooFew.data);
|
|
622
|
+
assert.strictEqual(bodyFew.code, 404);
|
|
623
|
+
assert.strictEqual(bodyFew.message, 'Not Found');
|
|
624
|
+
|
|
625
|
+
const tooMany = await httpRequest(port, { method: 'GET', path: '/files/a/b/c/d/e' });
|
|
626
|
+
assert.strictEqual(tooMany.status, 404);
|
|
627
|
+
const bodyMany = JSON.parse(tooMany.data);
|
|
628
|
+
assert.strictEqual(bodyMany.code, 404);
|
|
629
|
+
assert.strictEqual(bodyMany.message, 'Not Found');
|
|
630
|
+
} finally {
|
|
631
|
+
await srv.shutdown();
|
|
632
|
+
}
|
|
633
|
+
});
|
|
634
|
+
|
|
635
|
+
test('array path parameter allows raising the default maximum', async () => {
|
|
636
|
+
const port = 12393;
|
|
637
|
+
const srv = new ApiSrv({
|
|
638
|
+
port,
|
|
639
|
+
requestHandlers: {
|
|
640
|
+
GET: {
|
|
641
|
+
'/files/[segments:10:50]': (r) => r.jsonResponse({ pathParams: r.pathParams })
|
|
642
|
+
}
|
|
643
|
+
}
|
|
644
|
+
});
|
|
645
|
+
const ten = Array.from({ length: 10 }, (_, i) => `s${i}`);
|
|
646
|
+
const forty = Array.from({ length: 40 }, (_, i) => `s${i}`);
|
|
647
|
+
const nine = ten.slice(0, 9);
|
|
648
|
+
const fiftyOne = Array.from({ length: 51 }, (_, i) => `s${i}`);
|
|
649
|
+
try {
|
|
650
|
+
const minOk = await httpRequest(port, { method: 'GET', path: `/files/${ten.join('/')}` });
|
|
651
|
+
assert.strictEqual(minOk.status, 200);
|
|
652
|
+
const parsedMin = JSON.parse(minOk.data);
|
|
653
|
+
assert.deepStrictEqual(parsedMin.pathParams.segments, ten);
|
|
654
|
+
|
|
655
|
+
const extended = await httpRequest(port, { method: 'GET', path: `/files/${forty.join('/')}` });
|
|
656
|
+
assert.strictEqual(extended.status, 200);
|
|
657
|
+
const parsedExtended = JSON.parse(extended.data);
|
|
658
|
+
assert.deepStrictEqual(parsedExtended.pathParams.segments, forty);
|
|
659
|
+
|
|
660
|
+
const belowMin = await httpRequest(port, { method: 'GET', path: `/files/${nine.join('/')}` });
|
|
661
|
+
assert.strictEqual(belowMin.status, 404);
|
|
662
|
+
const bodyLow = JSON.parse(belowMin.data);
|
|
663
|
+
assert.strictEqual(bodyLow.code, 404);
|
|
664
|
+
assert.strictEqual(bodyLow.message, 'Not Found');
|
|
665
|
+
|
|
666
|
+
const aboveMax = await httpRequest(port, { method: 'GET', path: `/files/${fiftyOne.join('/')}` });
|
|
667
|
+
assert.strictEqual(aboveMax.status, 404);
|
|
668
|
+
const bodyHigh = JSON.parse(aboveMax.data);
|
|
669
|
+
assert.strictEqual(bodyHigh.code, 404);
|
|
670
|
+
assert.strictEqual(bodyHigh.message, 'Not Found');
|
|
671
|
+
} finally {
|
|
672
|
+
await srv.shutdown();
|
|
673
|
+
}
|
|
674
|
+
});
|
|
675
|
+
|
|
676
|
+
test('ignoreUrlParams prevents query parsing', async () => {
|
|
677
|
+
const port = 12377;
|
|
678
|
+
let urlValidatorCalled = false;
|
|
679
|
+
const srv = new ApiSrv({
|
|
680
|
+
port,
|
|
681
|
+
requestHandlers: {
|
|
682
|
+
GET: {
|
|
683
|
+
'/items/{itemId}': {
|
|
684
|
+
callback: (r) => r.jsonResponse({
|
|
685
|
+
params: r.params,
|
|
686
|
+
pathParams: r.pathParams,
|
|
687
|
+
hasUrlParams: Object.prototype.hasOwnProperty.call(r, 'urlParams')
|
|
688
|
+
}),
|
|
689
|
+
options: {
|
|
690
|
+
ignoreUrlParams: true,
|
|
691
|
+
urlParamsValidator: () => {
|
|
692
|
+
urlValidatorCalled = true;
|
|
693
|
+
return {};
|
|
694
|
+
}
|
|
695
|
+
}
|
|
696
|
+
}
|
|
697
|
+
}
|
|
698
|
+
}
|
|
699
|
+
});
|
|
700
|
+
try {
|
|
701
|
+
const res = await httpRequest(port, { method: 'GET', path: '/items/abc?foo=bar' });
|
|
702
|
+
assert.strictEqual(res.status, 200);
|
|
703
|
+
assert.deepStrictEqual(JSON.parse(res.data), {
|
|
704
|
+
params: { itemId: 'abc' },
|
|
705
|
+
pathParams: { itemId: 'abc' },
|
|
706
|
+
hasUrlParams: false
|
|
707
|
+
});
|
|
708
|
+
assert.strictEqual(urlValidatorCalled, false);
|
|
709
|
+
} finally {
|
|
710
|
+
await srv.shutdown();
|
|
711
|
+
}
|
|
712
|
+
});
|
|
713
|
+
|
|
714
|
+
test('path parameters override body parameters with warning', async (t) => {
|
|
715
|
+
const port = 12369;
|
|
716
|
+
const warnings = [];
|
|
717
|
+
const warnMock = t.mock.method(console, 'warn', (...args) => warnings.push(args.join(' ')));
|
|
718
|
+
const srv = new ApiSrv({
|
|
719
|
+
port,
|
|
720
|
+
requestHandlers: {
|
|
721
|
+
POST: {
|
|
722
|
+
'/user/{userId}': (r) => r.jsonResponse({
|
|
723
|
+
params: r.params,
|
|
724
|
+
pathParams: r.pathParams,
|
|
725
|
+
urlParams: r.urlParams,
|
|
726
|
+
bodyParams: r.bodyParams
|
|
727
|
+
})
|
|
728
|
+
}
|
|
729
|
+
}
|
|
730
|
+
});
|
|
731
|
+
try {
|
|
732
|
+
const res = await httpRequest(port, {
|
|
733
|
+
method: 'POST',
|
|
734
|
+
path: '/user/123',
|
|
735
|
+
headers: { 'Content-Type': 'application/json' },
|
|
736
|
+
body: JSON.stringify({ userId: 'fromBody', name: 'alice' })
|
|
737
|
+
});
|
|
738
|
+
assert.strictEqual(res.status, 200);
|
|
739
|
+
assert.deepStrictEqual(JSON.parse(res.data), {
|
|
740
|
+
params: { userId: '123', name: 'alice' },
|
|
741
|
+
pathParams: { userId: '123' },
|
|
742
|
+
urlParams: {},
|
|
743
|
+
bodyParams: { userId: 'fromBody', name: 'alice' }
|
|
744
|
+
});
|
|
745
|
+
assert.strictEqual(warnings.length, 1);
|
|
746
|
+
assert.match(warnings[0], /userId/);
|
|
747
|
+
assert.match(warnings[0], /request body/);
|
|
748
|
+
} finally {
|
|
749
|
+
t.mock.restoreAll();
|
|
750
|
+
await srv.shutdown();
|
|
751
|
+
}
|
|
752
|
+
});
|
|
753
|
+
|
|
754
|
+
test('returns 404 when no handler matches and callback missing', async () => {
|
|
755
|
+
const port = 12364;
|
|
756
|
+
const srv = new ApiSrv({
|
|
757
|
+
port,
|
|
758
|
+
requestHandlers: {
|
|
759
|
+
GET: {
|
|
760
|
+
'/foo': (r) => r.jsonResponse({ handled: 'requestHandlers' })
|
|
761
|
+
}
|
|
762
|
+
}
|
|
763
|
+
});
|
|
764
|
+
try {
|
|
765
|
+
const res = await httpRequest(port, { method: 'GET', path: '/bar' });
|
|
766
|
+
assert.strictEqual(res.status, 404);
|
|
767
|
+
assert.strictEqual(res.headers['content-type'], 'application/json; charset=utf-8');
|
|
768
|
+
const body = JSON.parse(res.data);
|
|
769
|
+
assert.strictEqual(body.code, 404);
|
|
770
|
+
assert.strictEqual(body.message, 'Not Found');
|
|
771
|
+
} finally {
|
|
772
|
+
await srv.shutdown();
|
|
773
|
+
}
|
|
774
|
+
});
|
|
775
|
+
|
|
776
|
+
test('returns 405 when path matches other method and callback missing', async () => {
|
|
777
|
+
const port = 12365;
|
|
778
|
+
const srv = new ApiSrv({
|
|
779
|
+
port,
|
|
780
|
+
requestHandlers: {
|
|
781
|
+
GET: {
|
|
782
|
+
'/foo': (r) => r.jsonResponse({ handled: 'requestHandlers' })
|
|
783
|
+
}
|
|
784
|
+
}
|
|
785
|
+
});
|
|
786
|
+
try {
|
|
787
|
+
const res = await httpRequest(port, {
|
|
788
|
+
method: 'POST',
|
|
789
|
+
path: '/foo',
|
|
790
|
+
headers: { 'Content-Type': 'application/json' },
|
|
791
|
+
body: JSON.stringify({})
|
|
792
|
+
});
|
|
793
|
+
assert.strictEqual(res.status, 405);
|
|
794
|
+
assert.strictEqual(res.headers['content-type'], 'application/json; charset=utf-8');
|
|
795
|
+
const body = JSON.parse(res.data);
|
|
796
|
+
assert.strictEqual(body.code, 405);
|
|
797
|
+
assert.strictEqual(body.message, 'Method Not Allowed');
|
|
798
|
+
} finally {
|
|
799
|
+
await srv.shutdown();
|
|
800
|
+
}
|
|
801
|
+
});
|
|
802
|
+
|
|
803
|
+
test('rejects dangerous paths by default', async () => {
|
|
804
|
+
const port = 12367;
|
|
805
|
+
let handled = 0;
|
|
806
|
+
const srv = new ApiSrv({
|
|
807
|
+
port,
|
|
808
|
+
callback: (r) => {
|
|
809
|
+
handled++;
|
|
810
|
+
r.jsonResponse({ ok: true });
|
|
811
|
+
}
|
|
812
|
+
});
|
|
813
|
+
try {
|
|
814
|
+
const cases = [
|
|
815
|
+
{ path: '/foo//bar', message: 'Bad Request (empty path segment)' },
|
|
816
|
+
{ path: '/foo/./bar', message: 'Bad Request (dangerous path segment ".")' },
|
|
817
|
+
{ path: '/foo/../bar', message: 'Bad Request (dangerous path segment "..")' }
|
|
818
|
+
];
|
|
819
|
+
for (const { path, message } of cases) {
|
|
820
|
+
const res = await httpRequest(port, { method: 'GET', path });
|
|
821
|
+
assert.strictEqual(res.status, 400);
|
|
822
|
+
assert.strictEqual(res.headers['content-type'], 'application/json; charset=utf-8');
|
|
823
|
+
const body = JSON.parse(res.data);
|
|
824
|
+
assert.strictEqual(body.code, 400);
|
|
825
|
+
assert.strictEqual(body.message, message);
|
|
826
|
+
}
|
|
827
|
+
assert.strictEqual(handled, 0);
|
|
828
|
+
} finally {
|
|
829
|
+
await srv.shutdown();
|
|
830
|
+
}
|
|
831
|
+
});
|
|
832
|
+
|
|
833
|
+
test('dangerous path rejection can be disabled', async () => {
|
|
834
|
+
const port = 12368;
|
|
835
|
+
let handled = 0;
|
|
836
|
+
const srv = new ApiSrv({
|
|
837
|
+
port,
|
|
838
|
+
rejectDangerousPaths: false,
|
|
839
|
+
callback: (r) => {
|
|
840
|
+
handled++;
|
|
841
|
+
r.jsonResponse({ url: r.url });
|
|
842
|
+
}
|
|
843
|
+
});
|
|
844
|
+
try {
|
|
845
|
+
const res = await httpRequest(port, { method: 'GET', path: '/foo//bar' });
|
|
846
|
+
assert.strictEqual(res.status, 200);
|
|
847
|
+
assert.deepStrictEqual(JSON.parse(res.data), { url: '/foo//bar' });
|
|
848
|
+
assert.strictEqual(handled, 1);
|
|
849
|
+
} finally {
|
|
850
|
+
await srv.shutdown();
|
|
851
|
+
}
|
|
852
|
+
});
|
|
853
|
+
|
|
854
|
+
test('requestHandleAdd and requestHandleDelete modify handlers at runtime', async () => {
|
|
855
|
+
const port = 12366;
|
|
856
|
+
const srv = new ApiSrv({ port });
|
|
857
|
+
srv.requestHandleAdd('GET', '/dynamic', (r) => r.jsonResponse({ method: r.method }));
|
|
858
|
+
srv.requestHandleAdd('POST', '/dynamic', (r) => r.jsonResponse({ method: r.method }));
|
|
859
|
+
try {
|
|
860
|
+
let res = await httpRequest(port, { method: 'GET', path: '/dynamic' });
|
|
861
|
+
assert.strictEqual(res.status, 200);
|
|
862
|
+
assert.deepStrictEqual(JSON.parse(res.data), { method: 'GET' });
|
|
863
|
+
|
|
864
|
+
res = await httpRequest(port, {
|
|
865
|
+
method: 'POST',
|
|
866
|
+
path: '/dynamic',
|
|
867
|
+
headers: { 'Content-Type': 'application/json' },
|
|
868
|
+
body: JSON.stringify({})
|
|
869
|
+
});
|
|
870
|
+
assert.strictEqual(res.status, 200);
|
|
871
|
+
assert.deepStrictEqual(JSON.parse(res.data), { method: 'POST' });
|
|
872
|
+
|
|
873
|
+
srv.requestHandleDelete('GET', '/dynamic');
|
|
874
|
+
res = await httpRequest(port, { method: 'GET', path: '/dynamic' });
|
|
875
|
+
assert.strictEqual(res.status, 405);
|
|
876
|
+
let body = JSON.parse(res.data);
|
|
877
|
+
assert.strictEqual(body.code, 405);
|
|
878
|
+
assert.strictEqual(body.message, 'Method Not Allowed');
|
|
879
|
+
|
|
880
|
+
srv.requestHandleDelete('*', '/dynamic');
|
|
881
|
+
res = await httpRequest(port, {
|
|
882
|
+
method: 'POST',
|
|
883
|
+
path: '/dynamic',
|
|
884
|
+
headers: { 'Content-Type': 'application/json' },
|
|
885
|
+
body: JSON.stringify({})
|
|
886
|
+
});
|
|
887
|
+
assert.strictEqual(res.status, 404);
|
|
888
|
+
body = JSON.parse(res.data);
|
|
889
|
+
assert.strictEqual(body.code, 404);
|
|
890
|
+
assert.strictEqual(body.message, 'Not Found');
|
|
891
|
+
} finally {
|
|
892
|
+
await srv.shutdown();
|
|
893
|
+
}
|
|
894
|
+
});
|
|
895
|
+
|
|
896
|
+
test('requestHandleAdd supports validator options', async () => {
|
|
897
|
+
const port = 12378;
|
|
898
|
+
const srv = new ApiSrv({ port });
|
|
899
|
+
srv.requestHandleAdd('POST', '/items/{itemId}', (r) => r.jsonResponse({
|
|
900
|
+
params: r.params,
|
|
901
|
+
pathParams: r.pathParams,
|
|
902
|
+
bodyParams: r.bodyParams,
|
|
903
|
+
urlParams: r.urlParams
|
|
904
|
+
}), {
|
|
905
|
+
pathParamsValidator: (pathParams) => ({ itemId: Number(pathParams.itemId) }),
|
|
906
|
+
bodyParamsValidator: async (bodyParams) => ({
|
|
907
|
+
name: bodyParams.name.toUpperCase(),
|
|
908
|
+
count: Number(bodyParams.count)
|
|
909
|
+
}),
|
|
910
|
+
paramsValidator: (params) => ({ ...params, validated: true })
|
|
911
|
+
});
|
|
912
|
+
try {
|
|
913
|
+
const res = await httpRequest(port, {
|
|
914
|
+
method: 'POST',
|
|
915
|
+
path: '/items/5',
|
|
916
|
+
headers: { 'Content-Type': 'application/json' },
|
|
917
|
+
body: JSON.stringify({ name: 'foo', count: '3' })
|
|
918
|
+
});
|
|
919
|
+
assert.strictEqual(res.status, 200);
|
|
920
|
+
assert.deepStrictEqual(JSON.parse(res.data), {
|
|
921
|
+
params: { name: 'FOO', count: 3, itemId: 5, validated: true },
|
|
922
|
+
pathParams: { itemId: 5 },
|
|
923
|
+
bodyParams: { name: 'FOO', count: 3 },
|
|
924
|
+
urlParams: {}
|
|
925
|
+
});
|
|
926
|
+
} finally {
|
|
927
|
+
await srv.shutdown();
|
|
928
|
+
}
|
|
929
|
+
});
|
|
930
|
+
|
|
931
|
+
test('requestHandleAdd enforces path template constraints', async () => {
|
|
932
|
+
const port = 12399;
|
|
933
|
+
const srv = new ApiSrv({ port });
|
|
934
|
+
try {
|
|
935
|
+
assert.throws(() => {
|
|
936
|
+
srv.requestHandleAdd('GET', '/bad/{1foo}', () => {});
|
|
937
|
+
}, /Invalid path parameter name/);
|
|
938
|
+
|
|
939
|
+
assert.throws(() => {
|
|
940
|
+
srv.requestHandleAdd('GET', '/bad/[parts:0]', () => {});
|
|
941
|
+
}, /Invalid minimum length/);
|
|
942
|
+
} finally {
|
|
943
|
+
await srv.shutdown();
|
|
944
|
+
}
|
|
945
|
+
});
|
|
946
|
+
|
|
947
|
+
test('authentication runs before parameter parsing', async () => {
|
|
948
|
+
const port = 12379;
|
|
949
|
+
let authSnapshot;
|
|
950
|
+
let handlerSnapshot;
|
|
951
|
+
const srv = new ApiSrv({
|
|
952
|
+
port,
|
|
953
|
+
requestHandlers: {
|
|
954
|
+
POST: {
|
|
955
|
+
'/items/{itemId}': {
|
|
956
|
+
callback: (r) => {
|
|
957
|
+
const normalizedPath = r.pathParams === undefined ? undefined : { ...r.pathParams };
|
|
958
|
+
const normalizedUrl = r.urlParams === undefined ? undefined : { ...r.urlParams };
|
|
959
|
+
handlerSnapshot = {
|
|
960
|
+
bodyParams: r.bodyParams,
|
|
961
|
+
pathParams: normalizedPath,
|
|
962
|
+
urlParams: normalizedUrl,
|
|
963
|
+
params: r.params
|
|
964
|
+
};
|
|
965
|
+
r.jsonResponse({ ok: true });
|
|
966
|
+
}
|
|
967
|
+
}
|
|
968
|
+
}
|
|
969
|
+
},
|
|
970
|
+
authCallback: (r) => {
|
|
971
|
+
authSnapshot = {
|
|
972
|
+
bodyParams: r.bodyParams,
|
|
973
|
+
pathParams: r.pathParams,
|
|
974
|
+
urlParams: r.urlParams,
|
|
975
|
+
params: r.params
|
|
976
|
+
};
|
|
977
|
+
return true;
|
|
978
|
+
}
|
|
979
|
+
});
|
|
980
|
+
try {
|
|
981
|
+
const res = await httpRequest(port, {
|
|
982
|
+
method: 'POST',
|
|
983
|
+
path: '/items/10',
|
|
984
|
+
headers: { 'Content-Type': 'application/json' },
|
|
985
|
+
body: JSON.stringify({ name: 'foo' })
|
|
986
|
+
});
|
|
987
|
+
assert.strictEqual(res.status, 200);
|
|
988
|
+
assert.deepStrictEqual(authSnapshot, {
|
|
989
|
+
bodyParams: undefined,
|
|
990
|
+
pathParams: undefined,
|
|
991
|
+
urlParams: undefined,
|
|
992
|
+
params: undefined
|
|
993
|
+
});
|
|
994
|
+
assert.deepStrictEqual(handlerSnapshot, {
|
|
995
|
+
bodyParams: { name: 'foo' },
|
|
996
|
+
pathParams: { itemId: '10' },
|
|
997
|
+
urlParams: {},
|
|
998
|
+
params: { name: 'foo', itemId: '10' }
|
|
999
|
+
});
|
|
1000
|
+
} finally {
|
|
1001
|
+
await srv.shutdown();
|
|
1002
|
+
}
|
|
1003
|
+
});
|
|
1004
|
+
|
|
1005
|
+
test('authentication failure skips parameter parsing', async () => {
|
|
1006
|
+
const port = 12380;
|
|
1007
|
+
let authCalls = 0;
|
|
1008
|
+
let authSnapshot;
|
|
1009
|
+
const srv = new ApiSrv({
|
|
1010
|
+
port,
|
|
1011
|
+
requestHandlers: {
|
|
1012
|
+
POST: {
|
|
1013
|
+
'/items': {
|
|
1014
|
+
callback: () => {
|
|
1015
|
+
throw new Error('handler must not be invoked');
|
|
1016
|
+
}
|
|
1017
|
+
}
|
|
1018
|
+
}
|
|
1019
|
+
},
|
|
1020
|
+
authCallback: (r) => {
|
|
1021
|
+
authCalls++;
|
|
1022
|
+
authSnapshot = {
|
|
1023
|
+
bodyParams: r.bodyParams,
|
|
1024
|
+
pathParams: r.pathParams,
|
|
1025
|
+
urlParams: r.urlParams,
|
|
1026
|
+
params: r.params
|
|
1027
|
+
};
|
|
1028
|
+
r.res.writeHead(401, { 'Content-Type': 'text/plain' });
|
|
1029
|
+
r.res.end('unauthorized');
|
|
1030
|
+
return false;
|
|
1031
|
+
}
|
|
1032
|
+
});
|
|
1033
|
+
try {
|
|
1034
|
+
const res = await httpRequest(port, {
|
|
1035
|
+
method: 'POST',
|
|
1036
|
+
path: '/items',
|
|
1037
|
+
headers: { 'Content-Type': 'application/json' },
|
|
1038
|
+
body: '{'
|
|
1039
|
+
});
|
|
1040
|
+
assert.strictEqual(res.status, 401);
|
|
1041
|
+
assert.strictEqual(res.data, 'unauthorized');
|
|
1042
|
+
assert.strictEqual(authCalls, 1);
|
|
1043
|
+
assert.deepStrictEqual(authSnapshot, {
|
|
1044
|
+
bodyParams: undefined,
|
|
1045
|
+
pathParams: undefined,
|
|
1046
|
+
urlParams: undefined,
|
|
1047
|
+
params: undefined
|
|
1048
|
+
});
|
|
109
1049
|
} finally {
|
|
110
1050
|
await srv.shutdown();
|
|
111
1051
|
}
|
|
@@ -173,7 +1113,9 @@ test('body read timeout returns 408', async () => {
|
|
|
173
1113
|
req.write('123'); // intentionally never calling end to trigger timeout
|
|
174
1114
|
});
|
|
175
1115
|
assert.strictEqual(res.status, 408);
|
|
176
|
-
|
|
1116
|
+
const body = JSON.parse(res.data);
|
|
1117
|
+
assert.strictEqual(body.code, 408);
|
|
1118
|
+
assert.strictEqual(body.message, 'Request Timeout');
|
|
177
1119
|
} finally {
|
|
178
1120
|
await srv.shutdown();
|
|
179
1121
|
}
|
|
@@ -260,3 +1202,621 @@ test('rejects unsupported charset parameter', async () => {
|
|
|
260
1202
|
}
|
|
261
1203
|
});
|
|
262
1204
|
|
|
1205
|
+
|
|
1206
|
+
test('a __proto__ parameter is an own property and does not replace the prototype', async () => {
|
|
1207
|
+
const port = 12400;
|
|
1208
|
+
const srv = new ApiSrv({
|
|
1209
|
+
port,
|
|
1210
|
+
callback: (r) => r.jsonResponse({
|
|
1211
|
+
inherited: r.params.injected,
|
|
1212
|
+
ownProto: Object.prototype.hasOwnProperty.call(r.params, '__proto__'),
|
|
1213
|
+
plainPrototype: Object.getPrototypeOf(r.params) === Object.prototype,
|
|
1214
|
+
keys: Object.keys(r.params)
|
|
1215
|
+
})
|
|
1216
|
+
});
|
|
1217
|
+
try {
|
|
1218
|
+
const res = await httpRequest(port, {
|
|
1219
|
+
method: 'POST',
|
|
1220
|
+
path: '/',
|
|
1221
|
+
headers: { 'Content-Type': 'application/json' },
|
|
1222
|
+
body: '{"__proto__": {"injected": "yes"}, "a": 1}'
|
|
1223
|
+
});
|
|
1224
|
+
assert.strictEqual(res.status, 200);
|
|
1225
|
+
assert.deepStrictEqual(JSON.parse(res.data), {
|
|
1226
|
+
ownProto: true,
|
|
1227
|
+
plainPrototype: true,
|
|
1228
|
+
keys: ['__proto__', 'a']
|
|
1229
|
+
});
|
|
1230
|
+
} finally {
|
|
1231
|
+
await srv.shutdown();
|
|
1232
|
+
}
|
|
1233
|
+
});
|
|
1234
|
+
|
|
1235
|
+
test('requestHandlers reject __proto__ as a path parameter name', () => {
|
|
1236
|
+
for (const path of ['/a/{__proto__}', '/a/[__proto__]', '/a/[__proto__:2]']) {
|
|
1237
|
+
assert.throws(() => new ApiSrv({
|
|
1238
|
+
port: 12401,
|
|
1239
|
+
requestHandlers: { GET: { [path]: () => {} } }
|
|
1240
|
+
}), /Invalid path parameter name "__proto__"/);
|
|
1241
|
+
}
|
|
1242
|
+
});
|
|
1243
|
+
|
|
1244
|
+
test('rejectDangerousParamNames rejects reserved names in body and query', async () => {
|
|
1245
|
+
const port = 12402;
|
|
1246
|
+
let called = 0;
|
|
1247
|
+
const srv = new ApiSrv({
|
|
1248
|
+
port,
|
|
1249
|
+
rejectDangerousParamNames: true,
|
|
1250
|
+
callback: (r) => { called++; return r.jsonResponse({ ok: true }); }
|
|
1251
|
+
});
|
|
1252
|
+
try {
|
|
1253
|
+
for (const body of ['{"__proto__": {"a": 1}}', '{"a": {"b": [{"constructor": 1}]}}', '{"prototype": 1}']) {
|
|
1254
|
+
const res = await httpRequest(port, {
|
|
1255
|
+
method: 'POST',
|
|
1256
|
+
path: '/',
|
|
1257
|
+
headers: { 'Content-Type': 'application/json' },
|
|
1258
|
+
body
|
|
1259
|
+
});
|
|
1260
|
+
assert.strictEqual(res.status, 400, body);
|
|
1261
|
+
assert.match(JSON.parse(res.data).message, /Reserved parameter name ".*" in request body/);
|
|
1262
|
+
}
|
|
1263
|
+
let res = await httpRequest(port, { method: 'GET', path: '/?__proto__=1' });
|
|
1264
|
+
assert.strictEqual(res.status, 400);
|
|
1265
|
+
assert.match(JSON.parse(res.data).message, /Reserved parameter name "__proto__" in query string/);
|
|
1266
|
+
res = await httpRequest(port, {
|
|
1267
|
+
method: 'POST',
|
|
1268
|
+
path: '/',
|
|
1269
|
+
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
|
1270
|
+
body: 'a=1&constructor=2'
|
|
1271
|
+
});
|
|
1272
|
+
assert.strictEqual(res.status, 400);
|
|
1273
|
+
assert.strictEqual(called, 0);
|
|
1274
|
+
res = await httpRequest(port, {
|
|
1275
|
+
method: 'POST',
|
|
1276
|
+
path: '/',
|
|
1277
|
+
headers: { 'Content-Type': 'application/json' },
|
|
1278
|
+
body: '{"a": {"proto": 1, "constructors": [2]}}'
|
|
1279
|
+
});
|
|
1280
|
+
assert.strictEqual(res.status, 200);
|
|
1281
|
+
assert.strictEqual(called, 1);
|
|
1282
|
+
} finally {
|
|
1283
|
+
await srv.shutdown();
|
|
1284
|
+
}
|
|
1285
|
+
});
|
|
1286
|
+
|
|
1287
|
+
test('reserved parameter names are accepted by default', async () => {
|
|
1288
|
+
const port = 12403;
|
|
1289
|
+
const srv = new ApiSrv({
|
|
1290
|
+
port,
|
|
1291
|
+
callback: (r) => r.jsonResponse({ keys: Object.keys(r.params) })
|
|
1292
|
+
});
|
|
1293
|
+
try {
|
|
1294
|
+
const res = await httpRequest(port, {
|
|
1295
|
+
method: 'POST',
|
|
1296
|
+
path: '/',
|
|
1297
|
+
headers: { 'Content-Type': 'application/json' },
|
|
1298
|
+
body: '{"constructor": 1, "prototype": 2}'
|
|
1299
|
+
});
|
|
1300
|
+
assert.strictEqual(res.status, 200);
|
|
1301
|
+
assert.deepStrictEqual(JSON.parse(res.data), { keys: ['constructor', 'prototype'] });
|
|
1302
|
+
} finally {
|
|
1303
|
+
await srv.shutdown();
|
|
1304
|
+
}
|
|
1305
|
+
});
|
|
1306
|
+
|
|
1307
|
+
test('requireObjectBody rejects JSON array bodies', async () => {
|
|
1308
|
+
const port = 12404;
|
|
1309
|
+
const strict = new ApiSrv({
|
|
1310
|
+
port,
|
|
1311
|
+
requireObjectBody: true,
|
|
1312
|
+
callback: (r) => r.jsonResponse({ keys: Object.keys(r.params) })
|
|
1313
|
+
});
|
|
1314
|
+
const lenient = new ApiSrv({
|
|
1315
|
+
port: port + 1,
|
|
1316
|
+
callback: (r) => r.jsonResponse({ keys: Object.keys(r.params) })
|
|
1317
|
+
});
|
|
1318
|
+
try {
|
|
1319
|
+
const request = (p, body) => httpRequest(p, {
|
|
1320
|
+
method: 'POST',
|
|
1321
|
+
path: '/',
|
|
1322
|
+
headers: { 'Content-Type': 'application/json' },
|
|
1323
|
+
body
|
|
1324
|
+
});
|
|
1325
|
+
let res = await request(port, '["a", "b"]');
|
|
1326
|
+
assert.strictEqual(res.status, 400);
|
|
1327
|
+
assert.deepStrictEqual(JSON.parse(res.data), { code: 400, message: 'Bad Request (JSON body must be an object)' });
|
|
1328
|
+
res = await request(port, '{"a": 1}');
|
|
1329
|
+
assert.strictEqual(res.status, 200);
|
|
1330
|
+
assert.deepStrictEqual(JSON.parse(res.data), { keys: ['a'] });
|
|
1331
|
+
// The default is unchanged: array items become parameters "0", "1", ...
|
|
1332
|
+
res = await request(port + 1, '["a", "b"]');
|
|
1333
|
+
assert.strictEqual(res.status, 200);
|
|
1334
|
+
assert.deepStrictEqual(JSON.parse(res.data), { keys: ['0', '1'] });
|
|
1335
|
+
} finally {
|
|
1336
|
+
await strict.shutdown();
|
|
1337
|
+
await lenient.shutdown();
|
|
1338
|
+
}
|
|
1339
|
+
});
|
|
1340
|
+
|
|
1341
|
+
test('errorCallback shapes validator errors and receives the cause', async () => {
|
|
1342
|
+
const port = 12406;
|
|
1343
|
+
const seen = [];
|
|
1344
|
+
const srv = new ApiSrv({
|
|
1345
|
+
port,
|
|
1346
|
+
errorCallback: (e) => {
|
|
1347
|
+
seen.push({ code: e.code, message: e.message, detail: e.detail, source: e.source, stage: e.stage,
|
|
1348
|
+
cause: e.cause ? e.cause.message : undefined, url: e.request.url, method: e.request.method });
|
|
1349
|
+
if (e.source !== 'validator') {
|
|
1350
|
+
return false;
|
|
1351
|
+
}
|
|
1352
|
+
e.request.jsonResponse({ status: 'error', problems: e.cause.problems }, 422);
|
|
1353
|
+
return true;
|
|
1354
|
+
},
|
|
1355
|
+
requestHandlers: {
|
|
1356
|
+
POST: {
|
|
1357
|
+
'/items': {
|
|
1358
|
+
callback: (r) => r.jsonResponse({ ok: true }),
|
|
1359
|
+
options: {
|
|
1360
|
+
paramsValidator: (params) => {
|
|
1361
|
+
if (params.a !== 1) {
|
|
1362
|
+
const err = new Error('a must be 1');
|
|
1363
|
+
err.problems = [{ path: '/a', reason: 'const' }];
|
|
1364
|
+
throw err;
|
|
1365
|
+
}
|
|
1366
|
+
return params;
|
|
1367
|
+
}
|
|
1368
|
+
}
|
|
1369
|
+
}
|
|
1370
|
+
}
|
|
1371
|
+
}
|
|
1372
|
+
});
|
|
1373
|
+
try {
|
|
1374
|
+
let res = await httpRequest(port, {
|
|
1375
|
+
method: 'POST',
|
|
1376
|
+
path: '/items',
|
|
1377
|
+
headers: { 'Content-Type': 'application/json' },
|
|
1378
|
+
body: '{"a": 2}'
|
|
1379
|
+
});
|
|
1380
|
+
assert.strictEqual(res.status, 422);
|
|
1381
|
+
assert.deepStrictEqual(JSON.parse(res.data), { status: 'error', problems: [{ path: '/a', reason: 'const' }] });
|
|
1382
|
+
assert.deepStrictEqual(seen.pop(), {
|
|
1383
|
+
code: 400,
|
|
1384
|
+
message: 'Bad Request (a must be 1)',
|
|
1385
|
+
detail: 'a must be 1',
|
|
1386
|
+
source: 'validator',
|
|
1387
|
+
stage: 'request parameters',
|
|
1388
|
+
cause: 'a must be 1',
|
|
1389
|
+
url: '/items',
|
|
1390
|
+
method: 'POST'
|
|
1391
|
+
});
|
|
1392
|
+
res = await httpRequest(port, {
|
|
1393
|
+
method: 'POST',
|
|
1394
|
+
path: '/items',
|
|
1395
|
+
headers: { 'Content-Type': 'application/json' },
|
|
1396
|
+
body: '{"a": 1}'
|
|
1397
|
+
});
|
|
1398
|
+
assert.strictEqual(res.status, 200);
|
|
1399
|
+
assert.strictEqual(seen.length, 0);
|
|
1400
|
+
} finally {
|
|
1401
|
+
await srv.shutdown();
|
|
1402
|
+
}
|
|
1403
|
+
});
|
|
1404
|
+
|
|
1405
|
+
test('errorCallback sees router, parser and handler errors and may leave the default', async () => {
|
|
1406
|
+
const port = 12407;
|
|
1407
|
+
const seen = [];
|
|
1408
|
+
const srv = new ApiSrv({
|
|
1409
|
+
port,
|
|
1410
|
+
errorCallback: (e) => {
|
|
1411
|
+
seen.push([e.code, e.source, e.message]);
|
|
1412
|
+
return false;
|
|
1413
|
+
},
|
|
1414
|
+
requestHandlers: {
|
|
1415
|
+
GET: { '/known': (r) => r.jsonResponse({ ok: true }), '/boom': () => { throw new Error('boom'); } },
|
|
1416
|
+
POST: { '/known': (r) => r.jsonResponse({ ok: true }) }
|
|
1417
|
+
}
|
|
1418
|
+
});
|
|
1419
|
+
try {
|
|
1420
|
+
let res = await httpRequest(port, { method: 'GET', path: '/unknown' });
|
|
1421
|
+
assert.strictEqual(res.status, 404);
|
|
1422
|
+
assert.deepStrictEqual(JSON.parse(res.data), { message: 'Not Found', code: 404 });
|
|
1423
|
+
res = await httpRequest(port, { method: 'DELETE', path: '/known' });
|
|
1424
|
+
assert.strictEqual(res.status, 405);
|
|
1425
|
+
assert.deepStrictEqual(JSON.parse(res.data), { message: 'Method Not Allowed', code: 405 });
|
|
1426
|
+
res = await httpRequest(port, {
|
|
1427
|
+
method: 'POST',
|
|
1428
|
+
path: '/known',
|
|
1429
|
+
headers: { 'Content-Type': 'application/json' },
|
|
1430
|
+
body: '{not json'
|
|
1431
|
+
});
|
|
1432
|
+
assert.strictEqual(res.status, 400);
|
|
1433
|
+
assert.deepStrictEqual(JSON.parse(res.data), { code: 400, message: 'Bad Request (Unable to parse JSON query parameters)' });
|
|
1434
|
+
res = await httpRequest(port, { method: 'GET', path: '/boom' });
|
|
1435
|
+
assert.strictEqual(res.status, 500);
|
|
1436
|
+
assert.deepStrictEqual(JSON.parse(res.data), { code: 500, message: 'Internal Server Error' });
|
|
1437
|
+
assert.deepStrictEqual(seen, [
|
|
1438
|
+
[404, 'router', 'Not Found'],
|
|
1439
|
+
[405, 'router', 'Method Not Allowed'],
|
|
1440
|
+
[400, 'parser', 'Bad Request (Unable to parse JSON query parameters)'],
|
|
1441
|
+
[500, 'handler', 'Internal Server Error']
|
|
1442
|
+
]);
|
|
1443
|
+
} finally {
|
|
1444
|
+
await srv.shutdown();
|
|
1445
|
+
}
|
|
1446
|
+
});
|
|
1447
|
+
|
|
1448
|
+
test('errorCallback can be asynchronous, and a failing one falls back to the default', async () => {
|
|
1449
|
+
const port = 12408;
|
|
1450
|
+
let mode = 'async';
|
|
1451
|
+
const srv = new ApiSrv({
|
|
1452
|
+
port,
|
|
1453
|
+
errorCallback: async (e) => {
|
|
1454
|
+
if (mode === 'throw') {
|
|
1455
|
+
throw new Error('hook failure');
|
|
1456
|
+
}
|
|
1457
|
+
if (mode === 'decline') {
|
|
1458
|
+
return undefined;
|
|
1459
|
+
}
|
|
1460
|
+
await new Promise((resolve) => setTimeout(resolve, 5));
|
|
1461
|
+
e.res.writeHead(e.code, { 'Content-Type': 'text/plain' });
|
|
1462
|
+
e.res.end(`custom ${e.code} ${e.source}`);
|
|
1463
|
+
return true;
|
|
1464
|
+
}
|
|
1465
|
+
});
|
|
1466
|
+
try {
|
|
1467
|
+
let res = await httpRequest(port, { method: 'GET', path: '/missing' });
|
|
1468
|
+
assert.strictEqual(res.status, 404);
|
|
1469
|
+
assert.strictEqual(res.data, 'custom 404 router');
|
|
1470
|
+
for (mode of ['throw', 'decline']) {
|
|
1471
|
+
res = await httpRequest(port, { method: 'GET', path: '/missing' });
|
|
1472
|
+
assert.strictEqual(res.status, 404, mode);
|
|
1473
|
+
assert.deepStrictEqual(JSON.parse(res.data), { message: 'Not Found', code: 404 }, mode);
|
|
1474
|
+
}
|
|
1475
|
+
} finally {
|
|
1476
|
+
await srv.shutdown();
|
|
1477
|
+
}
|
|
1478
|
+
});
|
|
1479
|
+
|
|
1480
|
+
test('errorCallback handles body size and unsupported method errors', async () => {
|
|
1481
|
+
const port = 12409;
|
|
1482
|
+
const seen = [];
|
|
1483
|
+
const srv = new ApiSrv({
|
|
1484
|
+
port,
|
|
1485
|
+
maxBodySize: 8,
|
|
1486
|
+
errorCallback: (e) => {
|
|
1487
|
+
seen.push([e.code, e.source]);
|
|
1488
|
+
e.res.writeHead(e.code, { 'Content-Type': 'application/json' });
|
|
1489
|
+
e.res.end(JSON.stringify({ custom: e.code }));
|
|
1490
|
+
return true;
|
|
1491
|
+
},
|
|
1492
|
+
callback: (r) => r.jsonResponse({ ok: true })
|
|
1493
|
+
});
|
|
1494
|
+
try {
|
|
1495
|
+
let res = await httpRequest(port, {
|
|
1496
|
+
method: 'POST',
|
|
1497
|
+
path: '/',
|
|
1498
|
+
headers: { 'Content-Type': 'application/json' },
|
|
1499
|
+
body: JSON.stringify({ a: 'a long enough value' })
|
|
1500
|
+
});
|
|
1501
|
+
assert.strictEqual(res.status, 413);
|
|
1502
|
+
assert.deepStrictEqual(JSON.parse(res.data), { custom: 413 });
|
|
1503
|
+
res = await httpRequest(port, { method: 'PATCH', path: '/' });
|
|
1504
|
+
assert.strictEqual(res.status, 405);
|
|
1505
|
+
assert.deepStrictEqual(JSON.parse(res.data), { custom: 405 });
|
|
1506
|
+
assert.deepStrictEqual(seen, [[413, 'limit'], [405, 'request']]);
|
|
1507
|
+
} finally {
|
|
1508
|
+
await srv.shutdown();
|
|
1509
|
+
}
|
|
1510
|
+
});
|
|
1511
|
+
|
|
1512
|
+
test('errorResponse from a handler does not go through errorCallback', async () => {
|
|
1513
|
+
const port = 12410;
|
|
1514
|
+
let hookCalls = 0;
|
|
1515
|
+
const srv = new ApiSrv({
|
|
1516
|
+
port,
|
|
1517
|
+
errorCallback: () => { hookCalls++; return false; },
|
|
1518
|
+
callback: (r) => r.errorResponse(409, 'ignored detail')
|
|
1519
|
+
});
|
|
1520
|
+
try {
|
|
1521
|
+
const res = await httpRequest(port, { method: 'GET', path: '/' });
|
|
1522
|
+
assert.strictEqual(res.status, 409);
|
|
1523
|
+
assert.deepStrictEqual(JSON.parse(res.data), { code: 409, message: 'Conflict' });
|
|
1524
|
+
assert.strictEqual(hookCalls, 0);
|
|
1525
|
+
} finally {
|
|
1526
|
+
await srv.shutdown();
|
|
1527
|
+
}
|
|
1528
|
+
});
|
|
1529
|
+
|
|
1530
|
+
test('pathRewrite maps prefixed paths to one handler and keeps the original', async () => {
|
|
1531
|
+
const port = 12411;
|
|
1532
|
+
const srv = new ApiSrv({
|
|
1533
|
+
port,
|
|
1534
|
+
pathRewrite: (path) => path.replace(/^\/(svc\/)?(hook\/)?/, '/'),
|
|
1535
|
+
requestHandlers: {
|
|
1536
|
+
GET: {
|
|
1537
|
+
'/items/{id}': (r) => r.jsonResponse({ url: r.url, originalUrl: r.originalUrl, id: r.params.id })
|
|
1538
|
+
}
|
|
1539
|
+
},
|
|
1540
|
+
callback: (r) => r.jsonResponse({ fallback: r.url, originalUrl: r.originalUrl })
|
|
1541
|
+
});
|
|
1542
|
+
try {
|
|
1543
|
+
for (const path of ['/items/7', '/hook/items/7', '/svc/hook/items/7']) {
|
|
1544
|
+
const res = await httpRequest(port, { method: 'GET', path: path + '?x=1' });
|
|
1545
|
+
assert.strictEqual(res.status, 200, path);
|
|
1546
|
+
assert.deepStrictEqual(JSON.parse(res.data), { url: '/items/7', originalUrl: path, id: '7' });
|
|
1547
|
+
}
|
|
1548
|
+
const res = await httpRequest(port, { method: 'GET', path: '/svc/other' });
|
|
1549
|
+
assert.deepStrictEqual(JSON.parse(res.data), { fallback: '/other', originalUrl: '/svc/other' });
|
|
1550
|
+
} finally {
|
|
1551
|
+
await srv.shutdown();
|
|
1552
|
+
}
|
|
1553
|
+
});
|
|
1554
|
+
|
|
1555
|
+
test('pathRewrite results are checked', async () => {
|
|
1556
|
+
const port = 12412;
|
|
1557
|
+
let mode = 'keep';
|
|
1558
|
+
let called = 0;
|
|
1559
|
+
const srv = new ApiSrv({
|
|
1560
|
+
port,
|
|
1561
|
+
pathRewrite: (path) => {
|
|
1562
|
+
switch (mode) {
|
|
1563
|
+
case 'keep':
|
|
1564
|
+
return undefined;
|
|
1565
|
+
case 'relative':
|
|
1566
|
+
return 'not-a-path';
|
|
1567
|
+
case 'throw':
|
|
1568
|
+
throw new Error('rewrite failure');
|
|
1569
|
+
case 'dangerous':
|
|
1570
|
+
return '/a/../b';
|
|
1571
|
+
}
|
|
1572
|
+
},
|
|
1573
|
+
callback: (r) => { called++; return r.jsonResponse({ url: r.url }); }
|
|
1574
|
+
});
|
|
1575
|
+
try {
|
|
1576
|
+
let res = await httpRequest(port, { method: 'GET', path: '/same' });
|
|
1577
|
+
assert.strictEqual(res.status, 200);
|
|
1578
|
+
assert.deepStrictEqual(JSON.parse(res.data), { url: '/same' });
|
|
1579
|
+
for (mode of ['relative', 'throw']) {
|
|
1580
|
+
res = await httpRequest(port, { method: 'GET', path: '/same' });
|
|
1581
|
+
assert.strictEqual(res.status, 500, mode);
|
|
1582
|
+
}
|
|
1583
|
+
mode = 'dangerous';
|
|
1584
|
+
res = await httpRequest(port, { method: 'GET', path: '/same' });
|
|
1585
|
+
assert.strictEqual(res.status, 400);
|
|
1586
|
+
assert.strictEqual(called, 1);
|
|
1587
|
+
} finally {
|
|
1588
|
+
await srv.shutdown();
|
|
1589
|
+
}
|
|
1590
|
+
});
|
|
1591
|
+
|
|
1592
|
+
test('handler authCallback runs after the server authCallback and before parameter parsing', async () => {
|
|
1593
|
+
const port = 12413;
|
|
1594
|
+
const order = [];
|
|
1595
|
+
const srv = new ApiSrv({
|
|
1596
|
+
port,
|
|
1597
|
+
authCallback: (r) => {
|
|
1598
|
+
order.push('server');
|
|
1599
|
+
return true;
|
|
1600
|
+
},
|
|
1601
|
+
requestHandlers: {
|
|
1602
|
+
GET: {
|
|
1603
|
+
'/private/{id}': {
|
|
1604
|
+
callback: (r) => r.jsonResponse({ id: r.params.id, handler: r.handler }),
|
|
1605
|
+
options: {
|
|
1606
|
+
meta: { name: 'private-item', scopes: ['read'] },
|
|
1607
|
+
authCallback: async (r) => {
|
|
1608
|
+
order.push(`handler:${r.handler.path}:${r.handler.meta.name}:${r.params === undefined}`);
|
|
1609
|
+
if (r.headers.authorization !== 'Bearer route-token') {
|
|
1610
|
+
r.jsonResponse({ denied: true }, 403);
|
|
1611
|
+
return false;
|
|
1612
|
+
}
|
|
1613
|
+
return true;
|
|
1614
|
+
}
|
|
1615
|
+
}
|
|
1616
|
+
},
|
|
1617
|
+
'/public': (r) => r.jsonResponse({ handler: r.handler })
|
|
1618
|
+
}
|
|
1619
|
+
},
|
|
1620
|
+
callback: (r) => r.jsonResponse({ handler: r.handler === undefined ? 'none' : r.handler })
|
|
1621
|
+
});
|
|
1622
|
+
try {
|
|
1623
|
+
let res = await httpRequest(port, { method: 'GET', path: '/private/5' });
|
|
1624
|
+
assert.strictEqual(res.status, 403);
|
|
1625
|
+
assert.deepStrictEqual(JSON.parse(res.data), { denied: true });
|
|
1626
|
+
res = await httpRequest(port, { method: 'GET', path: '/private/5', headers: { Authorization: 'Bearer route-token' } });
|
|
1627
|
+
assert.strictEqual(res.status, 200);
|
|
1628
|
+
assert.deepStrictEqual(JSON.parse(res.data), {
|
|
1629
|
+
id: '5',
|
|
1630
|
+
handler: { method: 'GET', path: '/private/{id}', meta: { name: 'private-item', scopes: ['read'] } }
|
|
1631
|
+
});
|
|
1632
|
+
assert.deepStrictEqual(order, [
|
|
1633
|
+
'server', 'handler:/private/{id}:private-item:true',
|
|
1634
|
+
'server', 'handler:/private/{id}:private-item:true'
|
|
1635
|
+
]);
|
|
1636
|
+
res = await httpRequest(port, { method: 'GET', path: '/public' });
|
|
1637
|
+
assert.deepStrictEqual(JSON.parse(res.data), { handler: { method: 'GET', path: '/public' } });
|
|
1638
|
+
res = await httpRequest(port, { method: 'GET', path: '/elsewhere' });
|
|
1639
|
+
assert.deepStrictEqual(JSON.parse(res.data), { handler: 'none' });
|
|
1640
|
+
} finally {
|
|
1641
|
+
await srv.shutdown();
|
|
1642
|
+
}
|
|
1643
|
+
});
|
|
1644
|
+
|
|
1645
|
+
test('handler authCallback is not called when the server authCallback rejects', async () => {
|
|
1646
|
+
const port = 12414;
|
|
1647
|
+
let handlerAuth = 0;
|
|
1648
|
+
const srv = new ApiSrv({
|
|
1649
|
+
port,
|
|
1650
|
+
authCallback: (r) => {
|
|
1651
|
+
r.jsonResponse({ denied: 'server' }, 401);
|
|
1652
|
+
return false;
|
|
1653
|
+
},
|
|
1654
|
+
requestHandlers: {
|
|
1655
|
+
GET: {
|
|
1656
|
+
'/x': {
|
|
1657
|
+
callback: (r) => r.jsonResponse({ ok: true }),
|
|
1658
|
+
options: { authCallback: () => { handlerAuth++; return true; } }
|
|
1659
|
+
}
|
|
1660
|
+
}
|
|
1661
|
+
}
|
|
1662
|
+
});
|
|
1663
|
+
try {
|
|
1664
|
+
const res = await httpRequest(port, { method: 'GET', path: '/x' });
|
|
1665
|
+
assert.strictEqual(res.status, 401);
|
|
1666
|
+
assert.strictEqual(handlerAuth, 0);
|
|
1667
|
+
} finally {
|
|
1668
|
+
await srv.shutdown();
|
|
1669
|
+
}
|
|
1670
|
+
});
|
|
1671
|
+
|
|
1672
|
+
test('handler options authCallback and meta are validated', () => {
|
|
1673
|
+
assert.throws(() => new ApiSrv({
|
|
1674
|
+
port: 12415,
|
|
1675
|
+
requestHandlers: { GET: { '/x': { callback: () => {}, options: { authCallback: 'nope' } } } }
|
|
1676
|
+
}), /authCallback must be a function for GET \/x/);
|
|
1677
|
+
assert.throws(() => new ApiSrv({
|
|
1678
|
+
port: 12415,
|
|
1679
|
+
requestHandlers: { GET: { '/x': { callback: () => {}, options: { unknownOption: 1 } } } }
|
|
1680
|
+
}), /Unsupported request handler option "unknownOption"/);
|
|
1681
|
+
});
|
|
1682
|
+
|
|
1683
|
+
test('requestHandlerList returns the registered handlers', async () => {
|
|
1684
|
+
const port = 12416;
|
|
1685
|
+
const srv = new ApiSrv({
|
|
1686
|
+
port,
|
|
1687
|
+
requestHandlers: {
|
|
1688
|
+
GET: {
|
|
1689
|
+
'/a': () => {},
|
|
1690
|
+
'/b/{id}': { callback: () => {}, options: { meta: 'b-item' } }
|
|
1691
|
+
},
|
|
1692
|
+
POST: { '/a': { callback: () => {}, options: { meta: { name: 'a-create' } } } }
|
|
1693
|
+
}
|
|
1694
|
+
});
|
|
1695
|
+
try {
|
|
1696
|
+
assert.deepStrictEqual(srv.requestHandlerList(), [
|
|
1697
|
+
{ method: 'GET', path: '/a', meta: undefined },
|
|
1698
|
+
{ method: 'GET', path: '/b/{id}', meta: 'b-item' },
|
|
1699
|
+
{ method: 'POST', path: '/a', meta: { name: 'a-create' } }
|
|
1700
|
+
]);
|
|
1701
|
+
srv.requestHandleAdd('DELETE', '/a', () => {});
|
|
1702
|
+
srv.requestHandleDelete('GET', '/a');
|
|
1703
|
+
assert.deepStrictEqual(srv.requestHandlerList().map((h) => `${h.method} ${h.path}`),
|
|
1704
|
+
['GET /b/{id}', 'POST /a', 'DELETE /a']);
|
|
1705
|
+
} finally {
|
|
1706
|
+
await srv.shutdown();
|
|
1707
|
+
}
|
|
1708
|
+
});
|
|
1709
|
+
|
|
1710
|
+
test('new constructor options are validated', () => {
|
|
1711
|
+
for (const [name, value] of [['errorCallback', 'x'], ['pathRewrite', 1], ['requireObjectBody', 'yes'],
|
|
1712
|
+
['rejectDangerousParamNames', 1]]) {
|
|
1713
|
+
assert.throws(() => new ApiSrv({ port: 12417, [name]: value }), new RegExp(`Bad ${name} for ApiSrv constructor`));
|
|
1714
|
+
}
|
|
1715
|
+
});
|
|
1716
|
+
|
|
1717
|
+
test('JSON responses and errors disable content type sniffing', async () => {
|
|
1718
|
+
const port = 12418;
|
|
1719
|
+
const srv = new ApiSrv({
|
|
1720
|
+
port,
|
|
1721
|
+
requestHandlers: { GET: { '/ok': (r) => r.jsonResponse({ ok: true }) } }
|
|
1722
|
+
});
|
|
1723
|
+
try {
|
|
1724
|
+
let res = await httpRequest(port, { method: 'GET', path: '/ok' });
|
|
1725
|
+
assert.strictEqual(res.headers['x-content-type-options'], 'nosniff');
|
|
1726
|
+
res = await httpRequest(port, { method: 'GET', path: '/missing' });
|
|
1727
|
+
assert.strictEqual(res.status, 404);
|
|
1728
|
+
assert.strictEqual(res.headers['x-content-type-options'], 'nosniff');
|
|
1729
|
+
res = await httpRequest(port, { method: 'GET', path: '/a//b' });
|
|
1730
|
+
assert.strictEqual(res.status, 400);
|
|
1731
|
+
assert.strictEqual(res.headers['x-content-type-options'], 'nosniff');
|
|
1732
|
+
} finally {
|
|
1733
|
+
await srv.shutdown();
|
|
1734
|
+
}
|
|
1735
|
+
});
|
|
1736
|
+
|
|
1737
|
+
test('a request target that is not a path matches no handler', async () => {
|
|
1738
|
+
const port = 12419;
|
|
1739
|
+
const raw = 'GET http://example.test/x/1 HTTP/1.1\r\nHost: example.test\r\nConnection: close\r\n\r\n';
|
|
1740
|
+
const srv = new ApiSrv({
|
|
1741
|
+
port,
|
|
1742
|
+
rejectDangerousPaths: false,
|
|
1743
|
+
requestHandlers: { GET: { '/x/{id}': (r) => r.jsonResponse({ ok: true }) } }
|
|
1744
|
+
});
|
|
1745
|
+
const strict = new ApiSrv({
|
|
1746
|
+
port: port + 20,
|
|
1747
|
+
requestHandlers: { GET: { '/x/{id}': (r) => r.jsonResponse({ ok: true }) } }
|
|
1748
|
+
});
|
|
1749
|
+
try {
|
|
1750
|
+
// Without the dangerous path check the matcher sees the absolute
|
|
1751
|
+
// URL: it matches nothing, and no longer fails with 500.
|
|
1752
|
+
assert.strictEqual(await rawRequest(port, raw), 404);
|
|
1753
|
+
// With the check (the default) the "//" of the URL is rejected.
|
|
1754
|
+
assert.strictEqual(await rawRequest(port + 20, raw), 400);
|
|
1755
|
+
} finally {
|
|
1756
|
+
await strict.shutdown();
|
|
1757
|
+
await srv.shutdown();
|
|
1758
|
+
}
|
|
1759
|
+
});
|
|
1760
|
+
|
|
1761
|
+
test('a body received in many chunks is assembled', async () => {
|
|
1762
|
+
const port = 12420;
|
|
1763
|
+
const srv = new ApiSrv({
|
|
1764
|
+
port,
|
|
1765
|
+
callback: (r) => r.jsonResponse({ length: r.params.value.length, bytes: r.requestPayloadBuffer.length })
|
|
1766
|
+
});
|
|
1767
|
+
try {
|
|
1768
|
+
const body = JSON.stringify({ value: 'x'.repeat(200000) });
|
|
1769
|
+
const res = await new Promise((resolve, reject) => {
|
|
1770
|
+
const req = http.request({ port, hostname: '127.0.0.1', method: 'POST', path: '/',
|
|
1771
|
+
headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(body) } },
|
|
1772
|
+
(r) => {
|
|
1773
|
+
let data = '';
|
|
1774
|
+
r.on('data', (d) => data += d);
|
|
1775
|
+
r.on('end', () => resolve({ status: r.statusCode, data }));
|
|
1776
|
+
});
|
|
1777
|
+
req.on('error', reject);
|
|
1778
|
+
for (let i = 0; i < body.length; i += 1000) {
|
|
1779
|
+
req.write(body.slice(i, i + 1000));
|
|
1780
|
+
}
|
|
1781
|
+
req.end();
|
|
1782
|
+
});
|
|
1783
|
+
assert.strictEqual(res.status, 200);
|
|
1784
|
+
assert.deepStrictEqual(JSON.parse(res.data), { length: 200000, bytes: Buffer.byteLength(body) });
|
|
1785
|
+
} finally {
|
|
1786
|
+
await srv.shutdown();
|
|
1787
|
+
}
|
|
1788
|
+
});
|
|
1789
|
+
|
|
1790
|
+
test('upgrade requests use pathRewrite and reject reserved query names', async () => {
|
|
1791
|
+
const port = 12421;
|
|
1792
|
+
const seen = [];
|
|
1793
|
+
const srv = new ApiSrv({
|
|
1794
|
+
port,
|
|
1795
|
+
rejectDangerousParamNames: true,
|
|
1796
|
+
pathRewrite: (path) => path.replace(/^\/svc\//, '/'),
|
|
1797
|
+
callback: (r) => r.jsonResponse({ ok: true }),
|
|
1798
|
+
upgradeCallback: (r) => {
|
|
1799
|
+
seen.push({ url: r.url, originalUrl: r.originalUrl, params: Object.assign({}, r.params) });
|
|
1800
|
+
r.s.end('HTTP/1.1 101 Switching Protocols\r\nConnection: close\r\n\r\n');
|
|
1801
|
+
return true;
|
|
1802
|
+
}
|
|
1803
|
+
});
|
|
1804
|
+
const upgrade = (path) => new Promise((resolve, reject) => {
|
|
1805
|
+
const socket = net.connect(port, '127.0.0.1');
|
|
1806
|
+
let data = '';
|
|
1807
|
+
socket.on('connect', () => socket.write(`GET ${path} HTTP/1.1\r\nHost: localhost\r\nConnection: Upgrade\r\nUpgrade: websocket\r\n\r\n`));
|
|
1808
|
+
socket.on('data', (d) => data += d.toString());
|
|
1809
|
+
socket.on('close', () => resolve(data));
|
|
1810
|
+
socket.on('error', reject);
|
|
1811
|
+
});
|
|
1812
|
+
try {
|
|
1813
|
+
let data = await upgrade('/svc/socket?a=1');
|
|
1814
|
+
assert.match(data, /^HTTP\/1\.1 101/);
|
|
1815
|
+
assert.deepStrictEqual(seen, [{ url: '/socket', originalUrl: '/svc/socket', params: { a: '1' } }]);
|
|
1816
|
+
data = await upgrade('/svc/socket?__proto__=1');
|
|
1817
|
+
assert.strictEqual(data, '');
|
|
1818
|
+
assert.strictEqual(seen.length, 1);
|
|
1819
|
+
} finally {
|
|
1820
|
+
await srv.shutdown();
|
|
1821
|
+
}
|
|
1822
|
+
});
|