Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What exactly does runInNewContext do?

I am currently learning some code-base, and it has used runInNewContext more often, I tried looking up for but there is no proper definition.

Reading the official docs specifies, all I could understand is the code is complied into the sandbox specified. What exactly does that mean, for example, there is a bit of code in the code-base that goes something like:

request(url, function(error, response, body) {
var subject = {}
try
  vm.runInNewContext(body, subject, url);
  deferred.resolve(subject);
catch _error
  console.log(_error);
}

What exactly happens here is confusing me.

Seeing this, I tried to toy around by passing a different object instead of body, but it spits out "Unexpected identifier".

like image 473
avinoth Avatar asked Dec 10 '14 06:12

avinoth


1 Answers

runInNewContext creates a new "context" or "sandbox" in which the code runs.

Say, for example, you have a chunk of code you want to run, which is loaded as a string. Just eval-ing the string can be dangerous, and gives you little control over what variables and globals this code has.

So, instead, you can create a sandbox, a new context, in which this code can be run. Further, you can "preset" variables that you want available, whether as contexts or as a way to pass things into the context.

So say your code looks like this:

var code = "var add = function(a,b){return a + b;}; add(one,two);";

This is a function, defined in a string, that adds two numbers, and then actively adds one and two. What are one and two? Right now they are undefined. But if you run it in a new context, you can (reasonably) safely run the string code and even define one and two:

vm.runInNewContext(code,{one:1,two:2});

which will cause the code to run and add(1,2). A more useful example might be to save it.

var result = 0, code = "var add = function(a,b){return a + b;}; result = add(one,two);";
vm.runInNewContext(code,{one:1,two:2,result:result});
console.log(result); // spits out 3

Notice that we created a variable result in our sandbox context, so that the code in code could set it.

I used it in cansecurity's declarative authorization, where you can set an expression to be evaluated and the output will only pass if the result is true. https://github.com/deitch/cansecurity look at https://github.com/deitch/cansecurity/blob/master/lib/declarative.js#L96

In that case, I actually take the result. For example, my code might be

var str = "user.id === req.user || user.role === 'admin'";
var authorized = vm.runInNewContext(str,{user:{id:"10",name:"John"},user:{role:"member",id:"10"}, req:{user:"20"}});
console.log(authorized); // spits out false, because user.id !== req.user, and user.role !== "admin"
like image 121
deitch Avatar answered Oct 03 '22 15:10

deitch