@contrast/route-coverage 1.51.0 → 1.53.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.
@@ -1,553 +0,0 @@
1
- /*
2
- * Copyright: 2025 Contrast Security, Inc
3
- * Contact: support@contrastsecurity.com
4
- * License: Commercial
5
-
6
- * NOTICE: This Software and the patented inventions embodied within may only be
7
- * used as part of Contrast Security’s commercial offerings. Even though it is
8
- * made available through public repositories, use of this Software is subject to
9
- * the applicable End User Licensing Agreement found at
10
- * https://www.contrastsecurity.com/enduser-terms-0317a or as otherwise agreed
11
- * between Contrast Security and the End User. The Software may not be reverse
12
- * engineered, modified, repackaged, sold, redistributed or otherwise used in a
13
- * way not consistent with the End User License Agreement.
14
- */
15
- 'use strict';
16
-
17
- const { AsyncLocalStorage } = require('node:async_hooks');
18
- const {
19
- get,
20
- set,
21
- isString,
22
- Event,
23
- RouteType,
24
- primordials: {
25
- ArrayPrototypeJoin,
26
- StringPrototypeSubstring,
27
- StringPrototypeToLowerCase,
28
- StringPrototypeReplace,
29
- }
30
- } = require('@contrast/common');
31
- const { funcInfo } = require('@contrast/fn-inspect');
32
- const Core = require('@contrast/core/lib/ioc/core');
33
-
34
- const METHODS = [
35
- 'all',
36
- 'get',
37
- 'post',
38
- 'put',
39
- 'delete',
40
- 'patch',
41
- 'options',
42
- 'head',
43
- ];
44
- const componentName = 'routeCoverage.express5';
45
- const kMetaKey = Symbol('cs_meta');
46
- const enumerable = false;
47
-
48
- module.exports = Core.makeComponent({
49
- name: componentName,
50
- factory: (core) => new ExpressInstrumentation(core),
51
- });
52
-
53
- class ExpressInstrumentation {
54
- constructor(core) {
55
- // decorate
56
- set(core, componentName, this);
57
-
58
- this.core = core;
59
- this.methodScope = new AsyncLocalStorage();
60
- this.handleScope = new AsyncLocalStorage();
61
- }
62
-
63
- install() {
64
- const self = this;
65
- const { core, handleScope, methodScope } = this;
66
- const patchType = 'route-coverage-express';
67
- const name = 'express-5';
68
-
69
- //
70
- // discovery instrumentation
71
- //
72
-
73
- core.depHooks.resolve({ name: 'express', version: '5' }, (express) => {
74
- // wrap router and app methods in "method scope" to capture info to help build signatures.
75
- // express has a number of APIs that work at different levels of abstraction, and we need to patch
76
- // all of them. the scopes let us know what top-level APIs are being called by application code.
77
- [...METHODS, 'use', 'route'].forEach((method) => {
78
- // then setup app and router to run in method scopes
79
- core.patcher.patch(express.application, method, {
80
- name: `express.application.${method}`,
81
- patchType: `${patchType}-discovery`,
82
- around(next, data) {
83
- if (methodScope.getStore()) return next();
84
- return methodScope.run({ method, args: data.args, type: 'app' }, next);
85
- }
86
- });
87
-
88
- core.patcher.patch(express.Router.prototype, method, {
89
- name: `express.Router.prototype.${method}`,
90
- patchType: `${patchType}-discovery`,
91
- around(next, data) {
92
- if (methodScope.getStore()) return next();
93
- return methodScope.run({ method, args: data.args, type: 'router' }, next);
94
- }
95
- });
96
- });
97
-
98
- // app[method] and router[method] end up calling this
99
- // Append metadata to the created Route object at layer.route.
100
- // we also patch the returned Route's methods for building signatures
101
- core.patcher.patch(express.Router.prototype, 'route', {
102
- name: 'express.Route',
103
- patchType: `${patchType}-discovery`,
104
- post(data) {
105
- const { result } = data;
106
- const methodStore = methodScope.getStore();
107
- const meta = {
108
- paths: ExpressInstrumentation.normalizePaths(data.args[0]),
109
- method: methodStore?.method,
110
- type: methodStore?.type || 'route',
111
- };
112
-
113
- Object.defineProperty(result, kMetaKey, {
114
- enumerable,
115
- value: meta
116
- });
117
-
118
- // patch route instance methods we do that here when we have
119
- // todo move to prototype to help w/ memory
120
- METHODS.forEach((method) => {
121
- if (result[method]) {
122
- core.patcher.patch(result, method, {
123
- name: `express.Router.prototype.route${method}`,
124
- patchType: `${patchType}-discovery`,
125
- pre(data) {
126
- data._stackIdx = data.obj.stack?.length;
127
- },
128
- post(data) {
129
- if (data.obj.stack?.length > data._stackIdx) {
130
- for (let i = data._stackIdx; i < data.obj.stack.length; i++) {
131
- const layer = data.obj.stack[i];
132
- const methodStore = methodScope.getStore();
133
- const meta = {
134
- type: methodStore?.type || 'route',
135
- method: methodStore?.method == 'all' ? 'all' : method,
136
- };
137
-
138
- Object.defineProperty(layer, kMetaKey, {
139
- enumerable,
140
- value: meta,
141
- });
142
- }
143
- }
144
- },
145
- });
146
- }
147
- });
148
-
149
- return result;
150
- },
151
- });
152
-
153
- core.patcher.patch(express.Router.prototype, 'use', {
154
- name: `${name}.Router.prototype.use`,
155
- patchType: `${patchType}-discovery`,
156
- pre(data) {
157
- data._stackLength = data.obj.stack?.length;
158
- },
159
- post(data) {
160
- if (data.obj.stack.length > data._stackLength) {
161
- for (let i = data._stackLength; i < data.obj.stack.length; i++) {
162
- const layer = data.obj.stack[i];
163
- const paths = ExpressInstrumentation.normalizePaths(data.args[0]);
164
- const methodStore = methodScope.getStore();
165
- const meta = {
166
- paths,
167
- method: 'use',
168
- type: methodStore?.type || 'router',
169
- };
170
-
171
- if (layer) {
172
- Object.defineProperty(layer, kMetaKey, {
173
- enumerable: false,
174
- value: meta
175
- });
176
- }
177
- }
178
- }
179
- },
180
- });
181
-
182
- return core.patcher.patch(express, {
183
- name: 'express-5.application',
184
- patchType: `${patchType}-discovery`,
185
- post(data) {
186
- const app = data.result;
187
- core.messages.on(Event.SERVER_LISTENING, () => {
188
- if (!app.router.stack[0]) {
189
- core.logger.debug('no routes detected in express router stack');
190
- return;
191
- }
192
- self.handleDiscovery(app);
193
- });
194
- return app;
195
- }
196
- });
197
- });
198
-
199
- core.depHooks.resolve({ name: 'express', version: '5' }, (express) => {
200
- core.patcher.patch(express.application, 'handle', {
201
- name: 'express.application.handle',
202
- patchType: `${patchType}-discovery`,
203
- around(next, data) {
204
- // wrap request handling in "handle scope". the scope's store data
205
- // helps for building observation templates as routing occurs
206
- const store = {
207
- matchIdx: -1,
208
- templateSegments: [],
209
- };
210
- return handleScope.run(store, next);
211
- }
212
- });
213
- });
214
-
215
- //
216
- // observation instrumentation
217
- //
218
-
219
- // when Layer.match gets called, matchers functions run underneath. the API doesn't present a really clean
220
- // way to instrument, so we're using scopes. we reference the scope's store in the instrumented matcher
221
- // functions so we can correlate a matcher that succeeds to its corresponding route template segment.
222
- core.depHooks.resolve({ name: 'router', file: 'lib/layer.js', version: '2' }, (Layer) => {
223
- core.patcher.patch(Layer.prototype, 'match', {
224
- name: 'Layer.prototype.match',
225
- patchType: `${patchType}-observation`,
226
- pre(data) {
227
- data._store = handleScope.getStore();
228
- if (!data._store) return;
229
-
230
- // we check in post hook whether any matcher instrumentation reset this in scope.
231
- // matchers will set this to a number only if multiple matchers run and one succeeds.
232
- // use the index of that matcher to get associated template segment from the metadata.
233
- data._store.matcherIdx = null;
234
- // save reference to metadata source
235
- data[kMetaKey] = data.obj[kMetaKey] || data.obj.route?.[kMetaKey];
236
- },
237
- post(data) {
238
- // whenever a layer matches, save the corresponding
239
- // template segment metadata in the handle scope store
240
- const { result } = data;
241
- if (!result || !data._store || !data[kMetaKey]?.paths) return;
242
-
243
- let template;
244
- if (data._store.matcherIdx != null) {
245
- template = data[kMetaKey].paths[data._store.matcherIdx];
246
- } else {
247
- template = data[kMetaKey].paths[0];
248
- }
249
-
250
- // if the layer matches, we know to push corresponding path to store's template segments.
251
- // we pop this value from the array in hook to all `next` callbacks below.
252
- data._store.templateSegments.push(template);
253
- }
254
- });
255
-
256
- // patch the `next` callback of every Layer's request handler.
257
- // we pop the value from the stack of route template segments being managed.
258
- core.patcher.patch(Layer.prototype, 'handleRequest', {
259
- name: 'Layer.prototype.handleRequest',
260
- patchType: `${patchType}-observation`,
261
- pre(data) {
262
- const next = data.args[2];
263
- const meta = data.obj[kMetaKey] || data.obj.route?.[kMetaKey];
264
- if (meta?.paths) {
265
- const store = handleScope.getStore();
266
- // this runs often and there's no need to use patcher here. monkey patch directly to optimize
267
- data.args[2] = function(...args) {
268
- if (store) store.templateSegments.pop();
269
- const ret = next(...args);
270
- return ret;
271
- };
272
- }
273
- }
274
- });
275
-
276
- // instrument the Layer constructor. this will allow us to patch
277
- // created matchers to help us build observation template from metadata.
278
- // if matcher was successful we store index of it in handle scope.
279
- return core.patcher.patch(Layer, {
280
- name: 'router.Layer',
281
- patchType: `${patchType}-observation`,
282
- pre(data) {
283
- data._methodScope = methodScope.getStore();
284
- },
285
- post(data) {
286
- const instance = data.result;
287
- // only instrument matchers if the Layer is being instantiated within method scope, and
288
- // if there are multiple matchers and we need the index to correlate to tempate segment
289
- if (data._methodScope && instance.matchers.length > 1) {
290
- for (let i = 0; i < instance.matchers.length; i++) {
291
- const matcher = instance.matchers[i];
292
- instance.matchers[i] = function(...args) {
293
- const result = matcher.apply(this, args);
294
- if (result) {
295
- const store = handleScope.getStore();
296
- if (store) store.matcherIdx = i;
297
- }
298
- return result;
299
- };
300
- }
301
- }
302
- // patch handle to report observation when called. it checks handle
303
- // scope to get current request's template to match with discovery info
304
- core.patcher.patch(instance, 'handle', {
305
- name: 'router.Layer.handle',
306
- patchType: `${patchType}-observation`,
307
- pre(data) {
308
- if (instance[kMetaKey]?.observables) {
309
- const store = handleScope.getStore();
310
- if (store) {
311
- const method = StringPrototypeToLowerCase.call(data.args[0].method || '');
312
- const template = ArrayPrototypeJoin.call(store.templateSegments, '') || '/';
313
-
314
-
315
- if (instance[kMetaKey]?.observables?.[template]) {
316
- self.observe({
317
- url: data.args[0].originalUrl,
318
- normalizedUrl: template,
319
- method,
320
- signature: instance[kMetaKey].observables[template],
321
- type: instance[kMetaKey].routeType,
322
- });
323
- } else {
324
- core.logger.error({
325
- // url: data.args[0].originalUrl, // this would need masking to log
326
- method,
327
- template,
328
- observables: instance[kMetaKey]?.observables,
329
- }, 'unable to map route template to signature');
330
- }
331
- }
332
- }
333
- },
334
- });
335
- },
336
- });
337
- });
338
- }
339
-
340
- discover(info) {
341
- const { method, observables, routeType } = info;
342
- if (!method || !observables) return;
343
-
344
- for (const [normalizedUrl, signature] of Object.entries(observables)) {
345
- this.core.routeCoverage.discover({
346
- url: normalizedUrl,
347
- normalizedUrl,
348
- method,
349
- signature,
350
- type: routeType,
351
- framework: 'express',
352
- });
353
- }
354
- }
355
-
356
- observe(info) {
357
- this.core.routeCoverage.observe({ framework: 'express', ...info });
358
- }
359
-
360
- /**
361
- * Traverse the application's router "stack" and generate route discovery events
362
- * using layer/route metadata that was appended by methods like router.post().
363
- * @param {object} app express instance
364
- */
365
- handleDiscovery(app) {
366
- const self = this;
367
- const router = app.router || app._router;
368
-
369
- // traverse fn executes this callback when visiting Layer instances
370
- this.traverse(router, (path, key, value, target, state) => {
371
- if (value.stack?.length > 0 || value.route) return;
372
-
373
- // get metadata for this Layer
374
- // metadata is on Layers within stacks and on Routes instances.
375
- const metas = [];
376
- for (let i = 0; i < path.length; i++) {
377
- const seg = path[i];
378
- if (Number.isFinite((Number(seg))) || seg == 'route') {
379
- const metaPath = ArrayPrototypeJoin.call(path.slice(0, i + 1), '.');
380
- const layerOrRoute = get(router, metaPath);
381
- if (layerOrRoute?.[kMetaKey]) {
382
- metas.push(layerOrRoute[kMetaKey]);
383
- }
384
- }
385
- }
386
-
387
- // mounted routers aren't discoverable since they themselves don't
388
- // represent routes, they dispatch to sub routers/route handlers.
389
- if (value.name != 'router' && value.handle?.name != 'router') {
390
- let routeType;
391
- if (value[kMetaKey]?.method == 'use') {
392
- // if the handler is registered via `use` method, there are no
393
- // associated HTTP methods. this use case is considered middleware.
394
- if (!this.core.config.getEffectiveValue('assess.report_middleware_routes')) return;
395
- routeType = RouteType.MIDDLEWARE;
396
- } else {
397
- routeType = RouteType.HTTP;
398
- }
399
-
400
- // `value` is a terminal Layer with observable signatures.
401
- // emit discovery after appending metadata.
402
- if (value[kMetaKey]) {
403
- const observables = this.generateObservables(metas, value.handle);
404
- if (observables) {
405
- value[kMetaKey].routeType = routeType;
406
- if (!value[kMetaKey].observables) {
407
- value[kMetaKey].observables = observables;
408
- } else {
409
- Object.assign(value[kMetaKey].observables, observables);
410
- }
411
- }
412
- self.discover(value[kMetaKey]);
413
- }
414
- }
415
- });
416
- }
417
-
418
- /**
419
- * Traverses the top-level app's routing stack and executes the provided callback when
420
- * visiting nodes. The callback is invoked only to visit Layer instances, objects and
421
- * functions, since these are the only 2 types that could have our metadata attached.
422
- */
423
- traverse(target, cb, path = [], data = new Map()) {
424
- loopKeys: for (const key in target) {
425
- path.push(key);
426
-
427
- // only visit Layer instances
428
- const maybeLayer = target[key];
429
- if (
430
- maybeLayer?.constructor?.name == 'Layer' &&
431
- !maybeLayer?.stack?.length
432
- ) {
433
- let _data = data.get(maybeLayer);
434
-
435
- if (!_data) {
436
- _data = { paths: [] };
437
- data.set(maybeLayer, _data);
438
- }
439
-
440
- // you can mount a router on itself
441
- // prevent infinitely recursing into self-mounted routers
442
- for (const visitedPath of _data.paths) {
443
- // these conditions indicate recursive nesting at particular path
444
- if (
445
- path.length > visitedPath.length &&
446
- visitedPath.every((el, i) => path[i] == el)
447
- ) {
448
- path.pop();
449
- continue loopKeys;
450
- }
451
- }
452
-
453
- _data.paths.push([...path]); // copy because path argument mutates
454
-
455
- const halt = cb(path, key, maybeLayer, target) === false;
456
- if (halt) return;
457
- }
458
-
459
- // might be able to fine-tune this a bit more
460
- if (typeof maybeLayer == 'object' || typeof maybeLayer == 'function') {
461
- this.traverse(maybeLayer, cb, path, data);
462
- }
463
-
464
- path.pop();
465
- }
466
- }
467
-
468
- generateObservables(metas, handler) {
469
- const { core } = this;
470
- handler = core.patcher.unwrap(handler);
471
-
472
- let type = '';
473
- let method = '';
474
- let templates = [];
475
- const info = funcInfo(handler);
476
-
477
- let file = info.file ?
478
- StringPrototypeReplace.call(info.file, core.appInfo.app_dir, '') :
479
- '';
480
- if (file.length > 30) {
481
- file = `...${StringPrototypeSubstring.call(file, file.length - 40)}`;
482
- }
483
- const handlerName = info.method || handler.name || 'anonymous';
484
- const formattedHandler = (file && Number.isFinite(info.lineNumber) && Number.isFinite(info.column)) ?
485
- `[${handlerName} ${file} ${info.lineNumber}:${info.column}]` :
486
- `[Function: ${handlerName}]`; // what util.inspect(handler) would return
487
-
488
- // loop backwards
489
- for (let i = metas.length - 1; i >= 0; i--) {
490
- const meta = metas[i];
491
- // use the most recent `type` and `method` used when building routes, so don't overwrite if set
492
- if (!type && meta.type) type = meta.type;
493
- if (!method && meta.method) method = meta.method;
494
-
495
- // builds out all possible template combinations that the Layer is able to handle during routing
496
- if (Array.isArray(meta.paths)) {
497
- if (!templates.length) {
498
- templates = [...meta.paths];
499
- } else {
500
- const _t = [];
501
- for (const templateSegment of meta.paths) {
502
- for (const templateAcc of templates) {
503
- _t.push(`${templateSegment}${templateAcc}`);
504
- }
505
- }
506
- templates = [..._t];
507
- }
508
- }
509
- }
510
-
511
- // build signature lookup based on each template (normalizeUri)
512
- const map = templates.reduce((acc, routeTemplate) => {
513
- if (!routeTemplate) routeTemplate = '/';
514
- acc[routeTemplate] = `${type}.${method}('${routeTemplate}', ${formattedHandler})`;
515
- return acc;
516
- }, {});
517
-
518
- return map;
519
- }
520
-
521
- static normalizePathSegment(value) {
522
- if (!value || value == '/') {
523
- // app.[method](handler) and app.[method]('/', handler) are the same so default to empty string
524
- return '';
525
- }
526
- if (value instanceof RegExp) {
527
- const rxString = value.toString();
528
- // todo: figure out best way to represent regexp in route template
529
- return `/[${StringPrototypeSubstring.call(rxString, 1, rxString.length - 1)}]`;
530
- }
531
- return value;
532
- }
533
-
534
- static normalizePaths(paths) {
535
- const ret = [];
536
-
537
- // same as mounting as /
538
- if (typeof paths == 'function') {
539
- // default to ''
540
- ret.push('');
541
- } else if (isString(paths)) {
542
- ret.push(ExpressInstrumentation.normalizePathSegment(paths));
543
- } else if (Array.isArray(paths)) {
544
- paths = paths.flat(Infinity).filter((v) => typeof v !== 'function');
545
- if (paths.length) ret.push(...paths.map(ExpressInstrumentation.normalizePathSegment));
546
- else ret.push('');
547
- } else if (paths instanceof RegExp) {
548
- ret.push(ExpressInstrumentation.normalizePathSegment(paths));
549
- }
550
-
551
- return ret;
552
- }
553
- }