laverdet / isolated-vm

Secure & isolated JS environments for nodejs
ISC License
2.18k stars 154 forks source link

Heap out of memory #457

Closed Spulae closed 9 months ago

Spulae commented 9 months ago

Node.js Version: v21.6.1

I need to enforce an 8MB memory limit while executing untrusted JavaScript code. Below is the code snippet I'm using:

import ivm from 'isolated-vm';

const isolate = new ivm.Isolate({ memoryLimit: 8 });
const context = await isolate.createContext();

const code = "let obj = {}; for(let i = 0; i < 1000000; i++) { obj['a'+i] = 'WKEGJLWBEGJLWENGLKWENLKGNWELKGNWKLEGNLKWENGLWENGKLWENKLG'; } return obj;";
const result = await context.evalClosure(code, undefined, { result: { copy: true } });

However, when I run the program, it terminates unexpectedly with the following error message:

<--- Last few GCs --->

[22163:0x6aacc50]      137 ms: Mark-Compact (reduce) 5.5 (8.7) -> 5.5 (7.2) MB, 14.48 / 0.00 ms  (average mu = 0.293, current mu = 0.003) last resort; GC in old space requested
[22163:0x6aacc50]      146 ms: Mark-Compact (reduce) 5.5 (7.2) -> 5.5 (6.9) MB, 8.32 / 0.00 ms  (average mu = 0.203, current mu = 0.005) last resort; GC in old space requested

<--- JS stacktrace --->

CALL_AND_RETRY_LAST
is_heap_oom = 1

<--- Heap statistics --->
total_heap_size = 7286784
total_heap_size_executable = 262144
total_physical_size = 6234112
total_available_size = 6444176
used_heap_size = 5760280
heap_size_limit = 11534336
malloced_memory = 2130032
peak_malloced_memory = 296184
does_zap_garbage = 0

Shouldn't the memoryLimit option in the Isolate constructor prevent this type of error? If not, how can I safely execute untrusted JavaScript code without causing my program to crash?

laverdet commented 9 months ago

Very low memory limits tend to cause this condition. You can listen for onCatastrophicError which will give you a way to kind of recover from the issue, but not really. I recommend at least 128mb memory limit though.