@contrast/agent 4.5.1 → 4.5.2

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.
@@ -19,7 +19,6 @@ const TagRange = require('../../models/tag-range');
19
19
  const tagRangeUtil = require('../../models/tag-range/util');
20
20
  const tracker = require('../../../tracker');
21
21
  const path = require('path');
22
- let trackingSeparators;
23
22
 
24
23
  /**
25
24
  * Splits string by separator
@@ -31,8 +30,9 @@ let trackingSeparators;
31
30
  */
32
31
  function splitString(str, win32) {
33
32
  // windows treats both (forward and backward) slashes as separators
34
- const posixRegEx = trackingSeparators ? /(?=\/)/g : /(\/)/g;
35
- const win32RegEx = trackingSeparators ? /(?=[/\\])/g : /[/\\]/g;
33
+ const posixRegEx = /(?=\/)/g;
34
+ const win32RegEx = /(?=[/\\])/g;
35
+
36
36
  if (win32) {
37
37
  str = str.replace(/\//g, '\\').split(win32RegEx);
38
38
  } else {
@@ -55,29 +55,26 @@ function splitString(str, win32) {
55
55
  *
56
56
  * @param {Object} meta object of metadata from result/arg
57
57
  * @param {(segmentOffset: number) => boolean} meta.evaluator expression to determine the proper position of segment in string
58
- * @param {number} meta.offset offset of full arg from result of path.resolve
59
58
  * @param {string} meta.str result from path.resolve or arg
59
+ * @param {number} offset offset of full arg from result of path.resolve
60
60
  * @param {string} segment path segment from one of the args to path.resolve
61
61
  */
62
- function getSegmentOffset({ str, offset, evaluator }, segment, win32) {
62
+ function getSegmentOffset({ str, evaluator }, offset, segment, win32) {
63
63
  // as the segments in each arg and in the result get traversed,
64
64
  // winnow away the string to ensure we are finding the proper
65
65
  // segment within the path
66
66
  const substr = str.substring(offset);
67
67
  let segmentOffset = substr.indexOf(segment);
68
68
  // If tracking separators, evaluator will fail on extensions
69
- if (trackingSeparators && substr === `.${segment}`) {
69
+ if (substr === `.${segment}`) {
70
70
  return segmentOffset + offset;
71
71
  }
72
72
  // Adjust offset if the segment does not start with a separator
73
73
  const { sep } = path[win32 ? 'win32' : 'posix'];
74
- if (
75
- trackingSeparators &&
76
- substr.startsWith(sep) &&
77
- !segment.startsWith(sep)
78
- ) {
74
+ if (substr.startsWith(sep) && !segment.startsWith(sep)) {
79
75
  segmentOffset--;
80
76
  }
77
+
81
78
  return evaluator(segmentOffset) ? segmentOffset + offset : -1;
82
79
  }
83
80
 
@@ -90,7 +87,12 @@ function getSegmentOffset({ str, offset, evaluator }, segment, win32) {
90
87
  */
91
88
  function isWithinTag(str, start, tag) {
92
89
  const stop = str.length - 1 + start;
93
- return tag.overlaps({ start, stop, tag: tag.tag });
90
+
91
+ return (
92
+ (stop <= tag.stop && stop >= tag.start) ||
93
+ (start >= tag.start && start <= tag.stop) ||
94
+ (tag.start >= start && tag.start <= stop)
95
+ );
94
96
  }
95
97
 
96
98
  /**
@@ -103,6 +105,7 @@ function isWithinTag(str, start, tag) {
103
105
  */
104
106
  function adjustStart({ tag, argOffset, offset }) {
105
107
  const start = tag.start - argOffset;
108
+
106
109
  return start > 0 ? start + offset : offset;
107
110
  }
108
111
 
@@ -154,16 +157,13 @@ function maybeUpdateResultMeta({ index, arg, resultMeta }) {
154
157
  }
155
158
 
156
159
  /**
157
- * Encapsulates moving the resultOffset based on a segment
160
+ * Calculates a new offset based on a segment
158
161
  *
159
- * @param {Object} resultMeta metadata from result of path.resolve
160
- * @param {Object} argMeta metadata for a given argument
162
+ * @param {Object} offset offset of the object
161
163
  * @param {string} segment path segment from one of the args to path.resolve
162
164
  */
163
- function calculateNewOffset(resultMeta, argMeta, segment) {
164
- const separatorOffset = trackingSeparators ? 0 : 1;
165
- resultMeta.offset = resultMeta.offset + segment.length + separatorOffset;
166
- argMeta.offset = argMeta.offset + segment.length + separatorOffset;
165
+ function calculateNewOffset(offset, segment) {
166
+ return offset + segment.length;
167
167
  }
168
168
 
169
169
  /**
@@ -173,10 +173,89 @@ function calculateNewOffset(resultMeta, argMeta, segment) {
173
173
  * @param {string} segment path segment to check
174
174
  * @return {boolean}
175
175
  */
176
- function applicableSegment(segment) {
176
+ function isApplicableSegment(segment) {
177
177
  return segment !== '.' && segment !== '..' && segment !== '';
178
178
  }
179
179
 
180
+ /**
181
+ * Filters invalid segments like those that are not part of the end result.
182
+ * It also calculates additional offset.
183
+ *
184
+ * @param {*} segments splitted path into segments
185
+ * @param {Object} resultMeta metadata from result of path.resolve
186
+ * @param {Object} data the data object of the propagate function
187
+ * @param {number} index the iteration index
188
+ * @param {boolean} win32 indicating win32 to replace `/` with `\'
189
+ */
190
+ function filterSegmentsAndCalculateOffset(
191
+ segments,
192
+ resultMeta,
193
+ data,
194
+ index,
195
+ win32
196
+ ) {
197
+ const { sep } = path[win32 ? 'win32' : 'posix'];
198
+ const isFirstIteration = index === 0;
199
+ const validSegments = [];
200
+ let additionalOffset = 0;
201
+
202
+ segments.reduce(
203
+ // eslint-disable-next-line complexity
204
+ (accumulator, segment) => {
205
+ let hasChange = false;
206
+ if (!isApplicableSegment(segment)) return accumulator;
207
+
208
+ if (!accumulator.isModified && !isFirstIteration) {
209
+ const previousArg = data.args[index - 1];
210
+
211
+ const sepAdded = !segment.startsWith(sep) && !previousArg.endsWith(sep);
212
+ const sepTaken = segment.startsWith(sep) && previousArg.endsWith(sep);
213
+ accumulator.isModified = sepAdded || sepTaken;
214
+ hasChange = sepAdded || sepTaken;
215
+ additionalOffset = hasChange ? (sepAdded ? 1 : -1) : 0;
216
+ }
217
+
218
+ const offset = getSegmentOffset(
219
+ resultMeta,
220
+ accumulator.offset + additionalOffset + accumulator.fileDotSeparator,
221
+ segment,
222
+ win32
223
+ );
224
+
225
+ // no reason to proceed if segment is not in final result
226
+ if (offset === -1) {
227
+ if (hasChange) {
228
+ additionalOffset = 0;
229
+ accumulator.isModified = false;
230
+ }
231
+
232
+ return accumulator;
233
+ }
234
+
235
+ // in case we have a file we need to increment the offset
236
+ if (resultMeta.str[offset + segment.length] === '.') {
237
+ accumulator.fileDotSeparator = 1;
238
+ }
239
+
240
+ validSegments.push(segment);
241
+ accumulator.offset = calculateNewOffset(accumulator.offset, segment);
242
+ accumulator.isModified = true;
243
+
244
+ return accumulator;
245
+ },
246
+ {
247
+ offset: resultMeta.offset,
248
+ fileDotSeparator: 0,
249
+ isModified: false
250
+ }
251
+ );
252
+
253
+ return {
254
+ additionalOffset,
255
+ segments: validSegments
256
+ };
257
+ }
258
+
180
259
  /**
181
260
  * Moves the tag ranges properly based on if a path segment exists in the
182
261
  * result
@@ -184,43 +263,66 @@ function applicableSegment(segment) {
184
263
  * @param {Object} resultMeta metadata for the result
185
264
  * @param {Object} argMeta meta for a given argument
186
265
  * @param {boolean} win32 indicating win32 to replace `/` with `\'
266
+ * @param {Object} data the data object of the propagate function
267
+ * @param {number} index the iteration index
187
268
  */
188
- function adjustTagsToPart(resultMeta, argMeta, win32) {
269
+ function adjustTagsToPart(resultMeta, argMeta, win32, data, index) {
189
270
  const { str, tagRanges } = argMeta;
190
- const segments = splitString(str, win32);
191
- const newTags = [];
192
- segments.forEach((segment) => {
193
- if (!applicableSegment(segment)) {
194
- return;
195
- }
196
- const offset = getSegmentOffset(resultMeta, segment, win32);
197
- // no reason to proceed if segment is not in final result
198
- if (offset === -1) {
199
- return;
200
- }
271
+ const { segments, additionalOffset } = filterSegmentsAndCalculateOffset(
272
+ splitString(str, win32),
273
+ resultMeta,
274
+ data,
275
+ index,
276
+ win32
277
+ );
278
+
279
+ // updating the offset
280
+ resultMeta.offset += additionalOffset;
281
+
282
+ return segments.reduce((newTags, segment) => {
283
+ const offset = getSegmentOffset(
284
+ resultMeta,
285
+ resultMeta.offset,
286
+ segment,
287
+ win32
288
+ );
289
+
290
+ const argOffset = getSegmentOffset(argMeta, argMeta.offset, segment, win32);
201
291
 
202
- const argOffset = getSegmentOffset(argMeta, segment, win32);
292
+ // updating the offset
293
+ resultMeta.offset = calculateNewOffset(resultMeta.offset, segment);
294
+ argMeta.offset = calculateNewOffset(argMeta.offset, segment);
203
295
 
204
- calculateNewOffset(resultMeta, argMeta, segment);
296
+ // in case we have a file we need to increment the offset
297
+ if (resultMeta.str[offset + segment.length] === '.') {
298
+ resultMeta.offset += 1;
299
+ }
205
300
 
206
301
  tagRanges.forEach((tag) => {
207
- if (isWithinTag(segment, argOffset, tag)) {
208
- const start = adjustStart({ tag, argOffset, offset });
209
- const stop = adjustStop({ tag, argOffset, offset, segment });
302
+ if (!isWithinTag(segment, argOffset, tag)) return;
210
303
 
211
- newTags.push(new TagRange(start, stop, tag.tag));
212
- }
304
+ const start = adjustStart({
305
+ tag,
306
+ argOffset,
307
+ offset
308
+ });
309
+ const stop = adjustStop({
310
+ tag,
311
+ argOffset,
312
+ offset,
313
+ segment
314
+ });
315
+
316
+ newTags.push(new TagRange(start, stop, tag.tag));
213
317
  });
214
- });
215
318
 
216
- return newTags;
319
+ return newTags;
320
+ }, []);
217
321
  }
218
322
 
219
- function propagate({ resultMeta, data, win32, trackSeparators }) {
220
- trackingSeparators = trackSeparators;
323
+ function propagate({ resultMeta, data, win32 }) {
221
324
  if (!resultMeta.evaluator) {
222
- resultMeta.evaluator = (segmentOffset) =>
223
- segmentOffset === (trackingSeparators ? 0 : 1);
325
+ resultMeta.evaluator = (segmentOffset) => segmentOffset === 0;
224
326
  }
225
327
 
226
328
  data.args.forEach((arg, index) => {
@@ -234,13 +336,20 @@ function propagate({ resultMeta, data, win32, trackSeparators }) {
234
336
  tagRanges: argData.tracked ? argData.tagRanges : []
235
337
  };
236
338
 
237
- const targetTagRanges = adjustTagsToPart(resultMeta, argMeta, win32);
339
+ const targetTagRanges = adjustTagsToPart(
340
+ resultMeta,
341
+ argMeta,
342
+ win32,
343
+ data,
344
+ index
345
+ );
238
346
 
239
347
  if (targetTagRanges.length > 0) {
240
348
  resultMeta.parents.push(argData.event);
241
349
  tagRangeUtil.addAllInPlace(resultMeta.tagRanges, targetTagRanges);
242
350
  }
243
351
  });
352
+
244
353
  trackResult(resultMeta, data);
245
354
  }
246
355
 
@@ -31,7 +31,11 @@ function hookPath(path) {
31
31
  resultMeta.offset = 0;
32
32
  resultMeta.evaluator = (segmentOffset) => segmentOffset === 0;
33
33
  }
34
- propagate({ data, resultMeta, win32: os === 'win32' });
34
+ propagate({
35
+ data,
36
+ resultMeta,
37
+ win32: os === 'win32'
38
+ });
35
39
  }
36
40
  });
37
41
  }
@@ -46,8 +46,7 @@ module.exports.handle = function handle() {
46
46
  propagate({
47
47
  resultMeta,
48
48
  data,
49
- win32: os === 'win32',
50
- trackSeparators: true
49
+ win32: os === 'win32'
51
50
  });
52
51
  }
53
52
  });
@@ -34,7 +34,12 @@ module.exports.handle = function handle() {
34
34
  if (!data.args[0]) return;
35
35
  const resultMeta = getResultMeta(data, 'resolve');
36
36
  const isAbsolute = absolutePath(data.args[0]);
37
- resultMeta.offset = isAbsolute ? 0 : process.cwd().length;
37
+
38
+ /*
39
+ plus one in case isAbsolute is false since our working deretory ends without slash
40
+ example: /Users/John/Documents/Projects/node-agent
41
+ */
42
+ resultMeta.offset = isAbsolute ? 0 : process.cwd().length + 1;
38
43
 
39
44
  // a work-around for paths like C:\Windows
40
45
  if (
@@ -45,7 +50,11 @@ module.exports.handle = function handle() {
45
50
  resultMeta.evaluator = (segmentOffset) => segmentOffset > -1;
46
51
  }
47
52
 
48
- propagate({ data, resultMeta, win32: os === 'win32' });
53
+ propagate({
54
+ data,
55
+ resultMeta,
56
+ win32: os === 'win32'
57
+ });
49
58
  }
50
59
  });
51
60
  }
@@ -18,7 +18,6 @@ const agentEmitter = require('../../agent-emitter');
18
18
  const { PATCH_TYPES } = require('../../constants');
19
19
  const ModuleHook = require('../../hooks/require');
20
20
  const patcher = require('../../hooks/patcher');
21
- const _ = require('lodash');
22
21
 
23
22
  ModuleHook.resolve({ name: 'aws-sdk' }, (AWS) => {
24
23
  patcher.patch(AWS.DynamoDB.prototype, 'makeRequest', {
@@ -27,7 +26,7 @@ ModuleHook.resolve({ name: 'aws-sdk' }, (AWS) => {
27
26
  alwaysRun: true,
28
27
  post(ctx) {
29
28
  try {
30
- const endpoint = _.get(this, 'endpoint');
29
+ const { endpoint } = this;
31
30
  agentEmitter.emit('architectureComponent', {
32
31
  vendor: 'DynamoDB',
33
32
  url: new URL(`${endpoint.protocol}//${endpoint.hostname}`).toString(),
@@ -0,0 +1,44 @@
1
+ /**
2
+ Copyright: 2021 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
+ const logger = require('../logger')('contrast:arch-component');
17
+ const agentEmitter = require('../../agent-emitter');
18
+ const { PATCH_TYPES } = require('../../constants');
19
+ const ModuleHook = require('../../hooks/require');
20
+ const patcher = require('../../hooks/patcher');
21
+
22
+ function emitArchitectureComponent(endpoint) {
23
+ agentEmitter.emit('architectureComponent', {
24
+ vendor: 'DynamoDB',
25
+ url: new URL(`${endpoint.protocol}//${endpoint.hostname}`).toString(),
26
+ remoteHost: '',
27
+ remotePort: endpoint.port
28
+ });
29
+ }
30
+
31
+ ModuleHook.resolve({ name: '@aws-sdk/client-dynamodb' }, (AWS) => {
32
+ patcher.patch(AWS.DynamoDBClient.prototype, 'send', {
33
+ name: 'DynamoDBv3.arch_component',
34
+ patchType: PATCH_TYPES.ARCH_COMPONENT,
35
+ alwaysRun: true,
36
+ post(ctx) {
37
+ try {
38
+ this.config.endpoint().then(emitArchitectureComponent);
39
+ } catch (err) {
40
+ logger.warn('unable to report DynamoDB architecture component\n', err);
41
+ }
42
+ }
43
+ });
44
+ });
@@ -17,3 +17,4 @@ require('./mysql');
17
17
  require('./sqlite3');
18
18
  require('./postgres');
19
19
  require('./dynamodb');
20
+ require('./dynamodbv3');
@@ -36,6 +36,7 @@ const {
36
36
  SCOPE_NAMES: { NO_PROPAGATION }
37
37
  } = require('../core/async-storage/scopes');
38
38
  const promisifyCustom = Symbol.for('nodejs.util.promisify.custom');
39
+ const some = require('../util/some');
39
40
 
40
41
  // When a pre-hook returns the result of this function, the value passed will
41
42
  // be used in place of the original function's return value, and the original
@@ -109,6 +110,15 @@ function runHooks(type, options, data, fn, thisTarget) {
109
110
  });
110
111
  }
111
112
 
113
+ /**
114
+ * Checks if any of the provided arguments are tracked.
115
+ * @param {any[]} args
116
+ * @return {boolean}
117
+ */
118
+ function argsTracked(args) {
119
+ return some(args, (arg) => arg && tracker.getData(arg).tracked);
120
+ }
121
+
112
122
  /**
113
123
  * Whether to skip the running of instrumentation in registered pre/post hooks.
114
124
  * When this returns `false` (don't skip), the pre/post hooks will execute in
@@ -220,11 +230,8 @@ function hookFunction(fn, options) {
220
230
  }
221
231
 
222
232
  // short-circuit optimization for add
223
- const [arg1, arg2] = args;
224
- if (fn.name === '__add' && arg1 && arg2) {
225
- if (!tracker.getData(arg1).tracked && !tracker.getData(arg2).tracked) {
226
- return arg1 + arg2;
227
- }
233
+ if (fn.name === '__add' && !argsTracked(args)) {
234
+ return args[0] + args[1];
228
235
  }
229
236
 
230
237
  const data = {
@@ -321,7 +328,8 @@ function hookableMethods(obj, props, callback) {
321
328
  }
322
329
 
323
330
  // Execute callback for every method in the props array.
324
- for (let i = props.length; i >= 0; i--) {
331
+ let i = props.length;
332
+ while (i--) {
325
333
  // If the property isn't a function...
326
334
  if (
327
335
  !isFunction(obj[props[i]]) ||
@@ -472,7 +480,7 @@ function patch(obj, props, options) {
472
480
  }
473
481
 
474
482
  const hookedMethods = hookableMethods(obj, props).map(function(prop) {
475
- const opts = Object.assign({}, options);
483
+ const opts = typeof options === 'object' ? { ...options } : options;
476
484
 
477
485
  // staticName means do not append methods to final name
478
486
  // only used for Function(aka global.ContrastFunction)
@@ -0,0 +1,27 @@
1
+ /**
2
+ Copyright: 2021 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
+ function some(array, predicate) {
16
+ let index = -1;
17
+ const length = array == null ? 0 : array.length;
18
+
19
+ while (++index < length) {
20
+ if (predicate(array[index], index, array)) {
21
+ return true;
22
+ }
23
+ }
24
+ return false;
25
+ }
26
+
27
+ module.exports = some;
@@ -309,7 +309,7 @@ endif
309
309
 
310
310
  quiet_cmd_regen_makefile = ACTION Regenerating $@
311
311
  cmd_regen_makefile = cd $(srcdir); /opt/hostedtoolcache/node/12.22.7/x64/lib/node_modules/npm/node_modules/node-gyp/gyp/gyp_main.py -fmake --ignore-environment "-Dlibrary=shared_library" "-Dvisibility=default" "-Dnode_root_dir=/home/runner/.cache/node-gyp/12.22.7" "-Dnode_gyp_dir=/opt/hostedtoolcache/node/12.22.7/x64/lib/node_modules/npm/node_modules/node-gyp" "-Dnode_lib_file=/home/runner/.cache/node-gyp/12.22.7/<(target_arch)/node.lib" "-Dmodule_root_dir=/home/runner/work/node-agent/node-agent/target/node_modules/unix-dgram" "-Dnode_engine=v8" "--depth=." "-Goutput_dir=." "--generator-output=build" -I/home/runner/work/node-agent/node-agent/target/node_modules/unix-dgram/build/config.gypi -I/opt/hostedtoolcache/node/12.22.7/x64/lib/node_modules/npm/node_modules/node-gyp/addon.gypi -I/home/runner/.cache/node-gyp/12.22.7/include/node/common.gypi "--toplevel-dir=." binding.gyp
312
- Makefile: $(srcdir)/../../../../../../.cache/node-gyp/12.22.7/include/node/common.gypi $(srcdir)/build/config.gypi $(srcdir)/binding.gyp $(srcdir)/../../../../../../../../opt/hostedtoolcache/node/12.22.7/x64/lib/node_modules/npm/node_modules/node-gyp/addon.gypi
312
+ Makefile: $(srcdir)/../../../../../../.cache/node-gyp/12.22.7/include/node/common.gypi $(srcdir)/../../../../../../../../opt/hostedtoolcache/node/12.22.7/x64/lib/node_modules/npm/node_modules/node-gyp/addon.gypi $(srcdir)/build/config.gypi $(srcdir)/binding.gyp
313
313
  $(call do_cmd,regen_makefile)
314
314
 
315
315
  # "all" is a concatenation of the "all" targets from all the included
@@ -126,7 +126,7 @@
126
126
  "progress": "",
127
127
  "https_proxy": "",
128
128
  "save_prod": "",
129
- "npm_session": "70d49993d405ee64",
129
+ "npm_session": "3f130026df618e76",
130
130
  "audit": "true",
131
131
  "cidr": "",
132
132
  "onload_script": "",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@contrast/agent",
3
- "version": "4.5.1",
3
+ "version": "4.5.2",
4
4
  "description": "Node.js security instrumentation by Contrast Security",
5
5
  "keywords": [
6
6
  "security",
@@ -109,6 +109,7 @@
109
109
  "yaml": "^1.10.0"
110
110
  },
111
111
  "devDependencies": {
112
+ "@aws-sdk/client-dynamodb": "^3.39.0",
112
113
  "@bmacnaughton/string-generator": "^1.0.0",
113
114
  "@contrast/eslint-config": "^2.0.1",
114
115
  "@contrast/fake-module": "file:test/mock/contrast-fake",