I have a web-application. As part of this, I need users of the app to be able to write (or copy and paste) very simple scripts to run against their data.
The scripts really can be very simple, and performance is only the most minor issue. And example of the sophistication of script I mean are something like:
ratio = 1.2345678
minimum = 10
def convert(money)
return money * ratio
end
if price < minimum
cost = convert(minimum)
else
cost = convert(price)
end
where price and cost are a global variables (something I can feed into the environment and access after the computation).
I do, however, need to guarantee some stuff.
Any scripts run cannot get access to the environment of Python. They cannot import stuff, call methods I don't explicitly expose for them, read or write files, spawn threads, etc. I need total lockdown.
I need to be able to put a hard-limit on the number of 'cycles' that a script runs for. Cycles is a general term here. could be VM instructions if the language byte-compiled. Apply-calls for an Eval/Apply loop. Or just iterations through some central processing loop that runs the script. The details aren't as important as my ability to stop something running after a short time and send an email to the owner and say "your scripts seems to be doing more than adding a few numbers together - sort them out."
It must run on Vanilla unpatched CPython.
So far I've been writing my own DSL for this task. I can do that. But I wondered if I could build on the shoulders of giants. Is there a mini-language available for Python that would do this?
There are plenty of hacky Lisp-variants (Even one I wrote on Github), but I'd prefer something with more non-specialist syntax (more C or Pascal, say), and as I'm considering this as an alternative to coding one myself I'd like something a bit more mature.
Any ideas?
Here is my take on this problem. Requiring that the user scripts run inside vanilla CPython means you either need to write an interpreter for your mini language, or compile it to Python bytecode (or use Python as your source language) and then "sanitize" the bytecode before executing it.
I've gone for a quick example based on the assumption that users can write their scripts in Python, and that the source and bytecode can be sufficiently sanitized through some combination of filtering unsafe syntax from the parse tree and/or removing unsafe opcodes from the bytecode.
The second part of the solution requires that the user script bytecode be periodically interrupted by a watchdog task which will ensure that the user script does not exceed some opcode limit, and for all of this to run on vanilla CPython.
Summary of my attempt, which mostly focuses on the 2nd part of the problem.
Hopefully this at least goes in the right direction. I'm interested to hear more about your solution when you arrive at it.
Source code for
lowperf.py
:Here is a sample user script
user.py
:Here is a sample run: