From 8974b8869ced5cd2d685151ace8580ceadfe240c Mon Sep 17 00:00:00 2001 From: eskerda Date: Fri, 11 Dec 2020 17:22:17 +0100 Subject: [PATCH] feat(sandbox) add load mode to string functions --- sandbox.lua | 8 +++++--- spec/sandbox_spec.lua | 10 ++++++++++ 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/sandbox.lua b/sandbox.lua index be65e1c..58143f2 100644 --- a/sandbox.lua +++ b/sandbox.lua @@ -138,8 +138,6 @@ end -- Public interface: sandbox.protect function sandbox.protect(f, options) - if type(f) == 'string' then f = assert(loadstring(f)) end - options = options or {} local quota = false @@ -150,7 +148,11 @@ function sandbox.protect(f, options) local env = merge(options.env or {}, BASE_ENV) env._G = env._G or env - setfenv(f, env) + if type(f) == 'string' then + f = assert(load(f, nil, options.mode, env)) + else + setfenv(f, env) + end return function(...) diff --git a/spec/sandbox_spec.lua b/spec/sandbox_spec.lua index d1e9465..2bb04df 100644 --- a/spec/sandbox_spec.lua +++ b/spec/sandbox_spec.lua @@ -13,6 +13,16 @@ describe('sandbox.run', function() assert.equal(r, 'hello') end) + it('can run bytecode strings by default', function() + local fn = function() end + assert.has_no.error(function() sandbox.run(string.dump(fn)) end) + end) + + it('can\'t run bytecode strings if given a \'t\' mode option', function() + local fn = function() end + assert.error(function() sandbox.run(string.dump(fn), { mode = 't' }) end) + end) + it('has access to safe methods', function() assert.equal(10, sandbox.run("return tonumber('10')")) assert.equal('HELLO', sandbox.run("return string.upper('hello')"))