-
Notifications
You must be signed in to change notification settings - Fork 63
/
Copy pathsandbox-sanity.test.js
458 lines (375 loc) · 15.7 KB
/
sandbox-sanity.test.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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
const Mocha = require('mocha'),
IS_NODE = typeof window === 'undefined',
TEST_ENV_GLOBALS = [
...Object.getOwnPropertyNames(Mocha),
// Following are Mocha's properties that
// for some reason are not enumerable
'context',
'xcontext',
'specify',
'xspecify',
// nyc,
'__coverage__',
// sinon
'sinon',
// chai
'expect'
],
IGNORED_GLOBALS = [
// Not required
'BroadcastChannel',
'FinalizationRegistry',
'FormData',
'Headers',
'MessageChannel',
'MessageEvent',
'MessagePort',
'Performance',
'PerformanceEntry',
'PerformanceMark',
'PerformanceMeasure',
'PerformanceObserver',
'PerformanceObserverEntryList',
'PerformanceResourceTiming',
'Request',
'Response',
'WeakRef',
'WebAssembly',
'fetch',
'global',
'globalThis',
'performance',
// No browser support
'process',
// requires node>=v19
'CustomEvent',
// requires node>=v21
'navigator',
// requires node>=22
'Iterator',
'Navigator',
'WebSocket',
// requires node>=23
'CloseEvent'
];
describe('sandbox', function () {
this.timeout(1000 * 60);
var Sandbox = require('../../lib');
it('should create context', function (done) {
Sandbox.createContext(function (err, ctx) {
if (err) { return done(err); }
ctx.on('error', done);
ctx.ping(function (err, ttl, packet) {
expect(err).to.be.null;
expect(packet).to.be.ok;
expect(ttl).to.be.a('number').that.is.above(-1);
done();
});
});
});
describe('invalid targets', function () {
let context;
function tester (input, done) {
context.on('error', done);
context.execute(input, function (err) {
expect(err).to.be.ok;
expect(err).to.have.property('message', 'sandbox: no target provided for execution');
done();
});
context.removeEventListener('error', done);
}
before(function (done) {
Sandbox.createContext(function (err, ctx) {
if (err) { return done(err); }
context = ctx;
done();
});
});
it('should not execute `null`', function (done) { tester(null, done); });
it('should not execute `undefined`', function (done) { tester(undefined, done); });
});
describe('valid empty targets', function () {
let context;
function tester (input, done) {
context.on('error', done);
context.execute(input, done);
}
before(function (done) {
Sandbox.createContext(function (err, ctx) {
if (err) { return done(err); }
context = ctx;
done();
});
});
it('should execute \'\'', function (done) { tester('', done); });
it('should execute []', function (done) { tester([], done); });
it('should execute [\'\']', function (done) { tester([''], done); });
it('should not execute `{}`', function (done) { tester({}, done); });
it('should not execute `{ script: {} }`', function (done) { tester({ script: {} }, done); });
it('should execute { script: { exec: \'\' } }', function (done) { tester({ script: { exec: '' } }, done); });
it('should execute { script: { exec: [] } }', function (done) { tester({ script: { exec: [] } }, done); });
it('should execute { script: { exec: [\'\'] }}', function (done) { tester({ script: { exec: [''] } }, done); });
});
it('should execute a piece of code', function (done) {
Sandbox.createContext(function (err, ctx) {
if (err) { return done(err); }
ctx.on('error', done);
ctx.execute('throw new Error("this will regurgitate!")', function (err) {
expect(err).to.be.ok;
expect(err).to.have.property('message', 'this will regurgitate!');
done();
});
});
});
it('should execute code with top level await', function (done) {
Sandbox.createContext(function (err, ctx) {
if (err) { return done(err); }
ctx.on('error', done);
ctx.execute(`
async function main () {
await Promise.resolve();
}
await main();
`, done);
});
});
it('should have a few important globals', function (done) {
Sandbox.createContext(function (err, ctx) {
if (err) { return done(err); }
ctx.on('error', done);
ctx.execute(`
var assert = require('assert');
assert.equal(typeof _, 'function');
assert.equal(typeof Error, 'function');
assert.equal(typeof console, 'object');
`, done);
});
});
it('should not have access to uvm bridge', function (done) {
Sandbox.createContext(function (err, ctx) {
if (err) { return done(err); }
ctx.on('error', done);
ctx.execute(`
var assert = require('assert');
assert.equal(typeof bridge, 'undefined');
assert.equal(typeof this.bridge, 'undefined');
assert.equal(typeof Function('return this.bridge')(), 'undefined');
`, done);
});
});
it('should not be able to mutate Error.prepareStackTrace', function (done) {
Sandbox.createContext(function (err, ctx) {
if (err) { return done(err); }
ctx.on('error', done);
ctx.execute(`
var assert = require('assert');
var fn = Error.prepareStackTrace;
Error.prepareStackTrace = () => {};
assert.equal(Error.prepareStackTrace, fn);
var err = new Error('Test');
assert.equal(err.stack.split('\\n')[0], 'Error: Test');
`, done);
});
});
it('should not have access to global properties', function (done) {
Sandbox.createContext(function (err, ctx) {
if (err) { return done(err); }
ctx.on('error', done);
ctx.execute(`
var assert = require('assert');
var allowedGlobals = ${JSON.stringify(require('uniscope/lib/allowed-globals'))};
var ignoredProps = [
'TEMPORARY', 'PERSISTENT', // DedicatedWorkerGlobalScope constants (in Browser)
'require', 'eval', 'console', // uniscope ignored
]
var propNames = [];
var contextObject = Function('return this;')();
do {
propNames = propNames.concat(Object.getOwnPropertyNames(contextObject));
contextObject = Object.getPrototypeOf(contextObject);
// traverse until Object prototype
// @note since we mutated the scope already, don't check using the constructor
// instead, check for hasOwnProperty existence on the contextObject.
} while (contextObject && !Object.hasOwnProperty.call(contextObject, 'hasOwnProperty'));
// filter out the ignored properties
propNames = propNames.filter(prop => !ignoredProps.includes(prop));
// FIXME: why's 'SharedArrayBuffer' missing from browser's context?
// Temporarily added to fix browser tests
!propNames.includes('SharedArrayBuffer') && propNames.push('SharedArrayBuffer');
// Make sure all allowed globals exists
const context = Function('return this;')();
for (const prop of allowedGlobals) {
if (prop === 'undefined' || prop === 'SharedArrayBuffer') {
continue;
}
assert.equal(context[prop] !== undefined, true, 'prop ' + prop + ' does not exist');
}
// make sure both propNames and allowedGlobals are same
assert.equal(JSON.stringify(propNames.sort()), JSON.stringify(allowedGlobals.sort()));
// double check using the diff
var diff = propNames
.filter(x => !allowedGlobals.includes(x))
.concat(allowedGlobals.filter(x => !propNames.includes(x)));
assert.equal(diff.length, 0);
`, done);
});
});
it('should accept an external execution id', function (done) {
Sandbox.createContext(function (err, ctx) {
if (err) { return done(err); }
ctx.on('error', done);
ctx.execute(`
var assert = require('assert');
assert.equal(typeof _, 'function');
assert.equal(typeof Error, 'function');
assert.equal(typeof console, 'object');
`, {
id: 'my-test-id'
}, function (err, execution) {
if (err) { return done(err); }
expect(execution).to.have.property('id', 'my-test-id');
done();
});
});
});
it('should create context fleet using templates', function (done) {
Sandbox.createContextFleet({
grpc: '',
websocket: ''
}, {}, (err, fleet) => {
if (err) { return done(err); }
expect(fleet).to.be.an('object');
expect(fleet.getContext).to.be.a('function');
expect(fleet.disposeAll).to.be.a('function');
done();
});
});
it('should return the correct context for the given template name', function (done) {
Sandbox.createContextFleet({
grpc: `
const chai = require('chai');
class Message {
constructor () {
this.type = 'grpc-message';
}
get to() {
return chai.expect(this).to;
}
}
function initializeExecution () {
return {
request: {
type: 'grpc-request'
},
response: {
type: 'grpc-response'
},
message: new Message(),
}
};
function chaiPlugin (chai) {
const Assertion = chai.Assertion;
Assertion.addProperty('grpcRequest', function () {
this.assert(this._obj.type === 'grpc-request',
'expecting a gRPC request but got #{this}',
'not expecting a gRPC request object');
});
Assertion.addProperty('grpcResponse', function () {
this.assert(this._obj.type === 'grpc-response',
'expecting a gRPC response but got #{this}',
'not expecting a gRPC response object');
});
Assertion.addProperty('grpcMessage', function () {
this.assert(this._obj.type === 'grpc-message',
'expecting a gRPC message but got #{this}',
'not expecting a gRPC message object');
});
}
module.exports = { initializeExecution, chaiPlugin };
`,
websocket: ''
}, {}, {}, (err, fleet) => {
if (err) { return done(err); }
fleet.getContext('grpc', (err, ctx) => {
if (err) { return done(err); }
ctx.on('error', done);
ctx.on('execution.assertion', (_, assertions) => {
assertions.forEach((a) => {
expect(a.passed).to.be.true;
});
});
ctx.execute(`
pm.test('Should be gRPC request, response, and message', () => {
pm.request.to.be.grpcRequest;
pm.response.to.be.grpcResponse;
pm.message.to.be.grpcMessage;
});
`, done);
});
});
});
it('should not be able to access NodeJS\'s `require`', function (done) {
Sandbox.createContext(function (err, ctx) {
if (err) { return done(err); }
ctx.on('error', done);
ctx.execute('const childProcess = require("child_process");', function (err) {
expect(err).to.be.ok;
expect(err).to.have.property('message', 'Cannot find module \'child_process\'');
done();
});
});
});
it('should persist overridden `require` across executions', function (done) {
const consoleSpy = sinon.spy();
Sandbox.createContext(function (err, ctx) {
if (err) { return done(err); }
ctx.on('error', done);
ctx.on('console', consoleSpy);
ctx.execute(`
require = (...args) => {
if (args[0] === 'utils') {
return () => console.log('utils');
}
return require(...args);
}
require('utils')();
`, function (err) {
if (err) { return done(err); }
ctx.execute('require(\'utils\')();', function (err) {
if (err) { return done(err); }
expect(consoleSpy).to.be.calledTwice;
expect(consoleSpy.firstCall.args[2]).to.equal('utils');
expect(consoleSpy.secondCall.args[2]).to.equal('utils');
done();
});
});
});
});
(IS_NODE ? it : it.skip)('should have missing globals as subset of explicitly ignored globals', function (done) {
Sandbox.createContext(function (err, ctx) {
if (err) { return done(err); }
ctx.on('error', done);
const nodeGlobals = Object.getOwnPropertyNames(this).filter((prop) => {
return !TEST_ENV_GLOBALS.includes(prop);
});
ctx.execute(`
var assert = require('assert');
var sandboxGlobals = Object.getOwnPropertyNames(this);
var contextObject = Function('return this;')();
do {
sandboxGlobals = sandboxGlobals.concat(Object.getOwnPropertyNames(contextObject));
contextObject = Object.getPrototypeOf(contextObject);
// traverse until Object prototype
// @note since we mutated the scope already, don't check using the constructor
// instead, check for hasOwnProperty existence on the contextObject.
} while (contextObject && !Object.hasOwnProperty.call(contextObject, 'hasOwnProperty'));
const diffWithNode = ${JSON.stringify(nodeGlobals)}
.filter((nodeGlobal) => !sandboxGlobals.includes(nodeGlobal))
.sort();
const isDiffSubsetOfIgnoredGlobals = diffWithNode
.every((v) => ${JSON.stringify(IGNORED_GLOBALS)}.includes(v));
assert.equal(isDiffSubsetOfIgnoredGlobals, true);
`, done);
});
});
});