@contrast/route-coverage 1.52.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.
package/lib/index.js CHANGED
@@ -122,12 +122,12 @@ module.exports = function init(core) {
122
122
  },
123
123
  };
124
124
 
125
- require('./install/express')(core);
125
+ core.initComponentSync(require('./install/express'));
126
126
  require('./install/fastify')(core);
127
127
  require('./install/graphql')(core);
128
- require('./install/hapi')(core);
128
+ core.initComponentSync(require('./install/hapi'));
129
129
  require('./install/koa')(core);
130
- require('./install/restify')(core);
130
+ core.initComponentSync(require('./install/restify'));
131
131
  core.initComponentSync(require('./install/socket.io'));
132
132
 
133
133
  messages.on(Event.SERVER_LISTENING, () => {
@@ -12,76 +12,139 @@
12
12
  * engineered, modified, repackaged, sold, redistributed or otherwise used in a
13
13
  * way not consistent with the End User License Agreement.
14
14
  */
15
+ // @ts-check
15
16
  'use strict';
16
17
 
17
- const { primordials: { StringPrototypeToLowerCase } } = require('@contrast/common');
18
- const { patchType } = require('./../utils/route-info');
18
+ const { AsyncLocalStorage } = require('node:async_hooks');
19
+ const { RouteType, set } = require('@contrast/common');
20
+ const { Core } = require('@contrast/core/lib/ioc/core');
21
+ const { formatHandler, patchType } = require('../utils/route-info');
19
22
 
20
- // Spec: https://contrast.atlassian.net/wiki/spaces/NOD/pages/3454861621/Node.js+Agent+Route+Signatures#Hapi
21
- module.exports = function init(core) {
22
- const { patcher, depHooks, routeCoverage } = core;
23
+ /**
24
+ * The hapi `Route` class from lib/route.js is not defined or exported.
25
+ * @typedef {Object} Route
26
+ * @property {boolean} _special internal hapi property for special routes
27
+ * @property {string} method
28
+ * @property {string} path
29
+ * @property {Object} settings
30
+ * @property {(request: { method: string, path: string}) => any} settings.handler set by the Route constructor
31
+ */
32
+
33
+ class HapiRouteCoverage {
34
+ /**
35
+ * @param {import('..').Core & {
36
+ * routeCoverage: import('..').RouteCoverage;
37
+ * }} core
38
+ */
39
+ constructor(core) {
40
+ set(core, 'routeCoverage.hapi', this);
41
+ this.core = core;
42
+ this.depHooks = core.depHooks;
43
+ this.patcher = core.patcher;
44
+ this.routeCoverage = core.routeCoverage;
45
+ this.registerScope = new AsyncLocalStorage();
46
+ }
23
47
 
24
- const createSignature = (method, url) => `server.route({ method: '${method}', path: '${url}', handler: [Function] })`;
25
- function emitRouteCoverage(url, method) {
26
- method = StringPrototypeToLowerCase.call(method);
27
- const event = {
28
- signature: createSignature(method, url),
29
- url,
30
- method,
31
- normalizedUrl: url,
32
- framework: 'hapi'
33
- };
34
- routeCoverage.discover(event);
48
+ install() {
49
+ this.depHooks.resolve(
50
+ { name: '@hapi/hapi', version: '>=18 <22', file: 'lib/server.js' },
51
+ /** @param {typeof import('@hapi/hapi').Server} Server */
52
+ (Server) => this.patchServer(Server),
53
+ );
54
+ this.depHooks.resolve(
55
+ { name: '@hapi/hapi', version: '>=18 <22', file: 'lib/route.js' },
56
+ /** @param {abstract new () => Route} Route */
57
+ (Route) => this.patchRoute(Route),
58
+ );
35
59
  }
36
60
 
37
- return core.routeCoverage.hapi = {
38
- install() {
39
- return depHooks.resolve({ name: '@hapi/hapi', version: '>=18 <22' }, (hapi) => {
40
- ['server', 'Server'].forEach((server) => {
41
- patcher.patch(hapi, server, {
42
- name: `hapi.${server}`,
43
- patchType,
44
- post(data) {
45
- patcher.patch(data.result._core.router, 'add', {
46
- name: '_core.router.add',
47
- patchType,
48
- post(data) {
49
- if (!data.args[0] || !data.result) return;
61
+ /**
62
+ * Spec: https://contrast.atlassian.net/wiki/spaces/NOD/pages/3454861621/Node.js+Agent+Route+Signatures#Hapi
63
+ * @param {Route} route
64
+ */
65
+ createSignature(route) {
66
+ const handler = formatHandler(this.patcher.unwrap(route.settings.handler));
67
+ return `server.route({ method: '${route.method}', path: '${route.path}', handler: ${handler} })`;
68
+ }
69
+
70
+ /** @param {typeof import('@hapi/hapi').Server} Server */
71
+ patchServer(Server) {
72
+ const self = this;
73
+ return this.patcher.patch(Server, {
74
+ name: 'hapi.Server',
75
+ patchType,
76
+ post({ result: server }) {
77
+ self.patcher.patch(server, 'register', {
78
+ name: 'server.register',
79
+ patchType,
80
+ around(next) {
81
+ if (self.registerScope.getStore()) return next();
82
+ return self.registerScope.run({ isMiddleware: true }, next);
83
+ },
84
+ });
85
+ },
86
+ });
87
+ }
50
88
 
51
- const [{ method, path }] = data.args;
52
- if (!method || !path) return;
89
+ /**
90
+ * @param {Route} route
91
+ * @param {string} signature
92
+ * @param {RouteType} type
93
+ */
94
+ patchRouteHandler(route, signature, type) {
95
+ const self = this;
96
+ this.patcher.patch(route.settings, 'handler', {
97
+ name: 'route.settings.handler',
98
+ patchType,
99
+ // this needs to be in a pre-hook so that the route
100
+ // data is in the store before our dataflow hooks run
101
+ pre({ args: [request] }) {
102
+ self.routeCoverage.observe({
103
+ signature,
104
+ method: request.method,
105
+ url: request.path,
106
+ normalizedUrl: route.path, // should also be defined at `request.route.path`
107
+ framework: 'hapi',
108
+ type,
109
+ });
110
+ },
111
+ });
112
+ }
53
113
 
54
- if (Array.isArray(method)) {
55
- method.forEach((verb) => {
56
- emitRouteCoverage(path, verb);
57
- });
58
- } else {
59
- emitRouteCoverage(path, method);
60
- }
114
+ /**
115
+ * @param {abstract new () => Route} Route
116
+ */
117
+ patchRoute(Route) {
118
+ const self = this;
119
+ return this.patcher.patch(Route, {
120
+ name: 'hapi.Route',
121
+ patchType,
122
+ post({ result: route }) {
123
+ if (route._special) return; // skip special internal routes
124
+ const signature = self.createSignature(route);
125
+ const type = self.registerScope.getStore()?.isMiddleware ? RouteType.MIDDLEWARE : RouteType.HTTP;
61
126
 
62
- patcher.patch(data.result.route.settings, 'handler', {
63
- name: 'route.settings.handler',
64
- patchType,
65
- // this needs to be in a pre-hook so that the route
66
- // data is in the store before our dataflow hooks run
67
- pre({ args }) {
68
- const [{ method, path: url, route }] = args;
69
- //TODO: Will this signature always be associated with an existing route?
70
- const signature = createSignature(method, path);
71
- routeCoverage.observe({
72
- signature,
73
- url,
74
- method: StringPrototypeToLowerCase.call(method),
75
- normalizedUrl: route.path,
76
- });
77
- }
78
- });
79
- }
80
- });
81
- }
82
- });
127
+ self.routeCoverage.discover({
128
+ signature,
129
+ method: route.method,
130
+ url: route.path,
131
+ normalizedUrl: route.path,
132
+ framework: 'hapi',
133
+ type,
83
134
  });
84
- });
85
- }
86
- };
87
- };
135
+
136
+ self.patchRouteHandler(route, signature, type);
137
+ },
138
+ });
139
+ }
140
+ }
141
+
142
+ module.exports = Core.makeComponent({
143
+ name: 'routeCoverage.hapi',
144
+ /**
145
+ * @param {import('..').Core & {
146
+ * routeCoverage: import('..').RouteCoverage;
147
+ * }} core
148
+ */
149
+ factory: (core) => new HapiRouteCoverage(core),
150
+ });
@@ -14,58 +14,240 @@
14
14
  */
15
15
  'use strict';
16
16
 
17
- const { isString, primordials: { StringPrototypeToLowerCase, StringPrototypeSplit } } = require('@contrast/common');
18
- const { createSignature, patchType } = require('../utils/route-info');
19
-
20
- // Spec: https://contrast.atlassian.net/wiki/spaces/NOD/pages/3454861621/Node.js+Agent+Route+Signatures#Restify
21
- module.exports = function init(core) {
22
- const { patcher, depHooks, routeCoverage } = core;
23
- const discover = (route) => routeCoverage.discover(route);
24
- const observe = (route) => routeCoverage.observe(route);
25
-
26
- function createRoute(url, method) {
27
- method = StringPrototypeToLowerCase.call(method);
28
- return {
29
- signature: createSignature(url, method, 'server'),
30
- method,
31
- url,
32
- normalizedUrl: url,
33
- framework: 'restify'
34
- };
17
+ const { AsyncLocalStorage } = require('async_hooks');
18
+ const {
19
+ isString,
20
+ primordials: {
21
+ StringPrototypeToLowerCase,
22
+ StringPrototypeSplit,
23
+ StringPrototypeSubstring,
24
+ },
25
+ set,
26
+ RouteType,
27
+ } = require('@contrast/common');
28
+ const { Core } = require('@contrast/core/lib/ioc/core');
29
+ const { formatHandler, patchType } = require('../utils/route-info');
30
+
31
+ const COMPONENT_NAME = 'routeCoverage.restify';
32
+ const FRAMEWORK = 'restify';
33
+
34
+ module.exports = Core.makeComponent({
35
+ name: COMPONENT_NAME,
36
+ factory: (core) => new RestifyInstrumentation(core),
37
+ });
38
+
39
+ class RestifyInstrumentation {
40
+ constructor(core) {
41
+ set(core, COMPONENT_NAME, this);
42
+ Object.defineProperty(this, 'core', { value: core });
43
+ this.routeScope = new AsyncLocalStorage();
44
+ this.conditionalHandlers = new WeakMap();
35
45
  }
36
46
 
37
- return core.routeCoverage.restify = {
38
- install() {
39
- depHooks.resolve({ name: 'restify', version: '>=10 <12' }, (restify) => {
40
- patcher.patch(restify, 'createServer', {
41
- name: 'restify.createServer',
42
- patchType,
43
- post({ result: server }) {
44
- patcher.patch(server.router, 'mount', {
45
- name: 'restify.router.mount',
47
+ formatHandler(fn) {
48
+ return formatHandler(this.core.patcher.unwrap(fn));
49
+ }
50
+
51
+ install() {
52
+ const self = this;
53
+ const { depHooks } = this.core;
54
+
55
+ depHooks.resolve({ name: 'restify', version: '>=10 <12' }, (restify, pkgMeta) => {
56
+ self.patchPlugins(restify, pkgMeta);
57
+ self.patchServer(restify, pkgMeta);
58
+ });
59
+ }
60
+
61
+ patchPlugins(restify) {
62
+ const self = this;
63
+ const { patcher, routeCoverage } = this.core;
64
+ if (!restify.plugins?.conditionalHandler) return;
65
+
66
+ const name = 'restify.plugins.conditionalHandler';
67
+ patcher.patch(restify.plugins, 'conditionalHandler', {
68
+ name,
69
+ patchType,
70
+ around(next, data) {
71
+ const { args } = data;
72
+ const conditionals = Array.isArray(args[0]) ? args[0] : [args[0]];
73
+ const formattedHandlers = [];
74
+
75
+ // we have to do this before calling next() to get return value
76
+ // since restify potentially alters conditional.handlers
77
+ for (const conditional of conditionals) {
78
+ const isHandlerArr = Array.isArray(conditional.handler);
79
+ const target = isHandlerArr ? conditional.handler : conditional;
80
+ const propsIter = isHandlerArr ? Object.keys(conditional.handler) : ['handler'];
81
+
82
+ for (const propName of propsIter) {
83
+ if (typeof target[propName] !== 'function') continue;
84
+
85
+ const formattedHandler = self.formatHandler(target[propName]);
86
+ formattedHandlers.push(formattedHandler);
87
+
88
+ patcher.patch(target, propName, {
89
+ name: 'restify.plugins.conditionalHandler',
46
90
  patchType,
47
- post({ result: route }) {
48
- const { path, method } = route;
49
- if (!path || !method || !isString(path)) return;
50
- const routeInfo = createRoute(path, method);
51
- discover(routeInfo);
52
-
53
- const [handler] = route.chain._stack;
54
- route.chain._stack[0] = patcher.patch(handler, {
55
- name: 'route.chain._stack[0].handler',
91
+ pre(data) {
92
+ const { args: [req] } = data;
93
+ const store = self.routeScope.getStore();
94
+ if (!store) return;
95
+
96
+ for (const routeInfo of store.observables) {
97
+ if (routeInfo.signature.indexOf(formattedHandler) >= 0) {
98
+ routeCoverage.observe({
99
+ ...routeInfo,
100
+ method: StringPrototypeToLowerCase.call(req.method),
101
+ url: StringPrototypeSplit.call(req.url, '?')[0],
102
+ });
103
+ break;
104
+ }
105
+ }
106
+ },
107
+ });
108
+ }
109
+ }
110
+
111
+ const result = next();
112
+
113
+ // save list of handlers that have been registered under the returned
114
+ // consolidated one. when this return value gets mounted at an actual
115
+ // path(s), we can lookup the handlers and discover each individually
116
+ // with that additional route info.
117
+ self.conditionalHandlers.set(result, formattedHandlers);
118
+
119
+ return result;
120
+ },
121
+ });
122
+ }
123
+
124
+ patchServer(restify, pkgMeta) {
125
+ const self = this;
126
+ const { logger, patcher, routeCoverage } = this.core;
127
+
128
+ patcher.patch(restify, 'createServer', {
129
+ name: 'restify.createServer',
130
+ patchType,
131
+ post({ result: server }) {
132
+ patcher.patch(server.router, 'mount', {
133
+ name: 'restify.router.mount',
134
+ patchType,
135
+ post({ result: route }) {
136
+ if (!route.path || !route.method || !isString(route.path)) {
137
+ logger.error({ route }, 'unable to process restify route');
138
+ return;
139
+ }
140
+
141
+ const { path } = route;
142
+ const method = StringPrototypeToLowerCase.call(route.method);
143
+ const baseInfo = {
144
+ method,
145
+ url: path,
146
+ normalizedUrl: path,
147
+ framework: FRAMEWORK,
148
+ type: RouteType.HTTP,
149
+ };
150
+
151
+ for (let idx = 0; idx < route.chain._stack.length; idx++) {
152
+ const handler = route.chain._stack[idx];
153
+ const routeInfo = {
154
+ ...baseInfo,
155
+ signature: `server.${method}(${path}, ${self.formatHandler(handler)})`,
156
+ };
157
+
158
+ if (!self.conditionalHandlers.has(handler)) {
159
+ // "regular" handlers
160
+ routeCoverage.discover(routeInfo);
161
+ route.chain._stack[idx] = patcher.patch(route.chain._stack[idx], {
162
+ name: 'restify.route.chain._stack',
56
163
  patchType,
57
- post({ args }) {
58
- const [req] = args;
59
- const { url: reqUrl, method } = req;
60
- const [url] = StringPrototypeSplit.call(reqUrl, '?');
61
- observe({ ...routeInfo, method: StringPrototypeToLowerCase.call(method), url });
164
+ pre({ args: [req] }) {
165
+ routeCoverage.observe({
166
+ ...routeInfo,
167
+ method: StringPrototypeToLowerCase.call(req.method),
168
+ url: StringPrototypeSplit.call(req.url, '?')[0],
169
+ });
170
+ }
171
+ });
172
+ } else {
173
+ // "conditional" handlers dispatch to their registered handlers
174
+ const formattedHandlers = self.conditionalHandlers.get(handler);
175
+ const store = { observables: [] };
176
+
177
+ for (const formattedHandler of formattedHandlers) {
178
+ const routeInfo = {
179
+ ...baseInfo,
180
+ signature: `server.${method}(${path}, ${formattedHandler})`,
181
+ };
182
+ routeCoverage.discover(routeInfo);
183
+ store.observables.push(routeInfo);
184
+ }
185
+
186
+ route.chain._stack[idx] = patcher.patch(route.chain._stack[idx], {
187
+ name: 'restify.route.chain._stack',
188
+ patchType,
189
+ around(next) {
190
+ return self.routeScope.run(store, next);
62
191
  }
63
192
  });
64
193
  }
65
- });
194
+ }
66
195
  }
67
196
  });
197
+
198
+ self.patchMiddlewareChains(server, pkgMeta);
199
+ }
200
+ });
201
+ }
202
+
203
+ patchMiddlewareChains(server) {
204
+ const self = this;
205
+ const { config, routeCoverage, patcher } = this.core;
206
+
207
+ if (!config.getEffectiveValue('assess.report_middleware_routes')) return;
208
+
209
+ for (const propName of ['preChain', 'useChain']) {
210
+ patcher.patch(server[propName], 'add', {
211
+ name: `restify.server.${propName}.add`,
212
+ patchType,
213
+ around(next, data) {
214
+ const len = data.obj._stack.length;
215
+ const ret = next();
216
+
217
+ if (data.obj._stack.length > len) {
218
+ const method = StringPrototypeSubstring.call(propName, 0, 3);
219
+ const baseData = {
220
+ method,
221
+ url: '/',
222
+ normalizedUrl: '/',
223
+ type: RouteType.MIDDLEWARE,
224
+ framework: FRAMEWORK,
225
+ };
226
+
227
+ for (let idx = 0; idx < data.obj._stack.length; idx++) {
228
+ const routeData = {
229
+ ...baseData,
230
+ signature: `server.${method}(${self.formatHandler(data.obj._stack[idx])})`,
231
+ };
232
+
233
+ routeCoverage.discover(routeData);
234
+ patcher.patch(data.obj._stack, idx, {
235
+ name: `restify.server.${propName}`,
236
+ patchType,
237
+ pre({ args: [req] }) {
238
+ routeCoverage.observe({
239
+ ...routeData,
240
+ method: StringPrototypeToLowerCase.call(req.method),
241
+ url: StringPrototypeSplit.call(req.url, '?')[0],
242
+ });
243
+ },
244
+ });
245
+ }
246
+ }
247
+ return ret;
248
+ }
68
249
  });
69
250
  }
70
- };
71
- };
251
+ }
252
+ }
253
+
@@ -33,7 +33,7 @@ function createSignature(path, method = '', obj = 'Router', handler = '[Function
33
33
  /**
34
34
  * Creates a formatted handler signature for a route
35
35
  * @param {function} handler
36
- * @param {string} appDir
36
+ * @param {string=} appDir
37
37
  * @return {string} formatted handler
38
38
  */
39
39
  function formatHandler(handler, appDir) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@contrast/route-coverage",
3
- "version": "1.52.0",
3
+ "version": "1.53.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)",
@@ -20,14 +20,14 @@
20
20
  "test": "bash ../scripts/test.sh"
21
21
  },
22
22
  "dependencies": {
23
- "@contrast/common": "1.38.0",
24
- "@contrast/config": "1.54.1",
25
- "@contrast/core": "1.59.1",
26
- "@contrast/dep-hooks": "1.28.1",
23
+ "@contrast/common": "1.39.0",
24
+ "@contrast/config": "1.55.0",
25
+ "@contrast/core": "1.60.0",
26
+ "@contrast/dep-hooks": "1.29.0",
27
27
  "@contrast/fn-inspect": "^5.0.2",
28
- "@contrast/logger": "1.32.1",
29
- "@contrast/patcher": "1.31.1",
30
- "@contrast/scopes": "1.29.1",
28
+ "@contrast/logger": "1.33.0",
29
+ "@contrast/patcher": "1.32.0",
30
+ "@contrast/scopes": "1.30.0",
31
31
  "semver": "^7.6.0"
32
32
  }
33
33
  }