/
sandbox.js
345 lines (295 loc) · 9.72 KB
/
sandbox.js
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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
const { createHook, executionAsyncId } = require('async_hooks')
const { EventEmitter } = require('events')
const { homedir, tmpdir } = require('os')
const { dirname, join } = require('path')
const { promisify } = require('util')
const { mkdir } = require('fs/promises')
const rimraf = promisify(require('rimraf'))
const mockLogs = require('./mock-logs')
const pkg = require('../../package.json')
const chain = new Map()
const sandboxes = new Map()
// keep a reference to the real process
const _process = process
createHook({
init: (asyncId, type, triggerAsyncId, resource) => {
// track parentage of asyncIds
chain.set(asyncId, triggerAsyncId)
},
before: (asyncId) => {
// find the nearest parent id that has a sandbox
let parent = asyncId
while (chain.has(parent) && !sandboxes.has(parent)) {
parent = chain.get(parent)
}
process = sandboxes.has(parent)
? sandboxes.get(parent)
: _process
},
}).enable()
const _data = Symbol('sandbox.data')
const _dirs = Symbol('sandbox.dirs')
const _test = Symbol('sandbox.test')
const _mocks = Symbol('sandbox.mocks')
const _npm = Symbol('sandbox.npm')
const _parent = Symbol('sandbox.parent')
const _output = Symbol('sandbox.output')
const _proxy = Symbol('sandbox.proxy')
const _get = Symbol('sandbox.proxy.get')
const _set = Symbol('sandbox.proxy.set')
const _logs = Symbol('sandbox.logs')
// these config keys can be redacted widely
const redactedDefaults = [
'tmp',
]
// we can't just replace these values everywhere because they're known to be
// very short strings that could be present all over the place, so we only
// replace them if they're located within quotes for now
const vagueRedactedDefaults = [
'editor',
'shell',
]
const normalize = (str) => str
.replace(/\r\n/g, '\n') // normalize line endings (for ini)
.replace(/[A-z]:\\/g, '\\') // turn windows roots to posix ones
.replace(/\\+/g, '/') // replace \ with /
class Sandbox extends EventEmitter {
constructor (test, options = {}) {
super()
this[_test] = test
this[_mocks] = options.mocks || {}
this[_data] = new Map()
this[_output] = []
const tempDir = `${test.testdirName}-sandbox`
this[_dirs] = {
temp: tempDir,
global: options.global || join(tempDir, 'global'),
home: options.home || join(tempDir, 'home'),
project: options.project || join(tempDir, 'project'),
cache: options.cache || join(tempDir, 'cache'),
}
this[_proxy] = new Proxy(_process, {
get: this[_get].bind(this),
set: this[_set].bind(this),
})
this[_proxy].env = {}
this[_proxy].argv = []
test.cleanSnapshot = this.cleanSnapshot.bind(this)
test.afterEach(() => this.reset())
test.teardown(() => this.teardown())
}
get config () {
return this[_npm] && this[_npm].config
}
get logs () {
return this[_logs]
}
get global () {
return this[_dirs].global
}
get home () {
return this[_dirs].home
}
get project () {
return this[_dirs].project
}
get cache () {
return this[_dirs].cache
}
get process () {
return this[_proxy]
}
get output () {
return this[_output].map((line) => line.join(' ')).join('\n')
}
cleanSnapshot (snapshot) {
let clean = normalize(snapshot)
const viewer = _process.platform === 'win32'
? /"browser"([^:]+|$)/g
: /"man"([^:]+|$)/g
// the global prefix is platform dependent
const realGlobalPrefix = _process.platform === 'win32'
? dirname(_process.execPath)
: dirname(dirname(_process.execPath))
const cache = _process.platform === 'win32'
? /\{HOME\}\/npm-cache(\r?\n|"|\/|$)/g
: /\{HOME\}\/\.npm(\n|"|\/|$)/g
// and finally replace some paths we know could be present
clean = clean
.replace(viewer, '"{VIEWER}"$1')
.split(normalize(this[_proxy].execPath)).join('{EXECPATH}')
.split(normalize(_process.execPath)).join('{REALEXECPATH}')
.split(normalize(this.global)).join('{GLOBALPREFIX}')
.split(normalize(realGlobalPrefix)).join('{REALGLOBALREFIX}')
.split(normalize(this.project)).join('{LOCALPREFIX}')
.split(normalize(this.home)).join('{HOME}')
.replace(cache, '{CACHE}$1')
.split(normalize(dirname(dirname(__dirname)))).join('{NPMDIR}')
.split(normalize(tmpdir())).join('{TMP}')
.split(normalize(homedir())).join('{REALHOME}')
.split(this[_proxy].platform).join('{PLATFORM}')
.split(this[_proxy].arch).join('{ARCH}')
.replace(new RegExp(process.version, 'g'), '{NODE-VERSION}')
.replace(new RegExp(pkg.version, 'g'), '{NPM-VERSION}')
// We do the defaults after everything else so that they don't cause the
// other cleaners to miss values we would have clobbered here. For
// instance if execPath is /home/user/.nvm/versions/node/1.0.0/bin/node,
// and we replaced the node version first, the real execPath we're trying
// to replace would no longer be represented, and be missed.
if (this[_npm]) {
// replace default config values with placeholders
for (const name of redactedDefaults) {
const value = this[_npm].config.defaults[name]
clean = clean.split(normalize(value)).join(`{${name.toUpperCase()}}`)
}
// replace vague default config values that are present within quotes
// with placeholders
for (const name of vagueRedactedDefaults) {
const value = this[_npm].config.defaults[name]
clean = clean.split(`"${normalize(value)}"`).join(`"{${name.toUpperCase()}}"`)
}
}
return clean
}
// test.afterEach hook
reset () {
this.removeAllListeners()
this[_parent] = undefined
this[_output] = []
this[_data].clear()
this[_proxy].env = {}
this[_proxy].argv = []
this[_npm] = undefined
}
// test.teardown hook
teardown () {
if (this[_parent]) {
const sandboxProcess = sandboxes.get(this[_parent])
sandboxProcess.removeAllListeners('log')
sandboxes.delete(this[_parent])
}
if (this[_npm]) {
this[_npm].unload()
}
return rimraf(this[_dirs].temp).catch(() => null)
}
// proxy get handler
[_get] (target, prop, receiver) {
if (this[_data].has(prop)) {
return this[_data].get(prop)
}
if (this[prop] !== undefined) {
return Reflect.get(this, prop, this)
}
return Reflect.get(target, prop, receiver)
}
// proxy set handler
[_set] (target, prop, value) {
if (prop === 'env') {
value = {
...value,
HOME: this.home,
}
}
if (prop === 'argv') {
value = [
process.execPath,
join(dirname(process.execPath), 'npm'),
...value,
]
}
return this[_data].set(prop, value)
}
async run (command, argv = []) {
await Promise.all([
mkdir(this.project, { recursive: true }),
mkdir(this.home, { recursive: true }),
mkdir(this.global, { recursive: true }),
])
// attach the sandbox process now, doing it after the promise above is
// necessary to make sure that only async calls spawned as part of this
// call to run will receive the sandbox. if we attach it too early, we
// end up interfering with tap
this[_parent] = executionAsyncId()
this[_data].set('_asyncId', this[_parent])
sandboxes.set(this[_parent], this[_proxy])
process = this[_proxy]
this[_proxy].argv = [
'--prefix', this.project,
'--userconfig', join(this.home, '.npmrc'),
'--globalconfig', join(this.global, 'npmrc'),
'--cache', this.cache,
command,
...argv,
]
const mockedLogs = mockLogs(this[_mocks])
this[_logs] = mockedLogs.logs
const Npm = this[_test].mock('../../lib/npm.js', {
'../../lib/utils/update-notifier.js': async () => {},
...this[_mocks],
...mockedLogs.logMocks,
})
this.process.on('log', (l, ...args) => {
if (l !== 'pause' && l !== 'resume') {
this[_logs].push([l, ...args])
}
})
this[_npm] = new Npm()
this[_npm].output = (...args) => this[_output].push(args)
await this[_npm].load()
const cmd = this[_npm].argv.shift()
return this[_npm].exec(cmd, this[_npm].argv)
}
async complete (command, argv, partial) {
if (!Array.isArray(argv)) {
partial = argv
argv = []
}
await Promise.all([
mkdir(this.project, { recursive: true }),
mkdir(this.home, { recursive: true }),
mkdir(this.global, { recursive: true }),
])
// attach the sandbox process now, doing it after the promise above is
// necessary to make sure that only async calls spawned as part of this
// call to run will receive the sandbox. if we attach it too early, we
// end up interfering with tap
this[_parent] = executionAsyncId()
this[_data].set('_asyncId', this[_parent])
sandboxes.set(this[_parent], this[_proxy])
process = this[_proxy]
this[_proxy].argv = [
'--prefix', this.project,
'--userconfig', join(this.home, '.npmrc'),
'--globalconfig', join(this.global, 'npmrc'),
'--cache', this.cache,
command,
...argv,
]
const mockedLogs = mockLogs(this[_mocks])
this[_logs] = mockedLogs.logs
const Npm = this[_test].mock('../../lib/npm.js', {
'../../lib/utils/update-notifier.js': async () => {},
...this[_mocks],
...mockedLogs.logMocks,
})
this.process.on('log', (l, ...args) => {
if (l !== 'pause' && l !== 'resume') {
this[_logs].push([l, ...args])
}
})
this[_npm] = new Npm()
this[_npm].output = (...args) => this[_output].push(args)
await this[_npm].load()
const impl = await this[_npm].cmd(command)
return impl.completion({
partialWord: partial,
conf: {
argv: {
remain: ['npm', command, ...argv],
},
},
})
}
}
module.exports = Sandbox