From a5ab81a1ca07583bceeee352d946b69f5642a7cd Mon Sep 17 00:00:00 2001 From: Viacheslav Klimov Date: Mon, 26 Oct 2026 10:38:47 +0200 Subject: [PATCH] Refactor js-executor sandbox (cherry picked from commit 00af0acb7c325a03d4d377062c62242c30886eb5) --- msa/js-executor/api/jsExecutor.ts | 159 +++++++++++++++++++++++- msa/js-executor/test/coldPathProbe.ts | 29 +++++ msa/js-executor/test/jsExecutor.test.ts | 118 ++++++++++++++++++ 3 files changed, 302 insertions(+), 4 deletions(-) create mode 100644 msa/js-executor/test/coldPathProbe.ts diff --git a/msa/js-executor/api/jsExecutor.ts b/msa/js-executor/api/jsExecutor.ts index f977468d6f..6975fc5def 100644 --- a/msa/js-executor/api/jsExecutor.ts +++ b/msa/js-executor/api/jsExecutor.ts @@ -4,11 +4,164 @@ import vm, { Script } from 'vm'; import atob from 'atob'; import btoa from 'btoa'; -import {TextDecoder} from "util"; +import {TextDecoder, types} from "util"; import { _logger } from '../config/logger'; export type TbScript = Script | Function; +type SandboxErrors = { + Error: ErrorConstructor; + TypeError: TypeErrorConstructor; + RangeError: RangeErrorConstructor; +}; + +// The only values host helpers may return to the sandbox. +type SandboxPrimitive = string | boolean | undefined; + +const typedArrayPrototype = Object.getPrototypeOf(Uint8Array.prototype); + +function intrinsicGetter(prototype: object, name: string): (this: unknown) => any { + return Object.getOwnPropertyDescriptor(prototype, name)!.get!; +} + +const typedArrayBuffer = intrinsicGetter(typedArrayPrototype, 'buffer'); +const typedArrayByteOffset = intrinsicGetter(typedArrayPrototype, 'byteOffset'); +const typedArrayByteLength = intrinsicGetter(typedArrayPrototype, 'byteLength'); +const dataViewBuffer = intrinsicGetter(DataView.prototype, 'buffer'); +const dataViewByteOffset = intrinsicGetter(DataView.prototype, 'byteOffset'); +const dataViewByteLength = intrinsicGetter(DataView.prototype, 'byteLength'); + +// Sandbox-realm btoa, atob and TextDecoder delegating to the host helpers of installSandboxGlobals. +// Arguments must be coerced here, with intrinsics captured before user code runs. +// invoke() rethrows sandbox-realm errors only; anything else becomes a sandbox RangeError. +const sandboxGlobalsShim = new vm.Script(`(function (h) { + 'use strict'; + var S = String; + var getPrototypeOf = Object.getPrototypeOf; + var errorPrototype = Error.prototype; + var SandboxRangeError = RangeError; + function isSandboxError(e) { + if (e === null || typeof e !== 'object') { + return false; + } + for (var p = getPrototypeOf(e); p !== null; p = getPrototypeOf(p)) { + if (p === errorPrototype) { + return true; + } + } + return false; + } + function invoke(fn, a, b, c, d) { + try { + return fn(a, b, c, d); + } catch (e) { + if (isSandboxError(e)) { + throw e; + } + throw new SandboxRangeError('Maximum call stack size exceeded'); + } + } + globalThis.btoa = function btoa(data) { return invoke(h.btoa, S(data)); }; + globalThis.atob = function atob(data) { return invoke(h.atob, S(data)); }; + class TextDecoder { + constructor(label, options) { invoke(h.create, this, label === undefined ? 'utf-8' : S(label), !!(options && options.fatal), !!(options && options.ignoreBOM)); } + get encoding() { return invoke(h.prop, this, 'encoding'); } + get fatal() { return invoke(h.prop, this, 'fatal'); } + get ignoreBOM() { return invoke(h.prop, this, 'ignoreBOM'); } + decode(input, options) { return invoke(h.decode, this, input, !!(options && options.stream)); } + } + Object.defineProperty(TextDecoder.prototype, Symbol.toStringTag, {value: 'TextDecoder', configurable: true}); + globalThis.TextDecoder = TextDecoder; +})`); + +function toSandboxError(errors: SandboxErrors, hostError: unknown): Error { + const source = hostError instanceof Error ? hostError : new Error(String(hostError)); + const errorType = source instanceof RangeError ? errors.RangeError : source instanceof TypeError ? errors.TypeError : errors.Error; + const err = new errorType(source.message); + const code = (source as NodeJS.ErrnoException).code; + if (typeof code === 'string') { + Object.defineProperty(err, 'code', {value: code, writable: true, enumerable: true, configurable: true}); + } + return err; +} + +function requireString(value: unknown, name: string): string { + if (typeof value !== 'string') { + throw new TypeError(`The "${name}" argument must be of type string`); + } + return value; +} + +// Reads the input through host intrinsics only; the value itself is never passed on or property-accessed. +function toHostBytes(input: unknown): Uint8Array | undefined { + if (input === undefined) { + return undefined; + } + if (types.isAnyArrayBuffer(input)) { + return new Uint8Array(input); + } + if (types.isTypedArray(input)) { + return new Uint8Array(typedArrayBuffer.call(input), typedArrayByteOffset.call(input), typedArrayByteLength.call(input)); + } + if (types.isDataView(input)) { + return new Uint8Array(dataViewBuffer.call(input), dataViewByteOffset.call(input), dataViewByteLength.call(input)); + } + throw new TypeError('The "input" argument must be an instance of ArrayBuffer or ArrayBufferView'); +} + +function installSandboxGlobals(sandbox: vm.Context): void { + // Captured before user code runs, so later monkeypatching inside the sandbox has no effect. + const errors: SandboxErrors = vm.runInContext('({Error: Error, TypeError: TypeError, RangeError: RangeError})', sandbox); + const decoders = new WeakMap(); // host realm: user code cannot patch it + const decoderOf = (self: unknown): TextDecoder => { + const decoder = typeof self === 'object' && self !== null ? decoders.get(self) : undefined; + if (!decoder) { + throw new TypeError('Illegal invocation'); + } + return decoder; + }; + // The one place host results and errors cross into the sandbox. + const guard = (fn: (...args: A) => R) => (...args: A): R => { + let result: R; + try { + result = fn(...args); + } catch (e) { + throw toSandboxError(errors, e); + } + if ((typeof result === 'object' && result !== null) || typeof result === 'function') { + throw new errors.Error('Host value must not be returned to the sandbox'); + } + return result; + }; + const host = Object.assign(Object.create(null), { + btoa: guard((data: unknown) => btoa(requireString(data, 'data'))), + atob: guard((data: unknown) => atob(requireString(data, 'data'))), + create: guard((self: unknown, label: unknown, fatal: unknown, ignoreBOM: unknown) => { + if (typeof self !== 'object' || self === null || decoders.has(self)) { + throw new TypeError('Illegal invocation'); + } + decoders.set(self, new TextDecoder(requireString(label, 'label'), {fatal: fatal === true, ignoreBOM: ignoreBOM === true})); + return undefined; + }), + prop: guard((self: unknown, name: unknown): SandboxPrimitive => { + const decoder = decoderOf(self); + switch (name) { + case 'encoding': + return decoder.encoding; + case 'fatal': + return decoder.fatal; + case 'ignoreBOM': + return decoder.ignoreBOM; + default: + return undefined; + } + }), + decode: guard((self: unknown, input: unknown, stream: unknown) => + decoderOf(self).decode(toHostBytes(input), {stream: stream === true})), + }); + sandboxGlobalsShim.runInContext(sandbox)(host); +} + export class JsExecutor { useSandbox: boolean; private logger = _logger('JsExecutor'); @@ -62,9 +215,7 @@ export class JsExecutor { ctxArgs[i] = String(args[i]); } sandbox.args = ctxArgs; - sandbox.btoa = btoa; - sandbox.atob = atob; - sandbox.TextDecoder = TextDecoder; + installSandboxGlobals(sandbox); const result = script.runInContext(sandbox, {timeout: timeout}); resolve(result); } catch (err) { diff --git a/msa/js-executor/test/coldPathProbe.ts b/msa/js-executor/test/coldPathProbe.ts new file mode 100644 index 0000000000..44249382ae --- /dev/null +++ b/msa/js-executor/test/coldPathProbe.ts @@ -0,0 +1,29 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { JsExecutor } from '../api/jsExecutor'; + +// Runs one probe as the first sandbox execution of a fresh process and reports +// whether any error caught on stack overflow came from outside the sandbox realm. +const call = process.argv[2]; + +(async () => { + const exec = new JsExecutor(true); + const script = await exec.compileScript(`function(msg, metadata, msgType){ + var foreign; + function attempt() { + if (foreign) return; + try { ${call}; } catch (e) { + if (e === null || typeof e !== 'object' || (e.constructor !== RangeError && e.constructor !== TypeError && e.constructor !== Error)) { + foreign = String(e && e.name); + } + } + } + function recurse() { try { recurse(); } catch (e) {} attempt(); } + recurse(); + return foreign ? 'foreign error: ' + foreign : 'isolated'; + }`); + const out = await exec.executeScript(script, ['{}', '{}', 'X'], 20000); + process.stdout.write(String(out)); +})().catch((err) => { + process.stdout.write('probe failed: ' + String(err && err.message)); +}); diff --git a/msa/js-executor/test/jsExecutor.test.ts b/msa/js-executor/test/jsExecutor.test.ts index 061fd90623..1d74bf251a 100644 --- a/msa/js-executor/test/jsExecutor.test.ts +++ b/msa/js-executor/test/jsExecutor.test.ts @@ -3,6 +3,9 @@ // SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 import { describe, test } from 'node:test'; import assert from 'node:assert/strict'; +import { execFile } from 'node:child_process'; +import path from 'node:path'; +import { promisify } from 'node:util'; import { JsExecutor } from '../api/jsExecutor'; import { oauthBearerProvider } from '../queue/oAuthBearerProvider'; @@ -39,6 +42,121 @@ test('sandbox passes string args through unchanged', async () => { assert.equal(out.first, 'hello'); }); +const sandboxRealmProbes: [string, string][] = [ + ['btoa', 'btoa.constructor'], + ['atob', 'atob.constructor'], + ['TextDecoder', 'TextDecoder.constructor'], + ['TextDecoder instance', 'new TextDecoder().constructor.constructor'], + ['TextDecoder.prototype.decode', 'TextDecoder.prototype.decode.constructor'], + ['TextDecoder getter', 'Object.getOwnPropertyDescriptor(TextDecoder.prototype, "encoding").get.constructor'], + ['TextDecoder constructor error', '(function(){ try { new TextDecoder("no-such-encoding"); } catch (e) { return e.constructor.constructor; } })()'], + ['TextDecoder decode error', '(function(){ try { new TextDecoder().decode("not a buffer"); } catch (e) { return e.constructor.constructor; } })()'], + ['TextDecoder fatal decode error', '(function(){ try { new TextDecoder("utf-8", {fatal: true}).decode(new Uint8Array([0xff])); } catch (e) { return e.constructor.constructor; } })()'], + ['getter on foreign receiver', '(function(){ try { Object.getOwnPropertyDescriptor(TextDecoder.prototype, "fatal").get.call({}); } catch (e) { return e.constructor.constructor; } })()'], + ['patched WeakMap/String', '(function(){ var leak; WeakMap.prototype.get = function(k){ leak = this; }; String = function(x){ return x; }; var d = new TextDecoder(); d.decode(new Uint8Array([104])); try { btoa("\\u0100"); } catch (e) {} return leak ? leak.constructor.constructor : Function; })()'], + ['Error.prepareStackTrace', '(function(){ var fr; Error.prepareStackTrace = function(e, s){ fr = s; return ""; }; try { new TextDecoder("nope"); } catch (e) { e.stack; } for (var i = 0; fr && i < fr.length; i++) { var f = fr[i].getFunction && fr[i].getFunction(); if (f) return f.constructor; var t = fr[i].getThis && fr[i].getThis(); if (t && t.constructor) return t.constructor.constructor; } return Function; })()'], + // Node formats some ERR_INVALID_ARG_TYPE messages with util.inspect, which calls a custom inspect hook. + ...['utf-8', 'latin1', 'utf-16le'].map((encoding): [string, string] => [`TextDecoder.decode inspect hook (${encoding})`, + `(function(){ var F; var o = Object.create(null); o[Symbol.for("nodejs.util.inspect.custom")] = function(d, opts, insp){ F = insp && insp.constructor; return "x"; }; + try { new TextDecoder("${encoding}").decode(o); } catch (e) {} + var p = {}; Object.setPrototypeOf(p, ArrayBuffer.prototype); Object.defineProperty(p, "constructor", {value: ArrayBuffer}); p[Symbol.for("nodejs.util.inspect.custom")] = o[Symbol.for("nodejs.util.inspect.custom")]; + try { new TextDecoder("${encoding}").decode(p); } catch (e) {} + return F || Function; })()`]), + ...['btoa', 'atob'].map((fn): [string, string] => [`${fn} with patched String returning an inspectable object`, + `(function(){ var F; String = function(x){ var o = Object.create(null); o[Symbol.for("nodejs.util.inspect.custom")] = function(d, opts, insp){ F = insp && insp.constructor; return "x"; }; return o; }; + try { ${fn}("a"); } catch (e) {} + return F || Function; })()`]), +]; + +for (const [name, functionCtor] of sandboxRealmProbes) { + test(`sandbox globals belong to the sandbox realm: ${name}`, async () => { + const exec = new JsExecutor(true); + const script = await exec.compileScript(`function(msg, metadata, msgType){ + var F = ${functionCtor}; + return F('return process')(); + }`); + await assert.rejects( + exec.executeScript(script, ['{}', '{}', 'X'], 5000), + /process is not defined/, + 'host process must not be reachable from inside the sandbox', + ); + }); +} + +test('sandbox globals belong to the sandbox realm: resolving functions of a returned thenable', async () => { + const exec = new JsExecutor(true); + const script = await exec.compileScript(`function(msg, metadata, msgType){ + return {then: function(resolve){ resolve(resolve.constructor.constructor('return process')()); }}; + }`); + await assert.rejects( + exec.executeScript(script, ['{}', '{}', 'X'], 5000), + /process is not defined/, + ); +}); + +// A stack overflow inside a helper reproduces only while its host code path is cold, +// so each probe runs as the first sandbox execution of a fresh process. +const coldPathCalls = [ + "btoa('a')", + "atob('YQ==')", + "new TextDecoder('nope')", + "new TextDecoder().decode(new Uint8Array([104]))", + "new TextDecoder().encoding", + "Object.getOwnPropertyDescriptor(TextDecoder.prototype, 'fatal').get.call({})", +]; + +test('sandbox helpers rethrow only sandbox-realm errors on stack overflow in cold host code', async () => { + const run = promisify(execFile); + const results = await Promise.all(coldPathCalls.map(async (call) => { + const {stdout} = await run(process.execPath, ['--require', 'ts-node/register', path.join(__dirname, 'coldPathProbe.ts'), call], + {cwd: path.join(__dirname, '..'), env: {...process.env, TS_NODE_TRANSPILE_ONLY: 'true'}, timeout: 60000}); + return [call, stdout]; + })); + assert.deepEqual(results, coldPathCalls.map((call) => [call, 'isolated'])); +}); + +test('sandbox btoa/atob encode, decode and coerce like the browser API', async () => { + const exec = new JsExecutor(true); + const script = await exec.compileScript(`function(msg, metadata, msgType){ + return JSON.stringify([btoa('hello'), atob('aGVsbG8='), atob(btoa('\\u00ff\\u0000x')) === '\\u00ff\\u0000x', btoa(123), + btoa.name, atob.name, Object.getPrototypeOf(btoa) === Function.prototype]); + }`); + const out = await exec.executeScript(script, ['{}', '{}', 'X'], 5000); + assert.equal(out, JSON.stringify(['aGVsbG8=', 'hello', true, 'MTIz', 'btoa', 'atob', true])); +}); + +test('sandbox TextDecoder decodes like the host TextDecoder', async () => { + const exec = new JsExecutor(true); + const script = await exec.compileScript(`function(msg, metadata, msgType){ + var bytes = new Uint8Array([0xEF, 0xBB, 0xBF, 0x68, 0xC3, 0xA9, 0xE2, 0x82, 0xAC]); + var d = new TextDecoder(); + var stream = new TextDecoder(); + var streamed = stream.decode(new Uint8Array([0xE2, 0x82]), {stream: true}) + stream.decode(new Uint8Array([0xAC])); + var latin = new TextDecoder('latin1'); + function errorType(fn) { try { fn(); return 'none'; } catch (e) { return e instanceof RangeError ? 'RangeError' : e instanceof TypeError ? 'TypeError' : 'other'; } } + return JSON.stringify([ + d.decode(bytes), d.decode(bytes.buffer), d.decode(new DataView(bytes.buffer, 3)), d.decode(), + d.decode(bytes.subarray(3)), d.decode(bytes.subarray(4, 6)), d.decode(new Uint16Array(bytes.buffer, 2, 2)), + new TextDecoder('utf-8', {ignoreBOM: true}).decode(bytes).length, streamed, + d.encoding, d.fatal, d.ignoreBOM, new TextDecoder('UTF8', {fatal: true}).fatal, + latin.encoding, latin.decode(new Uint8Array([0xE9])), + errorType(function(){ new TextDecoder('utf-8', {fatal: true}).decode(new Uint8Array([0xFF])); }), + errorType(function(){ new TextDecoder('no-such-encoding'); }), + errorType(function(){ TextDecoder.prototype.decode.call({}, bytes); }), + errorType(function(){ TextDecoder(); }), + d instanceof TextDecoder, Object.prototype.toString.call(d)]); + }`); + const out = await exec.executeScript(script, ['{}', '{}', 'X'], 5000); + assert.equal(out, JSON.stringify([ + 'hé€', 'hé€', 'hé€', '', + 'hé€', 'é', '\uFFFDhé', + 4, '€', + 'utf-8', false, false, true, + 'windows-1252', 'é', + 'TypeError', 'RangeError', 'TypeError', 'TypeError', + true, '[object TextDecoder]'])); +}); + // The use_sandbox=false path is intentionally non-isolating: scripts compile // and run in the host realm via vm.compileFunction. The two tests below codify // that documented contract so any future behavior change shows up as a test