-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathvm_runner.ts
More file actions
234 lines (198 loc) · 6.98 KB
/
vm_runner.ts
File metadata and controls
234 lines (198 loc) · 6.98 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
/* eslint-disable no-restricted-globals, @typescript-eslint/no-require-imports */
import * as fs from 'node:fs';
import { isBuiltin } from 'node:module';
import * as path from 'node:path';
import * as vm from 'node:vm';
import * as Mocha from 'mocha';
import * as ts from 'typescript';
import * as mochaConfiguration from '../../mocha_mongodb';
const mocha = new Mocha(mochaConfiguration);
mocha.suite.emit('pre-require', global, 'host-context', mocha);
// mocha hooks and custom "require" modules needs to be loaded and injected separately
require('./throw_rejections.cjs');
require('./chai_addons.ts');
require('./ee_checker.ts');
for (const path of ['./hooks/leak_checker.ts', './hooks/configuration.ts']) {
const mod = require(path);
const hooks = mod.mochaHooks;
const register = (hookName, globalFn) => {
if (hooks[hookName]) {
const list = Array.isArray(hooks[hookName]) ? hooks[hookName] : [hooks[hookName]];
list.forEach(fn => globalFn(fn));
}
};
register('beforeAll', global.before);
register('afterAll', global.after);
register('beforeEach', global.beforeEach);
register('afterEach', global.afterEach);
}
let compilerOptions: ts.CompilerOptions = { module: ts.ModuleKind.CommonJS };
const tsConfigPath = path.join(__dirname, '../../tsconfig.json');
const configFile = ts.readConfigFile(tsConfigPath, ts.sys.readFile);
if (!configFile.error) {
const parsedConfig = ts.parseJsonConfigFileContent(
configFile.config,
ts.sys,
path.dirname(tsConfigPath)
);
compilerOptions = {
...parsedConfig.options,
module: ts.ModuleKind.CommonJS,
sourceMap: false,
// inline source map for stack traces
inlineSourceMap: true
};
} else {
throw new Error('tsconfig is missing');
}
const moduleCache = new Map();
const sandbox = vm.createContext({
__proto__: null,
console: console,
AbortController: AbortController,
AbortSignal: AbortSignal,
Date: global.Date,
Error: global.Error,
URL: global.URL,
URLSearchParams: global.URLSearchParams,
queueMicrotask: queueMicrotask,
performance: global.performance,
process: process,
context: global.context,
describe: global.describe,
xdescribe: global.xdescribe,
it: global.it,
xit: global.xit,
before: global.before,
after: global.after,
beforeEach: global.beforeEach,
afterEach: global.afterEach
});
function createProxiedRequire(parentPath: string) {
const parentDir = path.dirname(parentPath);
return function sandboxRequire(moduleIdentifier: string) {
// allow all code modules be imported by the host environment
if (isBuiltin(moduleIdentifier)) {
return require(moduleIdentifier);
}
// list of dependencies we want to import from within the sandbox
const sandboxedDependencies = ['bson'];
const isSandboxedDep = sandboxedDependencies.some(
dep => moduleIdentifier === dep || moduleIdentifier.startsWith(`${dep}/`)
);
if (!moduleIdentifier.startsWith('.') && !isSandboxedDep) {
return require(moduleIdentifier);
}
// require.resolve throws if module can't be loaded, let it bubble up
const fullPath = require.resolve(moduleIdentifier, { paths: [parentDir] });
return loadInSandbox(fullPath);
};
}
function loadInSandbox(filepath: string) {
const realPath = fs.realpathSync(filepath);
if (moduleCache.has(realPath)) {
return moduleCache.get(realPath);
}
// clientmetadata requires package.json to fetch driver's version
if (realPath.endsWith('package.json')) {
const jsonContent = JSON.parse(fs.readFileSync(realPath, 'utf8'));
moduleCache.set(realPath, jsonContent);
return jsonContent;
}
// js-bson is allowed to use Buffer, only ./src/ is not
const isSourceFile = realPath.includes('/src/') || !realPath.includes('node_modules');
const isTestFile = realPath.includes('.test.ts') || realPath.includes('.test.js');
let localBuffer = Buffer;
if (isSourceFile && !isTestFile) {
localBuffer = new Proxy(Buffer, {
get() {
throw new Error(
`Forbidden: 'Buffer' usage is not allowed in source files. Use Uint8Array instead. File: ${realPath}`
);
},
construct() {
throw new Error(
`Forbidden: 'Buffer' usage is not allowed in source files. Use Uint8Array instead. File: ${realPath}`
);
}
}) as any;
}
const content = fs.readFileSync(realPath, 'utf8');
let executableCode: string;
if (realPath.endsWith('.ts')) {
executableCode = ts.transpileModule(content, {
compilerOptions: compilerOptions,
fileName: realPath
}).outputText;
} else {
// .js or .cjs should work just fine
executableCode = content;
}
const exportsContainer = {};
const localModule = { exports: exportsContainer };
const localRequire = createProxiedRequire(realPath);
const filename = realPath;
const dirname = path.dirname(realPath);
// prevent recursion
moduleCache.set(realPath, localModule.exports);
try {
const wrapper = `(function(exports, require, module, __filename, __dirname, Buffer) {
${executableCode}
})`;
const script = new vm.Script(wrapper, { filename: realPath });
const fn = script.runInContext(sandbox);
fn(localModule.exports, localRequire, localModule, filename, dirname, localBuffer);
const result = localModule.exports;
const isBSON = realPath.includes('node_modules/bson');
const isError = realPath.includes('src/error.ts');
if (isBSON || isError) {
for (const [key, value] of Object.entries(result)) {
if (typeof value === 'function' && value.name) {
// force instanceof to work across contexts by defining custom `instanceof` function
Object.defineProperty(value, Symbol.hasInstance, {
value: (i: any) => i && (i.constructor.name === value.name || i instanceof value)
});
// also inject into global for easier access in tests
(sandbox as any)[key] = value;
}
}
}
moduleCache.set(realPath, result);
return result;
} catch (err: any) {
moduleCache.delete(realPath);
console.error(`Error running ${realPath} in sandbox:`, err);
throw err;
}
}
// use it similar to regular mocha:
// mocha --config test/mocha_mongodb.js test/integration
// ts-node test/runner/vm_context.ts test/integration
const userArgs = process.argv.slice(2);
const searchTargets = userArgs.length > 0 ? userArgs : ['test'];
const testFiles = searchTargets.flatMap(target => {
try {
const stats = fs.statSync(target);
if (stats.isDirectory()) {
const pattern = path.join(target, '**/*.test.{ts,js}').replace(/\\/g, '/');
return fs.globSync(pattern);
}
if (stats.isFile()) {
return [target];
}
} catch {
console.error(`Error: Could not find path "${target}"`);
}
return [];
});
if (testFiles.length === 0) {
console.log('No test files found.');
process.exit(0);
}
testFiles.forEach(file => {
loadInSandbox(path.resolve(file));
});
console.log('Running Tests...');
mocha.run(failures => {
process.exitCode = failures ? 1 : 0;
});