Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check if a function is a pure function?

I'm working on react-metaform, and one of my challenges is that I need to allow the end-user to define metadata as functions. Example:

socialSecurityNumber.required: (m) => m.type == 'person'

The problem is obvious: I cannot trust the user. So, these are the precautions i'm planning to make:

  • User-defined functions should be pure function. In the sense that, these functions can only access their parameter, nothing else.
  • User-defined functions will run in an environment that is resilient to exceptions, too long execution times and infinite loops. (I'm not worried about this right now).

The question is: How do I make sure a user-defined function only accesses it's parameters and nothing else?

like image 314
André Pena Avatar asked Nov 10 '22 03:11

André Pena


1 Answers

I would use esprima to parse users' JavaScript functions that are stored in files or in a database. And I would allow to run only code that passes the parsing test (only whitelisted features - using local variables, parameters, ...).

You can start with a very simple checking code that only allows very limited scripts and progressively improve it. However, I guess you will put a lot of effort to the solution over time because your users will always want more.


Note: Angular.js uses for its dependency injection this kind of 'trick': https://jsfiddle.net/987Lwezy/

function test() {
   console.log("This is my secret!");
}


function parser(f) {
    document.body.innerHTML = test.toString();
}

parser(test);
like image 167
Martin Vseticka Avatar answered Nov 14 '22 22:11

Martin Vseticka