@contrast/route-coverage 1.51.0 → 1.52.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.
@@ -0,0 +1,67 @@
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 { RouteType } = require('@contrast/common');
18
+ const { patchType, formatHandler } = require('./../../utils/route-info');
19
+ const isArray = (arr) => Array.isArray(arr);
20
+ module.exports = function init(core) {
21
+ const { patcher, depHooks, routeCoverage } = core;
22
+
23
+ return core.routeCoverage.fastifyMiddie = {
24
+ install() {
25
+ depHooks.resolve({ name: '@fastify/middie', version: '*', file: 'lib/engine.js' }, (middie) => patcher.patch(middie, {
26
+ name: 'fastifyMiddie',
27
+ patchType,
28
+ post(data) {
29
+ patcher.patch(data.result, 'use', {
30
+ name: 'use',
31
+ patchType,
32
+ pre(data) {
33
+ const [url, fn] = data.args;
34
+ if (!url || !fn || !core.config.getEffectiveValue('assess.report_middleware_routes')) return;
35
+
36
+ const middleware = isArray(fn) ? fn : [fn];
37
+ const formattedPath = isArray(url) ? `[${url.join(', ')}]` : url;
38
+ const patchedMiddleware = middleware.map((f) => {
39
+ const formattedHandler = formatHandler(f);
40
+ const signature = `fastify.use(${formattedPath}, ${formattedHandler})`;
41
+
42
+ const routeInfo = {
43
+ signature,
44
+ url: formattedPath,
45
+ method: 'use',
46
+ normalizedUrl: formattedPath,
47
+ type: RouteType.MIDDLEWARE,
48
+ framework: 'fastify'
49
+ };
50
+ routeCoverage.discover(routeInfo);
51
+
52
+ return patcher.patch(f, {
53
+ name: 'middleware',
54
+ patchType,
55
+ post() {
56
+ routeCoverage.observe(routeInfo);
57
+ }
58
+ });
59
+ });
60
+ data.args[1] = patchedMiddleware;
61
+ }
62
+ });
63
+ }
64
+ }));
65
+ }
66
+ };
67
+ };
@@ -14,12 +14,12 @@
14
14
  */
15
15
  'use strict';
16
16
 
17
- const { getFastifyMethods } = require('../utils/methods');
17
+ const { getFastifyMethods } = require('../../utils/methods');
18
18
  const {
19
19
  primordials: { StringPrototypeToLowerCase, StringPrototypeSplit },
20
20
  RouteType,
21
21
  } = require('@contrast/common');
22
- const { patchType } = require('./../utils/route-info');
22
+ const { patchType, formatHandler } = require('./../../utils/route-info');
23
23
 
24
24
  // Spec: https://contrast.atlassian.net/wiki/spaces/NOD/pages/3454861621/Node.js+Agent+Route+Signatures#Fastify
25
25
  module.exports = function init(core) {
@@ -38,12 +38,12 @@ module.exports = function init(core) {
38
38
  return route?.[kRoutePrefix];
39
39
  }
40
40
 
41
- function createRouteInfo(method, url, fullyDeclared, type) {
41
+ function createRouteInfo(method, url, fullyDeclared, type, handler) {
42
42
  method = StringPrototypeToLowerCase.call(method);
43
43
 
44
44
  const signature = fullyDeclared
45
- ? `fastify.route({ method: '${method}', url: '${url}', handler: [Function] })`
46
- : `fastify.${method}('${url}', [Function])`;
45
+ ? `fastify.route({ method: ${method}, url: ${url}, handler: ${formatHandler(handler)} })`
46
+ : `fastify.${method}(${url}, ${formatHandler(handler)})`;
47
47
 
48
48
  const routeInfo = {
49
49
  signature,
@@ -89,30 +89,30 @@ module.exports = function init(core) {
89
89
  }
90
90
  }
91
91
 
92
- function discoverAndPatch(method, path, routeObj, handle, methods, fullyDeclared) {
92
+ function discoverAndPatch(method, path, routeObj, handle, handler, methods, fullyDeclared) {
93
93
  const type = routeObj?.options?.websocket ? RouteType.MESSAGE_BROKER : RouteType.HTTP;
94
94
 
95
95
  if (Array.isArray(method)) {
96
96
  // If all valid methods are included in `method` then .all shorthand was most likely used
97
97
  if (methods.every(m => method.includes(m))) {
98
- const routeInfo = createRouteInfo('all', path, fullyDeclared, type);
98
+ const routeInfo = createRouteInfo('all', path, fullyDeclared, type, handler);
99
99
  routeCoverage.discover(routeInfo);
100
100
  patchHandler(routeObj, handle, routeInfo);
101
101
  } else {
102
102
  method.forEach((verb) => {
103
- const routeInfo = createRouteInfo(verb, path, fullyDeclared, type);
103
+ const routeInfo = createRouteInfo(verb, path, fullyDeclared, type, handler);
104
104
  routeCoverage.discover(routeInfo);
105
105
  patchHandler(routeObj, handle, routeInfo);
106
106
  });
107
107
  }
108
108
  } else {
109
- const routeInfo = createRouteInfo(method, path, fullyDeclared, type);
109
+ const routeInfo = createRouteInfo(method, path, fullyDeclared, type, handler);
110
110
  routeCoverage.discover(routeInfo);
111
111
  patchHandler(routeObj, handle, routeInfo);
112
112
  }
113
113
  }
114
114
 
115
- return core.routeCoverage.fastify = {
115
+ return core.routeCoverage.fastifyCore = {
116
116
  install() {
117
117
  /**
118
118
  * There are some subtle differences between fastify minor versions the instrumentation must account for
@@ -158,7 +158,7 @@ module.exports = function init(core) {
158
158
  let handle = 'handler';
159
159
  if (!handler && typeof options === 'function') handle = 'options';
160
160
 
161
- discoverAndPatch(method, path, routeObj ? data.args[0] : data.args, handle, fastifyMethods, false);
161
+ discoverAndPatch(method, path, routeObj ? data.args[0] : data.args, handle, options || handler, fastifyMethods, false);
162
162
  }
163
163
  });
164
164
 
@@ -175,7 +175,7 @@ module.exports = function init(core) {
175
175
 
176
176
  const prefix = getPrefix(data.obj);
177
177
  const path = prefix ? prefix + url : url;
178
- discoverAndPatch(method, path, routeArgs, 'handler', fastifyMethods, true);
178
+ discoverAndPatch(method, path, routeArgs, 'handler', handler, fastifyMethods, true);
179
179
  }
180
180
  });
181
181
  }
@@ -18,14 +18,15 @@
18
18
  const { callChildComponentMethodsSync } = require('@contrast/common');
19
19
 
20
20
  module.exports = function(core) {
21
- const expressRouteCoverage = core.routeCoverage.express = {
21
+ const fastifyRouteCoverage = core.routeCoverage.fastify = {
22
22
  install() {
23
- callChildComponentMethodsSync(expressRouteCoverage, 'install');
23
+ callChildComponentMethodsSync(fastifyRouteCoverage, 'install');
24
24
  },
25
25
  };
26
26
 
27
- require('./express4')(core);
28
- require('./express5')(core);
27
+ require('./fastify')(core);
28
+ require('./fastify-express')(core);
29
+ require('./fastify-middie')(core);
29
30
 
30
- return expressRouteCoverage;
31
+ return fastifyRouteCoverage;
31
32
  };
@@ -15,28 +15,15 @@
15
15
  'use strict';
16
16
 
17
17
  const { METHODS } = require('./../utils/methods');
18
- const { isString, primordials: { StringPrototypeToLowerCase, StringPrototypeSplit } } = require('@contrast/common');
19
- const { createSignature, patchType } = require('./../utils/route-info');
18
+ const { isString, RouteType, primordials: { StringPrototypeToLowerCase, StringPrototypeSplit } } = require('@contrast/common');
19
+ const { patchType, formatHandler } = require('./../utils/route-info');
20
20
 
21
21
  // Spec: https://contrast.atlassian.net/wiki/spaces/NOD/pages/3454861621/Node.js+Agent+Route+Signatures#Koa
22
22
  module.exports = function init(core) {
23
23
  const { patcher, depHooks, routeCoverage } = core;
24
-
25
- function createRouteInfo(method, url) {
26
- method = StringPrototypeToLowerCase.call(method);
27
- const routeInfo = {
28
- signature: createSignature(url, method),
29
- url,
30
- method,
31
- normalizedUrl: url,
32
- framework: 'koa'
33
- };
34
- return routeInfo;
35
- }
36
-
37
24
  return core.routeCoverage.koa = {
38
25
  install() {
39
- depHooks.resolve({ name: 'koa', version: '>=2.3.0 <4' }, (Koa) => {
26
+ depHooks.resolve({ name: 'koa', version: '>=2.3.0 <4' }, (Koa, pkgMeta) => {
40
27
  // Koa uses its own routing library @koa/router to define routes before
41
28
  // mounting them on the app with .use so instrumenting use and traversing
42
29
  // the constructed routes is the more technically correct approach than
@@ -48,40 +35,47 @@ module.exports = function init(core) {
48
35
  if (args?.length === 0) return;
49
36
  const [router] = args;
50
37
 
51
- if (!router?.router) return;
38
+ if (!router?.router) {
39
+ core.logger.debug('no routes detected in koa router stack: %s@%s', pkgMeta.name, pkgMeta.version);
40
+ return;
41
+ }
52
42
 
53
43
  router.router.stack.forEach((Layer) => {
54
- const { methods, path } = Layer;
55
- if (!path || !isString(path)) return;
44
+ const { methods, path, stack } = Layer;
45
+ if (!path || !isString(path) || !stack || stack.length === 0) return;
56
46
 
57
- let routeInfo;
58
- if (methods.length === 0) {
59
- routeInfo = createRouteInfo('use', path);
60
- routeCoverage.discover(routeInfo);
61
- } else if (METHODS.every(m => methods.includes(m))) {
62
- // If a route was defined using .all this methods property will be an
63
- // array of all methods supported by Koa
64
- routeInfo = createRouteInfo('all', path);
47
+ const patchedMiddleware = [];
48
+ stack.forEach((handler) => {
49
+ const method = methods.length === 0 ? 'use' : METHODS.every(m => methods.includes(m)) ? 'all' : StringPrototypeToLowerCase.call(methods[methods.length - 1]);
50
+ if (method === 'use' && !core.config.getEffectiveValue('assess.report_middleware_routes')) return;
51
+ const routeInfo = {
52
+ signature: `Router.${method}(${path}, ${formatHandler(handler)})`,
53
+ method,
54
+ url: path,
55
+ normalizedUrl: path,
56
+ framework: 'koa',
57
+ type: method === 'use' ? RouteType.MIDDLEWARE : RouteType.HTTP
58
+ };
65
59
  routeCoverage.discover(routeInfo);
66
- } else {
67
- methods.forEach((method) => {
68
- routeInfo = createRouteInfo(method, path);
69
- routeCoverage.discover(routeInfo);
70
- });
71
- }
60
+ const patchedHandler = patcher.patch(handler, {
61
+ name: 'handler',
62
+ patchType,
63
+ pre(data) {
64
+ const { request } = data.args[0];
65
+ if (!request) return;
72
66
 
73
- if (!Layer.stack || Layer.stack.length === 0) return;
74
- async function observationMiddleware(ctx, next) {
75
- if (!ctx.request) return;
76
- const { url: reqUrl, method } = ctx.request;
77
- const [url] = StringPrototypeSplit.call(reqUrl, /\?/);
78
- routeCoverage.observe({ ...routeInfo, url, method: StringPrototypeToLowerCase.call(method) });
79
- await next();
80
- }
81
- // If two routes share middleware, the same stack is used
82
- // To add our observation middleware without adding them to all routes
83
- // we need to create a shallow copy
84
- Layer.stack = [observationMiddleware, ...Layer.stack];
67
+ const { method, url } = request;
68
+ if (!method | !url) return;
69
+ routeCoverage.observe({
70
+ ...routeInfo,
71
+ method: StringPrototypeToLowerCase.call(method),
72
+ url: StringPrototypeSplit.call(url, /\?/)[0]
73
+ });
74
+ }
75
+ });
76
+ patchedMiddleware.push(patchedHandler);
77
+ });
78
+ Layer.stack = patchedMiddleware;
85
79
  });
86
80
  }
87
81
  });
@@ -15,6 +15,8 @@
15
15
  'use strict';
16
16
 
17
17
  const patchType = 'route-coverage';
18
+ const { funcInfo } = require('@contrast/fn-inspect');
19
+ const { primordials: { StringPrototypeReplace, StringPrototypeSubstring } } = require('@contrast/common');
18
20
 
19
21
  /**
20
22
  * Creates a formatted "signature" for a route
@@ -28,4 +30,27 @@ function createSignature(path, method = '', obj = 'Router', handler = '[Function
28
30
  return `${obj}.${method}('${path}', ${handler})`;
29
31
  }
30
32
 
31
- module.exports = { createSignature, patchType };
33
+ /**
34
+ * Creates a formatted handler signature for a route
35
+ * @param {function} handler
36
+ * @param {string} appDir
37
+ * @return {string} formatted handler
38
+ */
39
+ function formatHandler(handler, appDir) {
40
+ const info = funcInfo(handler);
41
+ if (!info) return '[Function]';
42
+
43
+ let file = info.file ?
44
+ StringPrototypeReplace.call(info.file, appDir, '') :
45
+ '';
46
+ if (file.length > 30) {
47
+ file = `...${StringPrototypeSubstring.call(file, file.length - 40)}`;
48
+ }
49
+ const handlerName = info.method || handler.name || 'anonymous';
50
+ const formattedHandler = (file && Number.isFinite(info.lineNumber) && Number.isFinite(info.column)) ?
51
+ `[${handlerName} ${file} ${info.lineNumber}:${info.column}]` :
52
+ `[Function: ${handlerName}]`; // what util.inspect(handler) would return
53
+ return formattedHandler;
54
+ }
55
+
56
+ module.exports = { createSignature, patchType, formatHandler };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@contrast/route-coverage",
3
- "version": "1.51.0",
3
+ "version": "1.52.0",
4
4
  "description": "Handles route discovery and observation",
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "author": "Contrast Security <nodejs@contrastsecurity.com> (https://www.contrastsecurity.com)",
@@ -21,13 +21,13 @@
21
21
  },
22
22
  "dependencies": {
23
23
  "@contrast/common": "1.38.0",
24
- "@contrast/config": "1.54.0",
25
- "@contrast/core": "1.59.0",
26
- "@contrast/dep-hooks": "1.28.0",
24
+ "@contrast/config": "1.54.1",
25
+ "@contrast/core": "1.59.1",
26
+ "@contrast/dep-hooks": "1.28.1",
27
27
  "@contrast/fn-inspect": "^5.0.2",
28
- "@contrast/logger": "1.32.0",
29
- "@contrast/patcher": "1.31.0",
30
- "@contrast/scopes": "1.29.0",
28
+ "@contrast/logger": "1.32.1",
29
+ "@contrast/patcher": "1.31.1",
30
+ "@contrast/scopes": "1.29.1",
31
31
  "semver": "^7.6.0"
32
32
  }
33
33
  }
@@ -1,157 +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 METHODS = [
18
- 'all',
19
- 'get',
20
- 'post',
21
- 'put',
22
- 'delete',
23
- 'patch',
24
- 'options',
25
- 'head',
26
- ];
27
-
28
- const fnInspect = require('@contrast/fn-inspect');
29
- const { createSignature, patchType } = require('../../utils/route-info');
30
- const { isString, primordials: { ArrayPrototypeJoin, StringPrototypeToLowerCase, StringPrototypeReplace, StringPrototypeReplaceAll, StringPrototypeSplit, StringPrototypeSlice } } = require('@contrast/common');
31
-
32
- // Spec: https://contrast.atlassian.net/wiki/spaces/NOD/pages/3454861621/Node.js+Agent+Route+Signatures#Express
33
- module.exports = function init(core) {
34
- const { patcher, depHooks, routeCoverage } = core;
35
- const discover = (route) => routeCoverage.discover(route);
36
- const observe = (route) => routeCoverage.observe(route);
37
-
38
- const isRoute = (layer) => !!layer.route;
39
- const isRouter = (layer) => layer.name && StringPrototypeToLowerCase.call(layer.name) === 'router';
40
- const isValidPath = (path) => isString(path) || Array.isArray(path) || path instanceof RegExp;
41
- const getHandleMethod = (layer) => fnInspect.funcInfo(layer.__handle)?.file.includes('express-async-errors') ? '__handle' : 'handle';
42
- const getLastLayer = (router) => router?.stack[router.stack.length - 1];
43
-
44
- function regExpToPath(regex) {
45
- if (regex.source) {
46
- let [path] = StringPrototypeSplit.call(regex?.source, '/?');
47
- path = StringPrototypeReplaceAll.call(path, '\\', '');
48
- path = StringPrototypeReplace.call(path, '^', '');
49
- return path;
50
- }
51
- }
52
-
53
- function format(url) {
54
- if (Array.isArray(url)) {
55
- return `/[${ArrayPrototypeJoin.call(url)}]`;
56
- } else if (url instanceof RegExp) {
57
- return `/{${StringPrototypeSlice.call(url.toString(), 1, -1)}}`;
58
- } else {
59
- return url;
60
- }
61
- }
62
-
63
- function parseRoute(route) {
64
- const { path } = route;
65
- const method = route.methods._all ? 'all' : route.stack[0].method;
66
- return { url: format(path), method };
67
- }
68
-
69
-
70
- function createRouteInfo(url, method, obj) {
71
- return {
72
- signature: createSignature(url, method, obj),
73
- url,
74
- normalizedUrl: url,
75
- method,
76
- framework: 'express'
77
- };
78
- }
79
-
80
- function patchHandle(layer, routeInfo) {
81
- const handle = getHandleMethod(layer);
82
- patcher.patch(layer, handle, {
83
- name: 'express.Route.handle',
84
- patchType,
85
- post({ args }) {
86
- const [req] = args;
87
- const [url] = StringPrototypeSplit.call(req.originalUrl, '?');
88
- const { method } = req;
89
- if (url && method) {
90
- observe({ ...routeInfo, url, method: StringPrototypeToLowerCase.call(method) });
91
- }
92
- }
93
- });
94
- }
95
-
96
- function traverse(stack, path = '', depth = 0) {
97
- path = format(path);
98
- stack.forEach((layer) => {
99
- if (isRoute(layer)) {
100
- const { url, method } = parseRoute(layer.route);
101
- const routeInfo = createRouteInfo(path + url, method);
102
- discover(routeInfo);
103
- patchHandle(layer, routeInfo);
104
- } else if (isRouter(layer)) {
105
- const regexPath = regExpToPath(layer.regexp);
106
- if (depth < 3) traverse(layer.handle.stack, path + regexPath, depth += 1);
107
- } else {
108
- const regexPath = regExpToPath(layer.regexp);
109
- const routeInfo = createRouteInfo(path + regexPath, 'use');
110
- discover(routeInfo);
111
- patchHandle(layer, routeInfo);
112
- }
113
- });
114
- }
115
- return core.routeCoverage.express4 = {
116
- install() {
117
- depHooks.resolve({ name: 'express', version: '>=4 <5' }, (express) => {
118
- patcher.patch(express.application, 'use', {
119
- name: 'express.application.use',
120
- patchType,
121
- post({ args, result }) {
122
- const len = args.length;
123
- const fn = args[len - 1];
124
- const path = len > 1 ? args[0] : undefined;
125
- if (path && !isValidPath(path)) return;
126
- const handlers = Array.isArray(fn) ? fn : [fn];
127
- handlers.forEach((layer) => {
128
- if (isRouter(layer)) {
129
- traverse(layer.stack, path);
130
- } else if (path) {
131
- const routeInfo = createRouteInfo(format(path), 'use', 'App');
132
- discover(routeInfo);
133
- const lastLayer = getLastLayer(result._router);
134
- if (lastLayer) patchHandle(lastLayer, routeInfo);
135
- }
136
- });
137
- }
138
- });
139
-
140
- METHODS.forEach((method) => {
141
- patcher.patch(express.application, method, {
142
- name: `express.application.${method}`,
143
- patchType,
144
- post({ args, result }) {
145
- const [url, fn] = args;
146
- if (!url || !fn || !isValidPath(url)) return;
147
- const routeInfo = createRouteInfo(format(url), method, 'App');
148
- discover(routeInfo);
149
- const lastLayer = getLastLayer(result._router);
150
- if (lastLayer) patchHandle(lastLayer, routeInfo);
151
- }
152
- });
153
- });
154
- });
155
- }
156
- };
157
- };