luau-lang / luau

A fast, small, safe, gradually typed embeddable scripting language derived from Lua
https://luau.org
MIT License
3.98k stars 373 forks source link

Can't define function in lua script after calling luaL_sandbox in host #1265

Closed Ono-Sendai closed 4 months ago

Ono-Sendai commented 4 months ago

After calling luaL_sandbox, which we are supposed to do apparently (according to https://github.com/luau-lang/luau?tab=readme-ov-file#building), I then execute the script with lua_pcall(state, 0, LUA_MULTRET, 0);.

In the Lua script, a new function is defined:

function f(x : number, y : number) : number
    return x + y
end

But this results in: 1: string: [string "test"]:40: attempt to modify a readonly table

So scripts can't define new functions?

Or are we supposed to execute the script first, then sandbox it? But doesn't this go against the principle of sandboxing in the first place?

zeux commented 4 months ago

The correct procedure is that instead of running code in the (sandboxed) global state, you create new threads, sandbox them using luaL_sandboxthread and run code inside them.

So, do this once when initializing the VM:

  1. luaL_newstate
  2. luaL_openlibs plus whatever extra global setup for the shared global environment you need via luaL_register / lua_setglobal
  3. luaL_sandbox

... and then do this any time you want to start a new script:

  1. lua_newthread
  2. luaL_sandboxthread
  3. luau_load with bytecode
  4. lua_resume or lua_pcall to run it

luaL_sandboxthread will create a writeable global table for the thread that will refer to the (read-only) shared global environment for unknown keys.

Ono-Sendai commented 4 months ago

Awesome, that seems to work so far, thank you.