@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.
- package/lib/index.d.ts +2 -0
- package/lib/index.js +5 -4
- package/lib/install/express.js +535 -0
- package/lib/install/fastify/fastify-express.js +71 -0
- package/lib/install/fastify/fastify-middie.js +67 -0
- package/lib/install/{fastify.js → fastify/fastify.js} +12 -12
- package/lib/install/{express → fastify}/index.js +6 -5
- package/lib/install/hapi.js +126 -63
- package/lib/install/koa.js +39 -45
- package/lib/install/restify.js +226 -44
- package/lib/utils/route-info.js +26 -1
- package/package.json +8 -8
- package/lib/install/express/express4.js +0 -157
- package/lib/install/express/express5.js +0 -553
package/lib/index.d.ts
CHANGED
|
@@ -23,6 +23,7 @@ import { Scopes } from '@contrast/scopes';
|
|
|
23
23
|
export { RouteInfo };
|
|
24
24
|
|
|
25
25
|
export interface RouteCoverage extends Installable {
|
|
26
|
+
DISCOVERY_QUEUE_EMPTY_MS: number;
|
|
26
27
|
discover(info: RouteInfo): void;
|
|
27
28
|
discoveryFinished(): void;
|
|
28
29
|
queue(info: RouteInfo): void;
|
|
@@ -37,6 +38,7 @@ export interface Core {
|
|
|
37
38
|
readonly messages: Messages;
|
|
38
39
|
readonly patcher: Patcher;
|
|
39
40
|
readonly scopes: Scopes;
|
|
41
|
+
initComponentSync(c: any): void;
|
|
40
42
|
}
|
|
41
43
|
|
|
42
44
|
declare function init(core: Core): RouteCoverage;
|
package/lib/index.js
CHANGED
|
@@ -41,6 +41,7 @@ module.exports = function init(core) {
|
|
|
41
41
|
const routeIdentifier = (method, signature) => `${method}.${signature}`;
|
|
42
42
|
|
|
43
43
|
const routeCoverage = core.routeCoverage = {
|
|
44
|
+
DISCOVERY_QUEUE_EMPTY_MS: 10_000,
|
|
44
45
|
discover(info) {
|
|
45
46
|
const id = routeIdentifier(info.method, info.signature);
|
|
46
47
|
if (routeInfo.get(id)) return;
|
|
@@ -68,7 +69,7 @@ module.exports = function init(core) {
|
|
|
68
69
|
if (routeQueue.size === 1) {
|
|
69
70
|
setTimeout(() => {
|
|
70
71
|
this.discoveryFinished();
|
|
71
|
-
},
|
|
72
|
+
}, this.DISCOVERY_QUEUE_EMPTY_MS);
|
|
72
73
|
}
|
|
73
74
|
},
|
|
74
75
|
|
|
@@ -121,12 +122,12 @@ module.exports = function init(core) {
|
|
|
121
122
|
},
|
|
122
123
|
};
|
|
123
124
|
|
|
124
|
-
require('./install/express')
|
|
125
|
+
core.initComponentSync(require('./install/express'));
|
|
125
126
|
require('./install/fastify')(core);
|
|
126
127
|
require('./install/graphql')(core);
|
|
127
|
-
require('./install/hapi')
|
|
128
|
+
core.initComponentSync(require('./install/hapi'));
|
|
128
129
|
require('./install/koa')(core);
|
|
129
|
-
require('./install/restify')
|
|
130
|
+
core.initComponentSync(require('./install/restify'));
|
|
130
131
|
core.initComponentSync(require('./install/socket.io'));
|
|
131
132
|
|
|
132
133
|
messages.on(Event.SERVER_LISTENING, () => {
|
|
@@ -0,0 +1,535 @@
|
|
|
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 { EventEmitter } = require('events');
|
|
19
|
+
const process = require('process');
|
|
20
|
+
const {
|
|
21
|
+
get,
|
|
22
|
+
set,
|
|
23
|
+
isString,
|
|
24
|
+
Event,
|
|
25
|
+
RouteType,
|
|
26
|
+
primordials: {
|
|
27
|
+
ArrayPrototypeJoin,
|
|
28
|
+
StringPrototypeSubstring,
|
|
29
|
+
StringPrototypeToLowerCase,
|
|
30
|
+
}
|
|
31
|
+
} = require('@contrast/common');
|
|
32
|
+
const Core = require('@contrast/core/lib/ioc/core');
|
|
33
|
+
const { formatHandler } = require('../utils/route-info');
|
|
34
|
+
|
|
35
|
+
const METHODS = [
|
|
36
|
+
'all',
|
|
37
|
+
'get',
|
|
38
|
+
'post',
|
|
39
|
+
'put',
|
|
40
|
+
'delete',
|
|
41
|
+
'patch',
|
|
42
|
+
'options',
|
|
43
|
+
'head',
|
|
44
|
+
];
|
|
45
|
+
const componentName = 'routeCoverage.express';
|
|
46
|
+
const patchType = 'route-coverage-express';
|
|
47
|
+
const kMetaKey = Symbol('cs_meta');
|
|
48
|
+
|
|
49
|
+
module.exports = Core.makeComponent({
|
|
50
|
+
name: componentName,
|
|
51
|
+
factory: (core) => new ExpressInstrumentation(core),
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
class ExpressInstrumentation {
|
|
55
|
+
constructor(core) {
|
|
56
|
+
set(core, componentName, this);
|
|
57
|
+
Object.defineProperty(this, 'core', { value: core });
|
|
58
|
+
this.listenFlag = false;
|
|
59
|
+
this.isDiscoveryQueued = false;
|
|
60
|
+
this.events = new EventEmitter();
|
|
61
|
+
this.methodScope = new AsyncLocalStorage();
|
|
62
|
+
this.handleScope = new AsyncLocalStorage();
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
install() {
|
|
66
|
+
const { depHooks } = this.core;
|
|
67
|
+
depHooks.resolve({ name: 'express', version: '>=4 <6' }, (express, meta) => {
|
|
68
|
+
this.patchApplication(express.application);
|
|
69
|
+
this.patchRouter(express.Router, meta);
|
|
70
|
+
return this.patchExpress(express, meta);
|
|
71
|
+
});
|
|
72
|
+
depHooks.resolve({ name: 'express', version: '4', file: 'lib/router/layer.js' }, (Layer, meta) => this.patchLayer(Layer, meta));
|
|
73
|
+
depHooks.resolve({ name: 'router', version: '2' }, (Router, meta) => this.patchRouter(Router, meta));
|
|
74
|
+
depHooks.resolve({ name: 'router', file: 'lib/layer.js', version: '2' }, (Layer, meta) => this.patchLayer(Layer, meta));
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
patchExpress(express, pkgMeta) {
|
|
78
|
+
const self = this;
|
|
79
|
+
const { core } = self;
|
|
80
|
+
|
|
81
|
+
return core.patcher.patch(express, {
|
|
82
|
+
name: 'express.application',
|
|
83
|
+
patchType: `${patchType}-discovery`,
|
|
84
|
+
post(data) {
|
|
85
|
+
const app = data.result;
|
|
86
|
+
// force instantiation of router in express 4
|
|
87
|
+
app.lazyrouter?.();
|
|
88
|
+
|
|
89
|
+
core.messages.on(Event.SERVER_LISTENING, () => {
|
|
90
|
+
let router;
|
|
91
|
+
|
|
92
|
+
self.listenFlag = true;
|
|
93
|
+
|
|
94
|
+
try {
|
|
95
|
+
router = app._router || app.router;
|
|
96
|
+
} catch (err) {
|
|
97
|
+
/* some versions of express will error if you access deprecated router path */
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
if (!router?.stack?.[0]) {
|
|
101
|
+
core.logger.debug('no routes detected in express router stack: %s@%s', pkgMeta.name, pkgMeta.version);
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
self.handleDiscovery(router);
|
|
106
|
+
self.events.on('deferred-discovery', () => {
|
|
107
|
+
// rerun discovery if other instrumentation detects post-listen route registration
|
|
108
|
+
self.handleDiscovery(router);
|
|
109
|
+
});
|
|
110
|
+
});
|
|
111
|
+
|
|
112
|
+
return app;
|
|
113
|
+
}
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
patchApplication(application) {
|
|
118
|
+
const self = this;
|
|
119
|
+
const { core, handleScope, methodScope } = self;
|
|
120
|
+
|
|
121
|
+
[...METHODS, 'use', 'route'].forEach((method) => {
|
|
122
|
+
// then setup app and router to run in method scopes
|
|
123
|
+
core.patcher.patch(application, method, {
|
|
124
|
+
name: `express.application.${method}`,
|
|
125
|
+
patchType: `${patchType}-discovery`,
|
|
126
|
+
around(next, data) {
|
|
127
|
+
if (methodScope.getStore()) return next();
|
|
128
|
+
return methodScope.run({ method, args: data.args, type: 'app' }, next);
|
|
129
|
+
}
|
|
130
|
+
});
|
|
131
|
+
});
|
|
132
|
+
|
|
133
|
+
core.patcher.patch(application, 'handle', {
|
|
134
|
+
name: 'express.application.handle',
|
|
135
|
+
patchType: `${patchType}-discovery`,
|
|
136
|
+
around(next, data) {
|
|
137
|
+
// wrap request handling in "handle scope". the scope's store data
|
|
138
|
+
// helps for building observation templates as routing occurs
|
|
139
|
+
const store = { templateSegments: [] };
|
|
140
|
+
return handleScope.run(store, next);
|
|
141
|
+
}
|
|
142
|
+
});
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
patchRouter(Router, pkgMeta) {
|
|
146
|
+
const self = this;
|
|
147
|
+
const { core, methodScope } = this;
|
|
148
|
+
// express 4 uses setPrototypeOf
|
|
149
|
+
const patchTarget = (pkgMeta?.name == 'express' && pkgMeta?.version[0] == '4') ?
|
|
150
|
+
Router.prototype?.constructor :
|
|
151
|
+
Router.prototype;
|
|
152
|
+
|
|
153
|
+
if (!patchTarget) {
|
|
154
|
+
const descriptor = pkgMeta?.version ? `express ${pkgMeta.version}` : 'router package';
|
|
155
|
+
core.logger.error(`no router patch target for ${descriptor}`);
|
|
156
|
+
return Router;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
// wrap router and app methods in "method scope" to capture info to help build signatures.
|
|
160
|
+
// express has a number of APIs that work at different levels of abstraction, and we need to patch
|
|
161
|
+
// all of them. the scopes let us know what top-level APIs are being called by application code.
|
|
162
|
+
[...METHODS, 'use', 'route'].forEach((method) => {
|
|
163
|
+
core.patcher.patch(patchTarget, method, {
|
|
164
|
+
name: `express.Router.prototype.${method}`,
|
|
165
|
+
patchType: `${patchType}-discovery`,
|
|
166
|
+
around(next, data) {
|
|
167
|
+
if (method == 'use') data._stackLength = data.obj.stack?.length;
|
|
168
|
+
|
|
169
|
+
const ret = methodScope.getStore() ?
|
|
170
|
+
next() :
|
|
171
|
+
methodScope.run({ method, args: data.args, type: 'router' }, next);
|
|
172
|
+
|
|
173
|
+
if (method == 'use' && data.obj.stack.length > data._stackLength) {
|
|
174
|
+
for (let i = data._stackLength; i < data.obj.stack.length; i++) {
|
|
175
|
+
const layer = data.obj.stack[i];
|
|
176
|
+
const methodStore = methodScope.getStore();
|
|
177
|
+
|
|
178
|
+
const meta = {
|
|
179
|
+
template: ExpressInstrumentation.normalizeTemplate(data.args[0]),
|
|
180
|
+
method: 'use',
|
|
181
|
+
type: methodStore?.type || 'router',
|
|
182
|
+
};
|
|
183
|
+
|
|
184
|
+
if (layer) {
|
|
185
|
+
self.attachDiscoveryMeta(layer, meta);
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
return ret;
|
|
191
|
+
}
|
|
192
|
+
});
|
|
193
|
+
});
|
|
194
|
+
|
|
195
|
+
// app[method] and router[method] end up calling this
|
|
196
|
+
// Append metadata to the created Route object at layer.route.
|
|
197
|
+
// we also patch the returned Route's methods for building signatures
|
|
198
|
+
core.patcher.patch(patchTarget, 'route', {
|
|
199
|
+
name: 'express.Route',
|
|
200
|
+
patchType: `${patchType}-discovery`,
|
|
201
|
+
post(data) {
|
|
202
|
+
const { result } = data;
|
|
203
|
+
const methodStore = methodScope.getStore();
|
|
204
|
+
const meta = {
|
|
205
|
+
template: ExpressInstrumentation.normalizeTemplate(data.args[0]),
|
|
206
|
+
method: methodStore?.method,
|
|
207
|
+
type: methodStore?.type || 'route',
|
|
208
|
+
};
|
|
209
|
+
|
|
210
|
+
self.attachDiscoveryMeta(result, meta);
|
|
211
|
+
|
|
212
|
+
// patch route instance methods we do that here when we have
|
|
213
|
+
// todo move to prototype to help w/ memory
|
|
214
|
+
METHODS.forEach((method) => {
|
|
215
|
+
if (result[method]) {
|
|
216
|
+
core.patcher.patch(result, method, {
|
|
217
|
+
name: `express.Router.prototype.route${method}`,
|
|
218
|
+
patchType: `${patchType}-discovery`,
|
|
219
|
+
pre(data) {
|
|
220
|
+
data._stackIdx = data.obj.stack?.length;
|
|
221
|
+
},
|
|
222
|
+
post(data) {
|
|
223
|
+
if (data.obj.stack?.length > data._stackIdx) {
|
|
224
|
+
for (let i = data._stackIdx; i < data.obj.stack.length; i++) {
|
|
225
|
+
const layer = data.obj.stack[i];
|
|
226
|
+
const methodStore = methodScope.getStore();
|
|
227
|
+
const meta = {
|
|
228
|
+
type: methodStore?.type || 'route',
|
|
229
|
+
method: methodStore?.method == 'all' ? 'all' : method,
|
|
230
|
+
};
|
|
231
|
+
|
|
232
|
+
self.attachDiscoveryMeta(layer, meta);
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
},
|
|
236
|
+
});
|
|
237
|
+
}
|
|
238
|
+
});
|
|
239
|
+
|
|
240
|
+
return result;
|
|
241
|
+
},
|
|
242
|
+
});
|
|
243
|
+
|
|
244
|
+
return Router;
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
patchLayer(Layer, pkgMeta) {
|
|
248
|
+
const self = this;
|
|
249
|
+
const { core, handleScope, methodScope } = self;
|
|
250
|
+
|
|
251
|
+
// when Layer.match gets called, matchers functions run underneath. the API doesn't present a really clean
|
|
252
|
+
// way to instrument, so we're using scopes. we reference the scope's store in the instrumented matcher
|
|
253
|
+
// functions so we can correlate a matcher that succeeds to its corresponding route template segment.
|
|
254
|
+
core.patcher.patch(Layer.prototype, 'match', {
|
|
255
|
+
name: 'Layer.prototype.match',
|
|
256
|
+
patchType: `${patchType}-observation`,
|
|
257
|
+
pre(data) {
|
|
258
|
+
data._store = handleScope.getStore();
|
|
259
|
+
if (!data._store) return;
|
|
260
|
+
data[kMetaKey] = data.obj[kMetaKey] || data.obj.route?.[kMetaKey];
|
|
261
|
+
},
|
|
262
|
+
post(data) {
|
|
263
|
+
const { result } = data;
|
|
264
|
+
if (!result || !data._store || !data[kMetaKey]?.template) return;
|
|
265
|
+
// if the layer matches, we know to push corresponding path to store's template segments.
|
|
266
|
+
// we pop this value from the array in hook to all `next` callbacks below.
|
|
267
|
+
data._store.templateSegments.push(data[kMetaKey].template);
|
|
268
|
+
}
|
|
269
|
+
});
|
|
270
|
+
|
|
271
|
+
// patch the `next` callback of every Layer's request handler.
|
|
272
|
+
// we pop the value from the stack of route template segments being managed.
|
|
273
|
+
const handleRequest = pkgMeta.name == 'express' && pkgMeta.version[0] == '4' ? 'handle_request' : 'handleRequest';
|
|
274
|
+
core.patcher.patch(Layer.prototype, handleRequest, {
|
|
275
|
+
name: `Layer.prototype.${handleRequest}`,
|
|
276
|
+
patchType: `${patchType}-observation`,
|
|
277
|
+
pre(data) {
|
|
278
|
+
const next = data.args[2];
|
|
279
|
+
const meta = data.obj[kMetaKey] || data.obj.route?.[kMetaKey];
|
|
280
|
+
|
|
281
|
+
if (meta.template) {
|
|
282
|
+
const store = handleScope.getStore();
|
|
283
|
+
// this runs often and there's no need to use patcher here. monkey patch directly to optimize
|
|
284
|
+
data.args[2] = function (...args) {
|
|
285
|
+
if (store) store.templateSegments.pop();
|
|
286
|
+
const ret = next(...args);
|
|
287
|
+
return ret;
|
|
288
|
+
};
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
});
|
|
292
|
+
|
|
293
|
+
// instrument the Layer constructor. this will allow us to patch
|
|
294
|
+
// created matchers to help us build observation template from metadata.
|
|
295
|
+
// if matcher was successful we store index of it in handle scope.
|
|
296
|
+
return core.patcher.patch(Layer, {
|
|
297
|
+
name: 'router.Layer',
|
|
298
|
+
patchType: `${patchType}-observation`,
|
|
299
|
+
pre(data) {
|
|
300
|
+
data._methodScope = methodScope.getStore();
|
|
301
|
+
},
|
|
302
|
+
post(data) {
|
|
303
|
+
const instance = data.result;
|
|
304
|
+
|
|
305
|
+
// patch handle to report observation when called. it checks handle
|
|
306
|
+
// scope to get current request's template to match with discovery info
|
|
307
|
+
core.patcher.patch(instance, 'handle', {
|
|
308
|
+
name: 'router.Layer.handle',
|
|
309
|
+
patchType: `${patchType}-observation`,
|
|
310
|
+
pre(data) {
|
|
311
|
+
if (instance[kMetaKey]?.observables) {
|
|
312
|
+
const store = handleScope.getStore();
|
|
313
|
+
if (store) {
|
|
314
|
+
const method = StringPrototypeToLowerCase.call(data.args[0].method || '');
|
|
315
|
+
const template = ArrayPrototypeJoin.call(store.templateSegments, '') || '/';
|
|
316
|
+
|
|
317
|
+
if (instance[kMetaKey]?.observables?.[template]) {
|
|
318
|
+
self.observe({
|
|
319
|
+
url: data.args[0].originalUrl,
|
|
320
|
+
normalizedUrl: template,
|
|
321
|
+
method,
|
|
322
|
+
signature: instance[kMetaKey].observables[template],
|
|
323
|
+
type: instance[kMetaKey].routeType,
|
|
324
|
+
});
|
|
325
|
+
} else {
|
|
326
|
+
// one example that will trigger this logging is recursive routers
|
|
327
|
+
// this will at least log that something like this has been encountered
|
|
328
|
+
core.logger.error({
|
|
329
|
+
method,
|
|
330
|
+
template,
|
|
331
|
+
observables: instance[kMetaKey]?.observables,
|
|
332
|
+
}, 'unable to map route template to signature');
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
},
|
|
337
|
+
});
|
|
338
|
+
},
|
|
339
|
+
});
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
discover(info) {
|
|
343
|
+
const { method, observables, routeType } = info;
|
|
344
|
+
if (!method || !observables) return;
|
|
345
|
+
|
|
346
|
+
for (const [normalizedUrl, signature] of Object.entries(observables)) {
|
|
347
|
+
this.core.routeCoverage.discover({
|
|
348
|
+
url: normalizedUrl,
|
|
349
|
+
normalizedUrl,
|
|
350
|
+
method,
|
|
351
|
+
signature,
|
|
352
|
+
type: routeType,
|
|
353
|
+
framework: 'express',
|
|
354
|
+
});
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
observe(info) {
|
|
359
|
+
this.core.routeCoverage.observe({ framework: 'express', ...info });
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
/**
|
|
363
|
+
* Traverse the application's router "stack" and generate route discovery events
|
|
364
|
+
* using layer/route metadata that was appended by methods like router.post().
|
|
365
|
+
* @param {object} stack express application's router stack
|
|
366
|
+
*/
|
|
367
|
+
handleDiscovery(router) {
|
|
368
|
+
const self = this;
|
|
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
|
+
// `value` is a terminal Layer with observable signatures.
|
|
400
|
+
// emit discovery after appending metadata.
|
|
401
|
+
if (value[kMetaKey]) {
|
|
402
|
+
const observables = this.generateObservables(metas, value.handle);
|
|
403
|
+
if (observables) {
|
|
404
|
+
value[kMetaKey].routeType = routeType;
|
|
405
|
+
if (!value[kMetaKey].observables) {
|
|
406
|
+
value[kMetaKey].observables = observables;
|
|
407
|
+
} else {
|
|
408
|
+
Object.assign(value[kMetaKey].observables, observables);
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
self.discover(value[kMetaKey]);
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
});
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
/**
|
|
418
|
+
* Traverses the top-level app's routing stack and executes the provided callback when
|
|
419
|
+
* visiting nodes. The callback is invoked only to visit Layer instances, objects and
|
|
420
|
+
* functions, since these are the only 2 types that could have our metadata attached.
|
|
421
|
+
*/
|
|
422
|
+
traverse(target, cb, path = [], data = new Map()) {
|
|
423
|
+
loopKeys: for (const key in target) {
|
|
424
|
+
path.push(key);
|
|
425
|
+
|
|
426
|
+
// only visit Layer instances
|
|
427
|
+
const maybeLayer = target[key];
|
|
428
|
+
if (
|
|
429
|
+
maybeLayer?.constructor?.name == 'Layer' &&
|
|
430
|
+
!maybeLayer?.stack?.length
|
|
431
|
+
) {
|
|
432
|
+
let _data = data.get(maybeLayer);
|
|
433
|
+
|
|
434
|
+
if (!_data) {
|
|
435
|
+
_data = { paths: [] };
|
|
436
|
+
data.set(maybeLayer, _data);
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
// you can mount a router on itself
|
|
440
|
+
// prevent infinitely recursing into self-mounted routers
|
|
441
|
+
for (const visitedPath of _data.paths) {
|
|
442
|
+
// these conditions indicate recursive nesting at particular path
|
|
443
|
+
if (
|
|
444
|
+
path.length > visitedPath.length &&
|
|
445
|
+
visitedPath.every((el, i) => path[i] == el)
|
|
446
|
+
) {
|
|
447
|
+
path.pop();
|
|
448
|
+
continue loopKeys;
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
_data.paths.push([...path]); // copy because path argument mutates
|
|
453
|
+
|
|
454
|
+
const halt = cb(path, key, maybeLayer, target) === false;
|
|
455
|
+
if (halt) return;
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
// might be able to fine-tune this a bit more
|
|
459
|
+
if (typeof maybeLayer == 'object' || typeof maybeLayer == 'function') {
|
|
460
|
+
this.traverse(maybeLayer, cb, path, data);
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
path.pop();
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
generateObservables(metas, handler) {
|
|
468
|
+
const { core } = this;
|
|
469
|
+
handler = core.patcher.unwrap(handler);
|
|
470
|
+
|
|
471
|
+
let type = '';
|
|
472
|
+
let method = '';
|
|
473
|
+
const templates = [];
|
|
474
|
+
|
|
475
|
+
// loop backwards
|
|
476
|
+
for (let i = metas.length - 1; i >= 0; i--) {
|
|
477
|
+
const meta = metas[i];
|
|
478
|
+
// use the most recent `type` and `method` used when building routes, so don't overwrite if set
|
|
479
|
+
if (!type && meta.type) type = meta.type;
|
|
480
|
+
if (!method && meta.method) method = meta.method;
|
|
481
|
+
templates.unshift(meta.template ?? '');
|
|
482
|
+
}
|
|
483
|
+
let template = ArrayPrototypeJoin.call(templates, '');
|
|
484
|
+
if (template == '') template = '/';
|
|
485
|
+
const signature = `${type}.${method}(${template}, ${formatHandler(handler)})`;
|
|
486
|
+
|
|
487
|
+
// this gets merged into meta.observables if same route handler is mounted at multiple paths
|
|
488
|
+
return {
|
|
489
|
+
[template]: signature,
|
|
490
|
+
};
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
attachDiscoveryMeta(target, meta) {
|
|
494
|
+
// if this is called after the server was listening we need to re-traverse
|
|
495
|
+
if (this.listenFlag && !this.isDiscoveryQueued) {
|
|
496
|
+
this.isDiscoveryQueued = true;
|
|
497
|
+
process.nextTick(() => {
|
|
498
|
+
this.isDiscoveryQueued = false;
|
|
499
|
+
this.events.emit('deferred-discovery');
|
|
500
|
+
});
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
Object.defineProperty(target, kMetaKey, {
|
|
504
|
+
enumerable: false,
|
|
505
|
+
value: meta,
|
|
506
|
+
});
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
static normalizeTemplate(paths) {
|
|
510
|
+
if (typeof paths == 'function') return '';
|
|
511
|
+
if (isString(paths)) return ExpressInstrumentation.normalizePathSegment(paths);
|
|
512
|
+
if (paths instanceof RegExp) return ExpressInstrumentation.normalizePathSegment(paths);
|
|
513
|
+
|
|
514
|
+
if (Array.isArray(paths)) {
|
|
515
|
+
const ret = [];
|
|
516
|
+
paths = paths.flat(Infinity).filter((v) => typeof v !== 'function');
|
|
517
|
+
if (paths.length) ret.push(...paths.map((v) => ExpressInstrumentation.normalizePathSegment(v) || '/'));
|
|
518
|
+
else ret.push('');
|
|
519
|
+
return ret.length > 1 ? `[${ArrayPrototypeJoin.call(ret, ', ')}]` : ret[0];
|
|
520
|
+
}
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
static normalizePathSegment(value) {
|
|
524
|
+
if (!value || value == '/') {
|
|
525
|
+
// app.[method](handler) and app.[method]('/', handler) are the same so default to empty string
|
|
526
|
+
return '';
|
|
527
|
+
}
|
|
528
|
+
if (value instanceof RegExp) {
|
|
529
|
+
const rxString = value.toString();
|
|
530
|
+
// todo: figure out best way to represent regexp in route template
|
|
531
|
+
return `/[${StringPrototypeSubstring.call(rxString, 1, rxString.length - 1)}]`;
|
|
532
|
+
}
|
|
533
|
+
return value;
|
|
534
|
+
}
|
|
535
|
+
}
|
|
@@ -0,0 +1,71 @@
|
|
|
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, scopes } = core;
|
|
22
|
+
|
|
23
|
+
return core.routeCoverage.fastifyExpress = {
|
|
24
|
+
install() {
|
|
25
|
+
const name = 'fastifyExpress';
|
|
26
|
+
depHooks.resolve({ name: '@fastify/express', version: '*' }, (_xport) => patcher.patch(_xport, {
|
|
27
|
+
name,
|
|
28
|
+
patchType,
|
|
29
|
+
post(data) {
|
|
30
|
+
const store = { lock: true, name };
|
|
31
|
+
patcher.patch(data.args[0], 'use', {
|
|
32
|
+
name: 'use',
|
|
33
|
+
patchType,
|
|
34
|
+
around(next, data) {
|
|
35
|
+
const [url, fn] = data.args;
|
|
36
|
+
if (!url || !fn || !core.config.getEffectiveValue('assess.report_middleware_routes')) return next();
|
|
37
|
+
|
|
38
|
+
const middleware = isArray(fn) ? fn : [fn];
|
|
39
|
+
const formattedPath = isArray(url) ? `[${url.join(', ')}]` : url;
|
|
40
|
+
const patchedMiddleware = middleware.map((f) => {
|
|
41
|
+
const formattedHandler = formatHandler(f);
|
|
42
|
+
const signature = `fastify.use(${formattedPath}, ${formattedHandler})`;
|
|
43
|
+
|
|
44
|
+
const routeInfo = {
|
|
45
|
+
signature,
|
|
46
|
+
url: formattedPath,
|
|
47
|
+
method: 'use',
|
|
48
|
+
normalizedUrl: formattedPath,
|
|
49
|
+
type: RouteType.MIDDLEWARE,
|
|
50
|
+
framework: 'fastify'
|
|
51
|
+
};
|
|
52
|
+
routeCoverage.discover(routeInfo);
|
|
53
|
+
|
|
54
|
+
return patcher.patch(f, {
|
|
55
|
+
name: 'middleware',
|
|
56
|
+
patchType,
|
|
57
|
+
post() {
|
|
58
|
+
routeCoverage.observe(routeInfo);
|
|
59
|
+
}
|
|
60
|
+
});
|
|
61
|
+
});
|
|
62
|
+
data.args[1] = patchedMiddleware;
|
|
63
|
+
|
|
64
|
+
return !scopes.instrumentation.isLocked() ? scopes.instrumentation.run(store, next) : next();
|
|
65
|
+
}
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
}));
|
|
69
|
+
}
|
|
70
|
+
};
|
|
71
|
+
};
|