dd-trace 4.0.0-pre-60b4fde → 4.0.0-pre-307d719

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.
Files changed (51) hide show
  1. package/LICENSE-3rdparty.csv +2 -0
  2. package/README.md +49 -0
  3. package/esbuild.js +3 -0
  4. package/index.d.ts +8 -8
  5. package/package.json +15 -10
  6. package/packages/datadog-core/src/storage/async_resource.js +1 -1
  7. package/packages/datadog-esbuild/index.js +111 -0
  8. package/packages/datadog-instrumentations/src/google-cloud-pubsub.js +1 -1
  9. package/packages/datadog-instrumentations/src/helpers/hook.js +13 -3
  10. package/packages/datadog-instrumentations/src/helpers/instrument.js +7 -1
  11. package/packages/datadog-instrumentations/src/helpers/register.js +3 -3
  12. package/packages/datadog-instrumentations/src/mongoose.js +1 -1
  13. package/packages/datadog-instrumentations/src/pg.js +16 -11
  14. package/packages/datadog-plugin-next/src/index.js +6 -0
  15. package/packages/dd-trace/src/appsec/{templates/blocked.html → blocked_templates.js} +19 -1
  16. package/packages/dd-trace/src/appsec/blocking.js +9 -24
  17. package/packages/dd-trace/src/appsec/gateway/channels.js +1 -1
  18. package/packages/dd-trace/src/appsec/iast/analyzers/path-traversal-analyzer.js +12 -0
  19. package/packages/dd-trace/src/appsec/iast/analyzers/sql-injection-analyzer.js +1 -1
  20. package/packages/dd-trace/src/appsec/iast/analyzers/vulnerability-analyzer.js +9 -3
  21. package/packages/dd-trace/src/appsec/iast/index.js +3 -2
  22. package/packages/dd-trace/src/appsec/iast/taint-tracking/index.js +9 -2
  23. package/packages/dd-trace/src/appsec/iast/taint-tracking/operations.js +9 -0
  24. package/packages/dd-trace/src/appsec/iast/telemetry/logs.js +1 -1
  25. package/packages/dd-trace/src/appsec/index.js +4 -18
  26. package/packages/dd-trace/src/appsec/recommended.json +43 -14
  27. package/packages/dd-trace/src/appsec/remote_config/index.js +1 -1
  28. package/packages/dd-trace/src/appsec/sdk/index.js +2 -2
  29. package/packages/dd-trace/src/config.js +21 -18
  30. package/packages/dd-trace/src/datastreams/encoding.js +80 -0
  31. package/packages/dd-trace/src/dcitm.js +53 -0
  32. package/packages/dd-trace/src/encode/tags-processors.js +40 -68
  33. package/packages/dd-trace/src/iitm.js +1 -1
  34. package/packages/dd-trace/src/lambda/handler.js +30 -6
  35. package/packages/dd-trace/src/log/channels.js +11 -12
  36. package/packages/dd-trace/src/opentracing/propagation/log.js +23 -7
  37. package/packages/dd-trace/src/opentracing/propagation/text_map.js +28 -2
  38. package/packages/dd-trace/src/opentracing/span.js +14 -3
  39. package/packages/dd-trace/src/opentracing/span_context.js +3 -1
  40. package/packages/dd-trace/src/opentracing/tracer.js +3 -1
  41. package/packages/dd-trace/src/plugin_manager.js +1 -1
  42. package/packages/dd-trace/src/plugins/plugin.js +1 -1
  43. package/packages/dd-trace/src/profiling/config.js +27 -26
  44. package/packages/dd-trace/src/profiling/profilers/cpu.js +1 -1
  45. package/packages/dd-trace/src/ritm.js +1 -1
  46. package/packages/dd-trace/src/telemetry/dependencies.js +1 -1
  47. package/packages/dd-trace/src/telemetry/index.js +1 -1
  48. package/packages/diagnostics_channel/index.js +3 -0
  49. package/packages/diagnostics_channel/src/index.js +57 -0
  50. package/scripts/install_plugin_modules.js +3 -1
  51. package/packages/dd-trace/src/appsec/templates/blocked.json +0 -8
@@ -36,10 +36,12 @@ dev,chalk,MIT,Copyright Sindre Sorhus
36
36
  dev,checksum,MIT,Copyright Daniel D. Shaw
37
37
  dev,cli-table3,MIT,Copyright 2014 James Talmage
38
38
  dev,dotenv,BSD-2-Clause,Copyright 2015 Scott Motte
39
+ dev,esbuild,MIT,Copyright (c) 2020 Evan Wallace
39
40
  dev,eslint,MIT,Copyright JS Foundation and other contributors https://js.foundation
40
41
  dev,eslint-config-standard,MIT,Copyright Feross Aboukhadijeh
41
42
  dev,eslint-plugin-import,MIT,Copyright 2015 Ben Mosher
42
43
  dev,eslint-plugin-mocha,MIT,Copyright 2014 Mathias Schreck
44
+ dev,eslint-plugin-n,MIT,Copyright 2015 Toru Nagashima
43
45
  dev,eslint-plugin-node,MIT,Copyright 2015 Toru Nagashima
44
46
  dev,eslint-plugin-promise,ISC,jden and other contributors
45
47
  dev,eslint-plugin-standard,MIT,Copyright 2015 Jamund Ferguson
package/README.md CHANGED
@@ -151,6 +151,19 @@ $ yarn lint
151
151
  ```
152
152
 
153
153
 
154
+ ### Experimental ESM Support
155
+
156
+ ESM support is currently in the experimental stages, while CJS has been supported
157
+ since inception. This means that code loaded using `require()` should work fine
158
+ but code loaded using `import` might not always work.
159
+
160
+ Use the following command to enable experimental ESM support with your application:
161
+
162
+ ```sh
163
+ node --loader dd-trace/loader-hook.mjs entrypoint.js
164
+ ```
165
+
166
+
154
167
  ### Benchmarks
155
168
 
156
169
  Our microbenchmarks live in `benchmark/sirun`. Each directory in there
@@ -175,6 +188,42 @@ That said, even if your application runs on Lambda, any core instrumentation iss
175
188
  Regardless of where you open the issue, someone at Datadog will try to help.
176
189
 
177
190
 
191
+ ## Bundling
192
+
193
+ Generally, `dd-trace` works by intercepting `require()` calls that a Node.js application makes when loading modules. This includes modules that are built-in to Node.js, like the `fs` module for accessing the filesystem, as well as modules installed from the npm registry, like the `pg` database module.
194
+
195
+ Also generally, bundlers work by crawling all of the `require()` calls that an application makes to files on disk, replacing the `require()` calls with custom code, and then concatenating all of the resulting JavaScript into one "bundled" file. When a built-in module is loaded, like `require('fs')`, that call can then remain the same in the resulting bundle.
196
+
197
+ Fundamentally APM tools like `dd-trace` stop working at this point. Perhaps they continue to intercept the calls for built-in modules but don't intercept calls to third party libraries. This means that by default when you bundle a `dd-trace` app with a bundler it is likely to capture information about disk access (via `fs`) and outbound HTTP requests (via `http`), but will otherwise omit calls to third party libraries (like extracting incoming request route information for the `express` framework or showing which query is run for the `mysql` database client).
198
+
199
+ To get around this, one can treat all third party modules, or at least third party modules that the APM needs to instrument, as being "external" to the bundler. With this setting the instrumented modules remain on disk and continue to be loaded via `require()` while the non-instrumented modules are bundled. Sadly this results in a build with many extraneous files and starts to defeat the purpose of bundling.
200
+
201
+ For these reasons it's necessary to have custom-built bundler plugins. Such plugins are able to instruct the bundler on how to behave, injecting intermediary code and otherwise intercepting the "translated" `require()` calls. The result is that many more packages are then included in the bundled JavaScript file. Some applications can have 100% of modules bundled, however native modules still need to remain external to the bundle.
202
+
203
+ ### Esbuild Support
204
+
205
+ This library provides experimental esbuild support in the form of an esbuild plugin, and currently requires at least Node.js v16.17 or v18.7. To use the plugin, make sure you have `dd-trace@3+` installed, and then require the `dd-trace/esbuild` module when building your bundle.
206
+
207
+ Here's an example of how one might use `dd-trace` with esbuild:
208
+
209
+ ```javascript
210
+ const ddPlugin = require('dd-trace/esbuild')
211
+ const esbuild = require('esbuild')
212
+
213
+ esbuild.build({
214
+ entryPoints: ['app.js'],
215
+ bundle: true,
216
+ outfile: 'out.js',
217
+ plugins: [ddPlugin],
218
+ platform: 'node', // allows built-in modules to be required
219
+ target: ['node16']
220
+ }).catch((err) => {
221
+ console.error(err)
222
+ process.exit(1)
223
+ })
224
+ ```
225
+
226
+
178
227
  ## Security Vulnerabilities
179
228
 
180
229
  If you have found a security issue, please contact the security team directly at [security@datadoghq.com](mailto:security@datadoghq.com).
package/esbuild.js ADDED
@@ -0,0 +1,3 @@
1
+ 'use strict'
2
+
3
+ module.exports = require('./packages/datadog-esbuild/index.js')
package/index.d.ts CHANGED
@@ -871,7 +871,7 @@ declare namespace plugins {
871
871
  /**
872
872
  * Hook to execute just before the request span finishes.
873
873
  */
874
- request?: (span?: opentracing.Span, req?: IncomingMessage, res?: ServerResponse) => any;
874
+ request?: (span?: Span, req?: IncomingMessage, res?: ServerResponse) => any;
875
875
  };
876
876
 
877
877
  /**
@@ -907,7 +907,7 @@ declare namespace plugins {
907
907
  /**
908
908
  * Hook to execute just before the request span finishes.
909
909
  */
910
- request?: (span?: opentracing.Span, req?: ClientRequest, res?: IncomingMessage) => any;
910
+ request?: (span?: Span, req?: ClientRequest, res?: IncomingMessage) => any;
911
911
  };
912
912
 
913
913
  /**
@@ -997,7 +997,7 @@ declare namespace plugins {
997
997
  /**
998
998
  * Hook to execute just before the aws span finishes.
999
999
  */
1000
- request?: (span?: opentracing.Span, response?: anyObject) => any;
1000
+ request?: (span?: Span, response?: anyObject) => any;
1001
1001
  };
1002
1002
 
1003
1003
  /**
@@ -1066,7 +1066,7 @@ declare namespace plugins {
1066
1066
  /**
1067
1067
  * Hook to execute just before the query span finishes.
1068
1068
  */
1069
- query?: (span?: opentracing.Span, params?: TransportRequestParams) => any;
1069
+ query?: (span?: Span, params?: TransportRequestParams) => any;
1070
1070
  };
1071
1071
  }
1072
1072
 
@@ -1235,7 +1235,7 @@ declare namespace plugins {
1235
1235
  * Hook to execute just before the request span finishes.
1236
1236
  */
1237
1237
  request?: (
1238
- span?: opentracing.Span,
1238
+ span?: Span,
1239
1239
  req?: IncomingMessage | ClientRequest,
1240
1240
  res?: ServerResponse | IncomingMessage
1241
1241
  ) => any;
@@ -1428,7 +1428,7 @@ declare namespace plugins {
1428
1428
  /**
1429
1429
  * Hook to execute just before the request span finishes.
1430
1430
  */
1431
- request?: (span?: opentracing.Span, req?: IncomingMessage, res?: ServerResponse) => any;
1431
+ request?: (span?: Span, req?: IncomingMessage, res?: ServerResponse) => any;
1432
1432
  };
1433
1433
  }
1434
1434
 
@@ -1547,12 +1547,12 @@ declare namespace plugins {
1547
1547
  /**
1548
1548
  * Hook to execute just when the span is created.
1549
1549
  */
1550
- receive?: (span?: opentracing.Span, request?: any) => any;
1550
+ receive?: (span?: Span, request?: any) => any;
1551
1551
 
1552
1552
  /**
1553
1553
  * Hook to execute just when the span is finished.
1554
1554
  */
1555
- reply?: (span?: opentracing.Span, request?: any, response?: any) => any;
1555
+ reply?: (span?: Span, request?: any, response?: any) => any;
1556
1556
  };
1557
1557
  }
1558
1558
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dd-trace",
3
- "version": "4.0.0-pre-60b4fde",
3
+ "version": "4.0.0-pre-307d719",
4
4
  "description": "Datadog APM tracing client for JavaScript",
5
5
  "main": "index.js",
6
6
  "typings": "index.d.ts",
@@ -19,20 +19,23 @@
19
19
  "test:appsec:ci": "nyc --no-clean --include \"packages/dd-trace/src/appsec/**/*.js\" --exclude \"packages/dd-trace/test/appsec/iast/**/*.plugin.spec.js\" -- npm run test:appsec",
20
20
  "test:appsec:plugins": "mocha --colors --exit -r \"packages/dd-trace/test/setup/mocha.js\" \"packages/dd-trace/test/appsec/iast/**/*.@($(echo $PLUGINS)).plugin.spec.js\"",
21
21
  "test:appsec:plugins:ci": "yarn services && nyc --no-clean --include \"packages/dd-trace/test/appsec/iast/**/*.@($(echo $PLUGINS)).plugin.spec.js\" -- npm run test:appsec:plugins",
22
- "test:trace:core": "tap packages/dd-trace/test/*.spec.js packages/dd-trace/test/{ci-visibility,encode,exporters,opentracing,plugins,telemetry}/**/*.spec.js",
23
- "test:trace:core:ci": "npm run test:trace:core -- --coverage --nyc-arg=--include=packages/dd-trace/src/**/*.js",
22
+ "test:trace:core": "tap packages/dd-trace/test/*.spec.js \"packages/dd-trace/test/{ci-visibility,encode,exporters,opentracing,plugins,telemetry}/**/*.spec.js\"",
23
+ "test:trace:core:ci": "npm run test:trace:core -- --coverage --nyc-arg=--include=\"packages/dd-trace/src/**/*.js\"",
24
24
  "test:instrumentations": "mocha --colors -r 'packages/dd-trace/test/setup/mocha.js' 'packages/datadog-instrumentations/test/**/*.spec.js'",
25
25
  "test:instrumentations:ci": "nyc --no-clean --include 'packages/datadog-instrumentations/src/**/*.js' -- npm run test:instrumentations",
26
- "test:core": "tap packages/datadog-core/test/**/*.spec.js",
27
- "test:core:ci": "npm run test:core -- --coverage --nyc-arg=--include=packages/datadog-core/src/**/*.js",
26
+ "test:core": "tap \"packages/datadog-core/test/**/*.spec.js\"",
27
+ "test:core:ci": "npm run test:core -- --coverage --nyc-arg=--include=\"packages/datadog-core/src/**/*.js\"",
28
28
  "test:lambda": "mocha --colors --exit -r \"packages/dd-trace/test/setup/mocha.js\" \"packages/dd-trace/test/lambda/**/*.spec.js\"",
29
29
  "test:lambda:ci": "nyc --no-clean --include \"packages/dd-trace/src/lambda/**/*.js\" -- npm run test:lambda",
30
30
  "test:plugins": "mocha --colors --exit -r \"packages/dd-trace/test/setup/mocha.js\" \"packages/datadog-instrumentations/test/@($(echo $PLUGINS)).spec.js\" \"packages/datadog-plugin-@($(echo $PLUGINS))/test/**/*.spec.js\"",
31
31
  "test:plugins:ci": "yarn services && nyc --no-clean --include \"packages/datadog-instrumentations/src/@($(echo $PLUGINS)).js\" --include \"packages/datadog-instrumentations/src/@($(echo $PLUGINS))/**/*.js\" --include \"packages/datadog-plugin-@($(echo $PLUGINS))/src/**/*.js\" -- npm run test:plugins",
32
32
  "test:plugins:upstream": "node ./packages/dd-trace/test/plugins/suite.js",
33
- "test:profiler": "tap packages/dd-trace/test/profiling/**/*.spec.js",
34
- "test:profiler:ci": "npm run test:profiler -- --coverage --nyc-arg=--include=packages/dd-trace/src/profiling/**/*.js",
35
- "test:integration": "mocha --colors --timeout 30000 \"integration-tests/**/*.spec.js\"",
33
+ "test:profiler": "tap \"packages/dd-trace/test/profiling/**/*.spec.js\"",
34
+ "test:profiler:ci": "npm run test:profiler -- --coverage --nyc-arg=--include=\"packages/dd-trace/src/profiling/**/*.js\"",
35
+ "test:integration": "mocha --colors --timeout 30000 \"integration-tests/*.spec.js\"",
36
+ "test:integration:cucumber": "mocha --colors --timeout 30000 \"integration-tests/cucumber/*.spec.js\"",
37
+ "test:integration:cypress": "mocha --colors --timeout 30000 \"integration-tests/cypress/*.spec.js\"",
38
+ "test:integration:playwright": "mocha --colors --timeout 30000 \"integration-tests/playwright/*.spec.js\"",
36
39
  "test:shimmer": "mocha --colors 'packages/datadog-shimmer/test/**/*.spec.js'",
37
40
  "test:shimmer:ci": "nyc --no-clean --include 'packages/datadog-shimmer/src/**/*.js' -- npm run test:shimmer",
38
41
  "leak:core": "node ./scripts/install_plugin_modules && (cd packages/memwatch && yarn) && NODE_PATH=./packages/memwatch/node_modules node --no-warnings ./node_modules/.bin/tape 'packages/dd-trace/test/leak/**/*.js'",
@@ -64,7 +67,7 @@
64
67
  "dependencies": {
65
68
  "@datadog/native-appsec": "2.0.0",
66
69
  "@datadog/native-iast-rewriter": "2.0.1",
67
- "@datadog/native-iast-taint-tracking": "1.1.1",
70
+ "@datadog/native-iast-taint-tracking": "1.3.1",
68
71
  "@datadog/native-metrics": "^1.5.0",
69
72
  "@datadog/pprof": "^2.1.0",
70
73
  "@datadog/sketches-js": "^2.1.0",
@@ -88,7 +91,7 @@
88
91
  "path-to-regexp": "^0.1.2",
89
92
  "protobufjs": "^7.1.2",
90
93
  "retry": "^0.10.1",
91
- "semver": "^5.5.0"
94
+ "semver": "^7.3.8"
92
95
  },
93
96
  "devDependencies": {
94
97
  "@types/node": ">=14",
@@ -101,10 +104,12 @@
101
104
  "checksum": "^0.1.1",
102
105
  "cli-table3": "^0.5.1",
103
106
  "dotenv": "8.2.0",
107
+ "esbuild": "0.16.12",
104
108
  "eslint": "^8.23.0",
105
109
  "eslint-config-standard": "^11.0.0-beta.0",
106
110
  "eslint-plugin-import": "^2.8.0",
107
111
  "eslint-plugin-mocha": "^10.1.0",
112
+ "eslint-plugin-n": "^15.7.0",
108
113
  "eslint-plugin-node": "^5.2.1",
109
114
  "eslint-plugin-promise": "^3.6.0",
110
115
  "eslint-plugin-standard": "^3.0.1",
@@ -1,7 +1,7 @@
1
1
  'use strict'
2
2
 
3
3
  const { createHook, executionAsyncResource } = require('async_hooks')
4
- const { channel } = require('diagnostics_channel')
4
+ const { channel } = require('../../../diagnostics_channel')
5
5
 
6
6
  const beforeCh = channel('dd-trace:storage:before')
7
7
  const afterCh = channel('dd-trace:storage:after')
@@ -0,0 +1,111 @@
1
+ 'use strict'
2
+
3
+ /* eslint-disable no-console */
4
+
5
+ const NAMESPACE = 'datadog'
6
+
7
+ const instrumented = Object.keys(require('../datadog-instrumentations/src/helpers/hooks.js'))
8
+ const rawBuiltins = require('module').builtinModules
9
+
10
+ warnIfUnsupported()
11
+
12
+ const builtins = new Set()
13
+
14
+ for (const builtin of rawBuiltins) {
15
+ builtins.add(builtin)
16
+ builtins.add(`node:${builtin}`)
17
+ }
18
+
19
+ const packagesOfInterest = new Set()
20
+
21
+ const DEBUG = !!process.env.DD_TRACE_DEBUG
22
+
23
+ // We don't want to handle any built-in packages via DCITM
24
+ // Those packages will still be handled via RITM
25
+ // Attempting to instrument them would fail as they have no package.json file
26
+ for (const pkg of instrumented) {
27
+ if (builtins.has(pkg)) continue
28
+ if (pkg.startsWith('node:')) continue
29
+ packagesOfInterest.add(pkg)
30
+ }
31
+
32
+ const DC_CHANNEL = 'dd-trace:bundledModuleLoadStart'
33
+
34
+ module.exports.name = 'datadog-esbuild'
35
+
36
+ module.exports.setup = function (build) {
37
+ build.onResolve({ filter: /.*/ }, args => {
38
+ const packageName = args.path
39
+
40
+ if (args.namespace === 'file' && packagesOfInterest.has(packageName)) {
41
+ // The file namespace is used when requiring files from disk in userland
42
+ const pathToPackageJson = require.resolve(`${packageName}/package.json`, { paths: [ args.resolveDir ] })
43
+ const pkg = require(pathToPackageJson)
44
+
45
+ if (DEBUG) {
46
+ console.log(`resolve ${packageName}@${pkg.version}`)
47
+ }
48
+
49
+ // https://esbuild.github.io/plugins/#on-resolve-arguments
50
+ return {
51
+ path: packageName,
52
+ namespace: NAMESPACE,
53
+ pluginData: {
54
+ version: pkg.version
55
+ }
56
+ }
57
+ } else if (args.namespace === 'datadog') {
58
+ // The datadog namespace is used when requiring files that are injected during the onLoad stage
59
+ // see note in onLoad
60
+
61
+ if (builtins.has(packageName)) return
62
+
63
+ return {
64
+ path: require.resolve(packageName, { paths: [ args.resolveDir ] }),
65
+ namespace: 'file'
66
+ }
67
+ }
68
+ })
69
+
70
+ build.onLoad({ filter: /.*/, namespace: NAMESPACE }, args => {
71
+ if (DEBUG) {
72
+ console.log(`load ${args.path}@${args.pluginData.version}`)
73
+ }
74
+
75
+ // JSON.stringify adds double quotes. For perf gain could simply add in quotes when we know it's safe.
76
+ const contents = `
77
+ const dc = require('diagnostics_channel');
78
+ const ch = dc.channel(${JSON.stringify(DC_CHANNEL + ':' + args.path)});
79
+ const mod = require(${JSON.stringify(args.path)});
80
+ const payload = {
81
+ module: mod,
82
+ path: ${JSON.stringify(args.path)},
83
+ version: ${JSON.stringify(args.pluginData.version)}
84
+ };
85
+ ch.publish(payload);
86
+ module.exports = payload.module;
87
+ `
88
+ // https://esbuild.github.io/plugins/#on-load-results
89
+ return {
90
+ contents,
91
+ loader: 'js'
92
+ }
93
+ })
94
+ }
95
+
96
+ // Currently esbuild support requires Node.js >=v16.17 or >=v18.7
97
+ // Better yet it would support Node >=v14.17 or >=v16
98
+ // Of course, the most ideal would be to support all versions of Node that dd-trace supports.
99
+ // Version constraints based on Node's diagnostics_channel support
100
+ function warnIfUnsupported () {
101
+ const [major, minor] = process.versions.node.split('.').map(Number)
102
+ if (
103
+ major < 16 ||
104
+ (major === 16 && minor < 17) ||
105
+ (major === 18 && minor < 7)) {
106
+ console.error('WARNING: Esbuild support isn\'t available for older versions of Node.js.')
107
+ console.error(`Expected: Node.js >=v16.17 or >=v18.7. Actual: Node.js = ${process.version}.`)
108
+ console.error('This application may build properly with this version of Node.js, but unless a')
109
+ console.error('more recent version is used at runtime, third party packages won\'t be instrumented.')
110
+ }
111
+ }
@@ -63,7 +63,7 @@ function wrapMethod (method) {
63
63
  const api = method.name
64
64
 
65
65
  return function (request) {
66
- if (!requestStartCh.hasSubscribers) return request.apply(this, arguments)
66
+ if (!requestStartCh.hasSubscribers) return method.apply(this, arguments)
67
67
 
68
68
  const innerAsyncResource = new AsyncResource('bound-anonymous-fn')
69
69
 
@@ -3,13 +3,21 @@
3
3
  const path = require('path')
4
4
  const iitm = require('../../../dd-trace/src/iitm')
5
5
  const ritm = require('../../../dd-trace/src/ritm')
6
-
6
+ const dcitm = require('../../../dd-trace/src/dcitm')
7
+
8
+ /**
9
+ * This is called for every module that dd-trace supports instrumentation for.
10
+ * In practice, `modules` is always an array with a single entry.
11
+ *
12
+ * @param {string[]} modules list of modules to hook into
13
+ * @param {Function} onrequire callback to be executed upon encountering module
14
+ */
7
15
  function Hook (modules, onrequire) {
8
16
  if (!(this instanceof Hook)) return new Hook(modules, onrequire)
9
17
 
10
18
  this._patched = Object.create(null)
11
19
 
12
- const safeHook = (moduleExports, moduleName, moduleBaseDir) => {
20
+ const safeHook = (moduleExports, moduleName, moduleBaseDir, moduleVersion) => {
13
21
  const parts = [moduleBaseDir, moduleName].filter(v => v)
14
22
  const filename = path.join(...parts)
15
23
 
@@ -17,7 +25,7 @@ function Hook (modules, onrequire) {
17
25
 
18
26
  this._patched[filename] = true
19
27
 
20
- return onrequire(moduleExports, moduleName, moduleBaseDir)
28
+ return onrequire(moduleExports, moduleName, moduleBaseDir, moduleVersion)
21
29
  }
22
30
 
23
31
  this._ritmHook = ritm(modules, {}, safeHook)
@@ -33,11 +41,13 @@ function Hook (modules, onrequire) {
33
41
  return safeHook(moduleExports, moduleName, moduleBaseDir)
34
42
  }
35
43
  })
44
+ this._dcitmHook = dcitm(modules, {}, safeHook)
36
45
  }
37
46
 
38
47
  Hook.prototype.unhook = function () {
39
48
  this._ritmHook.unhook()
40
49
  this._iitmHook.unhook()
50
+ this._dcitmHook.unhook()
41
51
  this._patched = Object.create(null)
42
52
  }
43
53
 
@@ -1,6 +1,6 @@
1
1
  'use strict'
2
2
 
3
- const dc = require('diagnostics_channel')
3
+ const dc = require('../../../diagnostics_channel')
4
4
  const semver = require('semver')
5
5
  const instrumentations = require('./instrumentations')
6
6
  const { AsyncResource } = require('async_hooks')
@@ -14,6 +14,12 @@ exports.channel = function (name) {
14
14
  return ch
15
15
  }
16
16
 
17
+ /**
18
+ * @param {string} args.name module name
19
+ * @param {string[]} args.versions array of semver range strings
20
+ * @param {string} args.file path to file within package to instrument?
21
+ * @param Function hook
22
+ */
17
23
  exports.addHook = function addHook ({ name, versions, file }, hook) {
18
24
  if (!instrumentations[name]) {
19
25
  instrumentations[name] = []
@@ -1,6 +1,6 @@
1
1
  'use strict'
2
2
 
3
- const { channel } = require('diagnostics_channel')
3
+ const { channel } = require('../../../diagnostics_channel')
4
4
  const path = require('path')
5
5
  const semver = require('semver')
6
6
  const Hook = require('./hook')
@@ -17,7 +17,7 @@ const loadChannel = channel('dd-trace:instrumentation:load')
17
17
  // TODO: make this more efficient
18
18
 
19
19
  for (const packageName of names) {
20
- Hook([packageName], (moduleExports, moduleName, moduleBaseDir) => {
20
+ Hook([packageName], (moduleExports, moduleName, moduleBaseDir, moduleVersion) => {
21
21
  moduleName = moduleName.replace(pathSepExpr, '/')
22
22
 
23
23
  hooks[packageName]()
@@ -26,7 +26,7 @@ for (const packageName of names) {
26
26
  const fullFilename = filename(name, file)
27
27
 
28
28
  if (moduleName === fullFilename) {
29
- const version = getVersion(moduleBaseDir)
29
+ const version = moduleVersion || getVersion(moduleBaseDir)
30
30
 
31
31
  if (matchVersion(version, versions)) {
32
32
  try {
@@ -19,7 +19,7 @@ function wrapAddQueue (addQueue) {
19
19
 
20
20
  addHook({
21
21
  name: 'mongoose',
22
- versions: ['>=4.6.4 <7'] // TODO: Mongoose v7 compat
22
+ versions: ['>=4.6.4 <5', '5', '6', '>=7']
23
23
  }, mongoose => {
24
24
  if (mongoose.Promise !== global.Promise) {
25
25
  shimmer.wrap(mongoose.Promise.prototype, 'then', wrapThen)
@@ -27,27 +27,22 @@ function wrapQuery (query) {
27
27
  return query.apply(this, arguments)
28
28
  }
29
29
 
30
- const retval = query.apply(this, arguments)
31
-
32
- const queryQueue = this.queryQueue || this._queryQueue
33
- const activeQuery = this.activeQuery || this._activeQuery
34
- const pgQuery = queryQueue[queryQueue.length - 1] || activeQuery
35
-
36
- if (!pgQuery) {
37
- return retval
38
- }
39
-
40
30
  const callbackResource = new AsyncResource('bound-anonymous-fn')
41
31
  const asyncResource = new AsyncResource('bound-anonymous-fn')
42
32
  const processId = this.processID
33
+ let pgQuery = {
34
+ text: arguments[0]
35
+ }
36
+
43
37
  return asyncResource.runInAsyncScope(() => {
44
38
  startCh.publish({
45
39
  params: this.connectionParameters,
46
- originalQuery: pgQuery.text,
47
40
  query: pgQuery,
48
41
  processId
49
42
  })
50
43
 
44
+ arguments[0] = pgQuery.text
45
+
51
46
  const finish = asyncResource.bind(function (error) {
52
47
  if (error) {
53
48
  errorCh.publish(error)
@@ -55,6 +50,16 @@ function wrapQuery (query) {
55
50
  finishCh.publish()
56
51
  })
57
52
 
53
+ const retval = query.apply(this, arguments)
54
+ const queryQueue = this.queryQueue || this._queryQueue
55
+ const activeQuery = this.activeQuery || this._activeQuery
56
+
57
+ pgQuery = queryQueue[queryQueue.length - 1] || activeQuery
58
+
59
+ if (!pgQuery) {
60
+ return retval
61
+ }
62
+
58
63
  if (pgQuery.callback) {
59
64
  const originalCallback = callbackResource.bind(pgQuery.callback)
60
65
  pgQuery.callback = function (err, res) {
@@ -68,6 +68,12 @@ class NextPlugin extends Plugin {
68
68
  const span = store.span
69
69
  const req = this._requests.get(span)
70
70
 
71
+ // Only use error page names if there's not already a name
72
+ const current = span.context()._tags['next.page']
73
+ if (current && (page === '/404' || page === '/500' || page === '/_error')) {
74
+ return
75
+ }
76
+
71
77
  span.addTags({
72
78
  [COMPONENT]: this.constructor.id,
73
79
  'resource.name': `${req.method} ${page}`.trim(),
@@ -1,4 +1,7 @@
1
- <!-- Sorry, you’ve been blocked -->
1
+ /* eslint-disable max-len */
2
+ 'use strict'
3
+
4
+ const html = `<!-- Sorry, you've been blocked -->
2
5
  <!DOCTYPE html>
3
6
  <html lang="en">
4
7
 
@@ -97,3 +100,18 @@
97
100
  </body>
98
101
 
99
102
  </html>
103
+ `
104
+
105
+ const json = `{
106
+ "errors": [
107
+ {
108
+ "title": "You've been blocked",
109
+ "detail": "Sorry, you cannot access this page. Please contact the customer service team. Security provided by Datadog."
110
+ }
111
+ ]
112
+ }`
113
+
114
+ module.exports = {
115
+ html,
116
+ json
117
+ }
@@ -1,12 +1,10 @@
1
1
  'use strict'
2
2
 
3
3
  const log = require('../log')
4
- const fs = require('fs')
4
+ const blockedTemplates = require('./blocked_templates')
5
5
 
6
- // TODO: move template loading to a proper spot.
7
- let templateLoaded = false
8
- let templateHtml = ''
9
- let templateJson = ''
6
+ let templateHtml = blockedTemplates.html
7
+ let templateJson = blockedTemplates.json
10
8
 
11
9
  function block (req, res, rootSpan, abortController) {
12
10
  if (res.headersSent) {
@@ -42,29 +40,16 @@ function block (req, res, rootSpan, abortController) {
42
40
  }
43
41
  }
44
42
 
45
- function loadTemplates (config) {
46
- if (!templateLoaded) {
47
- templateHtml = fs.readFileSync(config.appsec.blockedTemplateHtml)
48
- templateJson = fs.readFileSync(config.appsec.blockedTemplateJson)
49
- templateLoaded = true
43
+ function setTemplates (config) {
44
+ if (config.appsec.blockedTemplateHtml) {
45
+ templateHtml = config.appsec.blockedTemplateHtml
50
46
  }
51
- }
52
-
53
- async function loadTemplatesAsync (config) {
54
- if (!templateLoaded) {
55
- templateHtml = await fs.promises.readFile(config.appsec.blockedTemplateHtml)
56
- templateJson = await fs.promises.readFile(config.appsec.blockedTemplateJson)
57
- templateLoaded = true
47
+ if (config.appsec.blockedTemplateJson) {
48
+ templateJson = config.appsec.blockedTemplateJson
58
49
  }
59
50
  }
60
51
 
61
- function resetTemplates () {
62
- templateLoaded = false
63
- }
64
-
65
52
  module.exports = {
66
53
  block,
67
- loadTemplates,
68
- loadTemplatesAsync,
69
- resetTemplates
54
+ setTemplates
70
55
  }
@@ -1,6 +1,6 @@
1
1
  'use strict'
2
2
 
3
- const dc = require('diagnostics_channel')
3
+ const dc = require('../../../../diagnostics_channel')
4
4
 
5
5
  // TODO: use TBD naming convention
6
6
  // or directly use http plugin's channels
@@ -1,4 +1,6 @@
1
1
  'use strict'
2
+
3
+ const path = require('path')
2
4
  const { getIastContext } = require('../iast-context')
3
5
  const { storage } = require('../../../../../datadog-core')
4
6
  const InjectionAnalyzer = require('./injection-analyzer')
@@ -37,6 +39,16 @@ class PathTraversalAnalyzer extends InjectionAnalyzer {
37
39
  }
38
40
  this.analyze(pathArguments)
39
41
  })
42
+
43
+ this.exclusionList = [ path.join('node_modules', 'send') + path.sep ]
44
+ }
45
+
46
+ _isExcluded (location) {
47
+ let ret = false
48
+ if (location && location.path) {
49
+ ret = this.exclusionList.some(elem => location.path.includes(elem))
50
+ }
51
+ return ret
40
52
  }
41
53
 
42
54
  analyze (value) {
@@ -6,7 +6,7 @@ class SqlInjectionAnalyzer extends InjectionAnalyzer {
6
6
  super('SQL_INJECTION')
7
7
  this.addSub('apm:mysql:query:start', ({ sql }) => this.analyze(sql))
8
8
  this.addSub('apm:mysql2:query:start', ({ sql }) => this.analyze(sql))
9
- this.addSub('apm:pg:query:start', ({ originalQuery }) => this.analyze(originalQuery))
9
+ this.addSub('apm:pg:query:start', ({ query }) => this.analyze(query.text))
10
10
  }
11
11
  }
12
12