-
Notifications
You must be signed in to change notification settings - Fork 406
Expand file tree
/
Copy pathrewriter.js
More file actions
266 lines (223 loc) · 7.95 KB
/
Copy pathrewriter.js
File metadata and controls
266 lines (223 loc) · 7.95 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
'use strict'
/* eslint n/no-unsupported-features/node-builtins: ['error', { ignores: ['module.register'] }] */
const Module = require('module')
const { pathToFileURL } = require('url')
const { MessageChannel } = require('worker_threads')
const shimmer = require('../../../../../datadog-shimmer')
const { isPrivateModule, isDdTrace } = require('./filter')
const { csiMethods } = require('./csi-methods')
const { getName } = require('../telemetry/verbosity')
const telemetry = require('../telemetry')
const { incrementTelemetryIfNeeded } = require('./rewriter-telemetry')
const dc = require('dc-polyfill')
const log = require('../../../log')
const { isMainThread } = require('worker_threads')
const { LOG_MESSAGE, REWRITTEN_MESSAGE } = require('./constants')
const orchestrionConfig = require('../../../../../datadog-instrumentations/src/orchestrion-config')
const { getEnvironmentVariable } = require('../../../config-helper')
let config
const hardcodedSecretCh = dc.channel('datadog:secrets:result')
let rewriter
let unwrapCompile = () => {}
let getPrepareStackTrace
let cacheRewrittenSourceMap
let kSymbolPrepareStackTrace
function noop () {}
function isFlagPresent (flag) {
return getEnvironmentVariable('NODE_OPTIONS')?.includes(flag) ||
process.execArgv?.some(arg => arg.includes(flag))
}
let getRewriterOriginalPathAndLineFromSourceMap = function (path, line, column) {
return { path, line, column }
}
function setGetOriginalPathAndLineFromSourceMapFunction (chainSourceMap, { getOriginalPathAndLineFromSourceMap }) {
if (!getOriginalPathAndLineFromSourceMap) return
getRewriterOriginalPathAndLineFromSourceMap = chainSourceMap
? (path, line, column) => {
// if --enable-source-maps is present stacktraces of the rewritten files contain the original path, file and
// column because the sourcemap chaining is done during the rewriting process so we can skip it
return !globalThis.__DD_ESBUILD_IAST_WITH_SM && isPrivateModule(path) && !isDdTrace(path)
? { path, line, column }
: getOriginalPathAndLineFromSourceMap(path, line, column)
}
: getOriginalPathAndLineFromSourceMap
}
function getRewriter (telemetryVerbosity) {
if (!rewriter) {
try {
const iastRewriter = require('@datadog/wasm-js-rewriter')
const Rewriter = iastRewriter.Rewriter
getPrepareStackTrace = iastRewriter.getPrepareStackTrace
kSymbolPrepareStackTrace = iastRewriter.kSymbolPrepareStackTrace
cacheRewrittenSourceMap = iastRewriter.cacheRewrittenSourceMap
const chainSourceMap = isFlagPresent('--enable-source-maps')
setGetOriginalPathAndLineFromSourceMapFunction(chainSourceMap, iastRewriter)
rewriter = new Rewriter({
csiMethods,
telemetryVerbosity: getName(telemetryVerbosity),
chainSourceMap,
orchestrion: orchestrionConfig
})
} catch (e) {
log.error('Unable to initialize Rewriter', e)
}
}
return rewriter
}
let originalPrepareStackTrace
function getPrepareStackTraceAccessor () {
if (!getPrepareStackTrace) {
getPrepareStackTrace = require('@datadog/wasm-js-rewriter/js/stack-trace').getPrepareStackTrace
}
originalPrepareStackTrace = Error.prepareStackTrace
let actual = getPrepareStackTrace(originalPrepareStackTrace)
return {
configurable: true,
get () {
return actual
},
set (value) {
actual = getPrepareStackTrace(value)
originalPrepareStackTrace = value
}
}
}
function getCompileMethodFn (compileMethod) {
let delegate = function (content, filename) {
try {
if (isDdTrace(filename)) {
return compileMethod.apply(this, [content, filename])
}
if (!isPrivateModule(filename) || !config.iast?.enabled) {
return compileMethod.apply(this, [content, filename])
}
// TODO when we have CJS support for orchestrion and taint-tracking, add
// them here as appropriate
const rewritten = rewriter.rewrite(content, filename, ['iast'])
incrementTelemetryIfNeeded(rewritten.metrics)
if (rewritten?.literalsResult && hardcodedSecretCh.hasSubscribers) {
hardcodedSecretCh.publish(rewritten.literalsResult)
}
if (rewritten?.content) {
return compileMethod.apply(this, [rewritten.content, filename])
}
} catch (e) {
log.error('Error rewriting file %s', filename, e)
}
return compileMethod.apply(this, [content, filename])
}
const shim = function () {
return delegate.apply(this, arguments)
}
unwrapCompile = function () {
delegate = compileMethod
}
return shim
}
function esmRewritePostProcess (rewritten, filename) {
const { literalsResult, metrics } = rewritten
if (metrics?.status === 'modified') {
if (filename.startsWith('file://')) {
filename = filename.slice(7)
}
cacheRewrittenSourceMap(filename, rewritten.content)
}
incrementTelemetryIfNeeded(metrics)
if (literalsResult && hardcodedSecretCh.hasSubscribers) {
hardcodedSecretCh.publish(literalsResult)
}
}
let shimmedPrepareStackTrace = false
function shimPrepareStackTrace () {
if (shimmedPrepareStackTrace) {
return
}
const pstDescriptor = Object.getOwnPropertyDescriptor(global.Error, 'prepareStackTrace')
if (!pstDescriptor || pstDescriptor.configurable || pstDescriptor.writable) {
Object.defineProperty(global.Error, 'prepareStackTrace', getPrepareStackTraceAccessor())
}
shimmedPrepareStackTrace = true
}
function enableRewriter (telemetryVerbosity) {
try {
if (config.iast?.enabled) {
const rewriter = getRewriter(telemetryVerbosity)
if (rewriter) {
shimPrepareStackTrace()
if (!globalThis.__DD_ESBUILD_IAST_WITH_SM && !globalThis.__DD_ESBUILD_IAST_WITH_NO_SM) {
// Avoid rewriting twice when application has been bundled
shimmer.wrap(Module.prototype, '_compile', compileMethod => getCompileMethodFn(compileMethod))
}
}
enableEsmRewriter(telemetryVerbosity)
}
} catch (e) {
log.error('Error enabling Rewriter', e)
}
}
function isEsmConfigured () {
return (isFlagPresent('--loader') ||
isFlagPresent('--experimental-loader') ||
isFlagPresent('dd-trace/initialize.mjs')) ||
isFlagPresent('dd-trace/register.js')
}
let enableEsmRewriter = function (telemetryVerbosity) {
if (isMainThread && Module.register && isEsmConfigured()) {
shimPrepareStackTrace()
const { port1, port2 } = new MessageChannel()
port1.on('message', (message) => {
const { type, data } = message
switch (type) {
case LOG_MESSAGE:
log[data.level]?.(...data.messages)
break
case REWRITTEN_MESSAGE:
esmRewritePostProcess(data.rewritten, data.url)
break
}
})
port1.unref()
port2.unref()
try {
Module.register('./rewriter-esm.mjs', {
parentURL: pathToFileURL(__filename),
transferList: [port2],
data: {
port: port2,
csiMethods,
telemetryVerbosity,
chainSourceMap: isFlagPresent('--enable-source-maps'),
orchestrionConfig,
iastEnabled: config?.iast?.enabled
}
})
} catch (e) {
log.error('Error enabling ESM Rewriter', e)
port1.close()
port2.close()
}
cacheRewrittenSourceMap = require('@datadog/wasm-js-rewriter/js/source-map').cacheRewrittenSourceMap
enableEsmRewriter = noop
}
}
function disable () {
unwrapCompile()
if (!Error.prepareStackTrace?.[kSymbolPrepareStackTrace]) return
try {
delete Error.prepareStackTrace
Error.prepareStackTrace = originalPrepareStackTrace
shimmedPrepareStackTrace = false
} catch (e) {
log.warn('Error disabling Rewriter', e)
}
}
function getOriginalPathAndLineFromSourceMap ({ path, line, column }) {
return getRewriterOriginalPathAndLineFromSourceMap(path, line, column)
}
function enable (configArg) {
config = configArg
enableRewriter(telemetry.verbosity || 'OFF')
}
module.exports = {
enable, disable, getOriginalPathAndLineFromSourceMap, getRewriter
}