tr-apisrv 2.1.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.
Files changed (4) hide show
  1. package/README.md +169 -1
  2. package/index.js +304 -51
  3. package/package.json +1 -1
  4. package/test/test.js +618 -0
package/test/test.js CHANGED
@@ -1202,3 +1202,621 @@ test('rejects unsupported charset parameter', async () => {
1202
1202
  }
1203
1203
  });
1204
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
+ });