simplification
Download
712 lines 27.7 KiBLuaModified 2026-11-09 raw
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712
-- Tests for using Nomsu as a library from Lua (run with: lua test/library.lua)
local root_dir = (arg and arg[0] or ""):match("^(.*)/test/[^/]*$") or "."
package.path = root_dir.."/?.lua;"..package.path

-- Some C modules (like lpeg and lfs) make globals of their own, so load them before
-- checking which globals Nomsu makes
for _, name in ipairs{"lpeg", "re", "lfs"} do pcall(require, name) end
local globals_before = {}
for k in pairs(_G) do globals_before[k] = true end
local package_before = {}
for k in pairs(package) do package_before[k] = true end

local nomsu = require "nomsu"

local failures, tests = 0, 0
local function test(name, fn)
    tests = tests + 1
    -- Like Nomsu's test tool, show "[ .. ]" while the test runs, then overwrite it
    io.write("[ .. ] ", name)
    io.flush()
    local ok, err = pcall(fn)
    if ok then
        io.write("\r[\027[32mPASS\027[0m\n")
    else
        failures = failures + 1
        io.write("\r[\027[31;1mFAIL\027[0m\n    ", (tostring(err):gsub("\n", "\n    ")), "\n")
    end
end

-- Make a runtime that collects its output, and return it with a function that
-- returns (and clears) the output so far
local function capturing_runtime(config)
    local output = {}
    config = config or {}
    config.print = function(text) output[#output+1] = text end
    local runtime = nomsu.Runtime(config)
    return runtime, function()
        local text = table.concat(output)
        output = {}
        return text
    end
end

local function assert_equal(actual, expected)
    if actual ~= expected then
        error(("expected %q, but got %q"):format(tostring(expected), tostring(actual)), 2)
    end
end

test("run() returns the code's value", function()
    local ok, value = capturing_runtime():run("return (1 + 2)")
    assert(ok, value)
    assert_equal(value, 3)
end)

test("Errors are returned, not raised", function()
    local runtime = capturing_runtime()
    local ok, err = runtime:run("$x = []")
    assert_equal(ok, false)
    assert(type(err) == "string" and err:match("Parse error"), err)
    ok, err = runtime:run("fail \"oops\"")
    assert_equal(ok, false)
    assert(err:match("oops"), err)
end)

test("Loading Nomsu doesn't make globals", function()
    nomsu.Runtime{print = function() end}:run("say \"x\"")
    for k in pairs(_G) do assert(globals_before[k], "new global: "..tostring(k)) end
    for k in pairs(package) do assert(package_before[k], "new package field: "..tostring(k)) end
end)

test("(say) and (ask) use the runtime's output and input", function()
    local runtime, output = capturing_runtime{input = function() return "Bob" end}
    assert(runtime:run("say \"Hello\" 1\nsay \"x\" inline"))
    assert_equal(output(), "Hello1\nx")
    assert(runtime:run("say \"Hi \\(ask \"Name? \")\""))
    assert_equal(output(), "Name? Hi Bob\n")
end)

test("Runtimes have separate modules and compile rules", function()
    local a = capturing_runtime()
    local b = capturing_runtime()
    assert(a.root.LOADED_MODULES ~= b.root.LOADED_MODULES)
    assert(a.root.LOADED_MODULES.core ~= b.root.LOADED_MODULES.core)
    assert(a.root.COMPILE_RULES ~= b.root.COMPILE_RULES)
end)

test("Compile rules can use names that the file's variables also have", function()
    local runtime = capturing_runtime()
    -- A compile rule's own arguments, and the variables it assigns or loops over
    local ok, result = runtime:run([[
$x = 5
$s = 1
$i = 1
(double $x) compiles to "(\($x as lua expr) * 2)"
(triple $y) compiles to:
    $s = 0
    for $i in (1 to 3):
        $s += 1
    return (Lua "(\($y as lua expr) * 3)")
return ((double 4) + (triple 4))]])
    assert(ok, result)
    assert_equal(result, 20)
    -- But not variables that only get a value when the file runs
    local ok2, err = runtime:run([[
$z = 5
(bad) compiles to "\$z"]])
    assert(not ok2 and tostring(err):match("compile%-time code uses %$z"), tostring(err))
end)

local api = [[
#!/usr/bin/env nomsu -V8.0.0
public:
    (greet $name) means (say "Hi \$name")
    (explode) means:
        fail "kaboom"
]]

test("Modules can come from a table", function()
    local runtime, output = capturing_runtime{
        modules = {["game/api"] = api}
    }
    assert(runtime:run("use \"game/api\"\ngreet \"Ann\""))
    assert_equal(output(), "Hi Ann\n")
end)

test("Errors in modules from a table show their code", function()
    local runtime = capturing_runtime{
        modules = {["game/api"] = api}
    }
    local ok, err = runtime:run("use \"game/api\"\nexplode")
    assert_equal(ok, false)
    assert(err:match("game/api%.nom:5"), err)
    assert(err:match("fail \"kaboom\""), err)
end)

test("Each runtime shows its own module's code in errors", function()
    local function make(message)
        return capturing_runtime{
            modules = {
                m = "#!/usr/bin/env nomsu -V8.0.0\npublic:\n    (go) means:\n        fail \""..message.."\"\n"
            }
        }
    end
    -- Several runtimes, since which runtime's code is found first depends on the order
    -- of a table iteration
    local runtimes = {}
    for i = 1, 5 do
        runtimes[i] = make("from runtime "..i..(" "):rep(i))
        assert(runtimes[i]:run("use \"m\""))
    end
    for i, runtime in ipairs(runtimes) do
        local _, err = runtime:run("use \"m\"\ngo")
        assert(err:find("fail \"from runtime "..i..(" "):rep(i).."\"", 1, true), err)
    end
end)

test("A missing module is an error", function()
    local runtime = capturing_runtime{modules = {}}
    local ok, err = runtime:run("use \"nowhere\"")
    assert_equal(ok, false)
    assert(tostring(err):match("nowhere"), err)
end)

test("(exit) stops the code, not the program", function()
    local runtime, output = capturing_runtime()
    local ok, signal = runtime:run("say \"before\"\nexit 3\nsay \"after\"")
    assert_equal(ok, false)
    assert_equal(type(signal), "table")
    assert_equal(signal.exit, 3)
    assert_equal(output(), "before\n")
end)

test("(try) doesn't catch (exit)", function()
    local runtime, output = capturing_runtime()
    local ok, signal = runtime:run("try:\n    exit 4\n..if it fails:\n    say \"caught\"")
    assert_equal(ok, false)
    assert_equal(signal.exit, 4)
    assert_equal(output(), "")
end)

test("Runtimes are freed when they're no longer used", function()
    local alive = setmetatable({}, {__mode = "k"})
    local function use_runtime()
        local runtime = capturing_runtime()
        local text = ("x"):rep(20000)
        for i = 1, 50 do assert(runtime:run("$s = \""..text..i.."\"")) end
        alive[runtime.root] = true
    end
    use_runtime()
    -- LuaJIT's compiled traces can refer to the last runtime until they're flushed
    if jit then jit.flush() end
    collectgarbage(); collectgarbage()
    assert(next(alive) == nil, "the runtime wasn't freed")
end)

-------------------------------------------------------------------------------------
-- Sandboxes

local function sandbox(config)
    local runtime, output = capturing_runtime(config)
    runtime:seal()
    return runtime, output
end

-- Run Lua code directly in a sandbox's runtime environment. This is the most that
-- sandboxed code should ever be able to do, so everything has to be safe even then.
local function run_lua_in(runtime, code)
    local fn = assert(load(code, "attack", "t", runtime.environment.RUNTIME_ENV))
    return pcall(fn)
end

test("Sandboxed code can use the core language", function()
    local runtime, output = sandbox()
    assert(runtime:run([[
(double $x) means ($x * 2)
$total = 0
for $i in (1 to 4):
    $total += (double $i)
$squares = (($x * $x) for $x in {1, 2, 3})
try:
    fail "oops"
..if it fails with $e:
    $caught = ($e, matches "oops")
$c =
    coroutine:
        yield 1
        yield 2
$yielded = ($ for $ in (values yielded by $c))
say "\$total \$squares \(("yes") if $caught else "no") \$yielded \(floor 2.5) \({3, 1, 2} sorted)"
]]))
    assert_equal(output(), "20 {1, 4, 9} yes {1, 2} 2 {1, 2, 3}\n")
end)

test("Sandboxed code can't use inline Lua, compile rules, or modules", function()
    local runtime, output = sandbox()
    for _, code in ipairs{
        "lua> \"say_1_inline('escaped')\"",
        "say (=lua \"'escaped'\")",
        "(escape) compiles to \"say_1_inline('escaped')\"\nescape",
        "(escape) parses as (say \"escaped\")\nescape",
        "at compile time:\n    say \"escaped\"",
        "say (nomsu environment)",
        "$tree = \\(1 + 2)",
    } do
        local ok = runtime:run(code)
        assert(not ok, "this worked in a sandbox: "..code)
    end
    assert_equal(output(), "")
end)

test("Sandboxed code can't reach Lua's libraries or Nomsu's internals", function()
    local runtime = sandbox()
    local ok, err = run_lua_in(runtime, [[
        for _, name in ipairs{"io", "os", "package", "require", "load", "loadstring", "loadfile",
            "dofile", "debug", "getfenv", "setfenv", "collectgarbage", "jit", "Files", "lpeg",
            "re", "COMPILE_RULES", "LOADED_MODULES", "MODULE_LOADER", "SOURCES", "new_environment",
            "run", "compile", "compile_file", "_1_parsed", "Module",
            "WRITE_OUTPUT", "READ_INPUT", "LuaCode", "NomsuCode", "SyntaxTree", "Source",
            "LuaCode_from", "NomsuCode_from", "_IMPORTS", "EXIT_SIGNAL"} do
            assert(_ENV[name] == nil, name.." is in the sandbox")
        end
        assert(string.dump == nil, "string.dump is in the sandbox")
    ]])
    assert(ok, err)
end)

test("Nothing reachable in a sandbox leads out of it", function()
    local runtime = capturing_runtime()
    local setup_environment = runtime.environment
    runtime:seal()
    local env = runtime.environment.RUNTIME_ENV
    local forbidden = {
        [runtime.root] = "the root environment", [runtime.environment] = "the compile context",
        [setup_environment] = "the setup environment",
        [runtime.root.LOADED_MODULES] = "the loaded modules", [runtime.root.SOURCES] = "the sources",
        [require("text")] = "the real Text", [string] = "the real string library",
        [math] = "the real math library", [table] = "the real table library",
        [getmetatable("")] = "the string metatable", [getmetatable] = "the real getmetatable",
    }
    for _, mod in pairs(runtime.root.LOADED_MODULES) do forbidden[mod] = "a module's environment" end
    for _, lib in ipairs{io, os, package, debug} do
        forbidden[lib] = "a Lua library"
        for _, v in pairs(lib) do forbidden[v] = "a Lua library function" end
    end
    -- Look at everything sandboxed code can get to by indexing tables and getting metatables
    local safe_getmetatable = env.getmetatable
    local seen = {}
    local function visit(x, path)
        if forbidden[x] then error(path.." is "..forbidden[x], 0) end
        if type(x) ~= "table" or seen[x] then return end
        seen[x] = true
        local mt = safe_getmetatable(x)
        if mt then visit(mt, "getmetatable("..path..")") end
        for k, v in pairs(x) do
            visit(k, path.."[key]")
            visit(v, path.."."..tostring(k))
        end
    end
    visit(env, "_ENV")
    for _, value in ipairs{"", 1, true, runtime.environment.RUNTIME_ENV.say} do
        visit(safe_getmetatable(value), "getmetatable("..type(value)..")")
    end
end)

test("Sandboxed code can't change shared tables", function()
    local runtime = sandbox()
    local other = sandbox()
    local ok, err = run_lua_in(runtime, [[
        string.rep, math.floor, table.insert = nil, nil, nil
        assert(not pcall(function() Text.upper = nil end), "Text could be changed")
        rawset(Text, "as_lua", function() return "evil" end)
        assert(not pcall(setmetatable, Text, {}), "Text's metatable could be changed")
        assert(getmetatable("") == nil, "got the string metatable")
        assert(_1_x27_s_metatable("") == nil, "got the string metatable from ($'s metatable)")
    ]])
    assert(ok, err)
    assert_equal(("ab"):rep(2), "abab")
    assert(math.floor and table.insert and ("x"):upper() == "X")
    assert_equal(("x"):as_lua(), '"x"')
    assert_equal(getmetatable("").__index, require("text"))
    ok, err = run_lua_in(other, [[assert(string.rep and math.floor and table.insert)]])
    assert(ok, "one sandbox changed another's libraries: "..tostring(err))
end)

test("Sandboxed code can't set a __gc finalizer", function()
    -- A __gc finalizer would run later, in the host, outside the sandbox's limits
    local runtime = sandbox()
    -- Directly (the sandbox's setmetatable), and through core's (set $'s metatable to)
    local attempts = {
        "set {} 's metatable to {.__gc = (-> (do nothing))}",
        "$e = {}\nset $e's metatable to {.__gc = (-> (do nothing))}\n$error $e",
    }
    for _, code in ipairs(attempts) do
        local ok, err = runtime:run(code)
        assert(not ok, "a sandbox set a __gc finalizer: "..code)
        assert(tostring(err):match("__gc"), err)
    end
    -- The host can still collect garbage without running any sandbox code
    collectgarbage()
    collectgarbage()
end)

test("(fail) in a sandbox can't show other files", function()
    local path = os.tmpname()
    local f = assert(io.open(path, "w"))
    f:write("SECRET FILE CONTENTS\n")
    f:close()
    local other = capturing_runtime()
    other:run("$x = \"OTHER RUNTIME CODE\"\nfail \"x\"")
    local runtime = sandbox()
    local _, err = run_lua_in(runtime, ("at_1_fail(%q, 'leak')"):format("@"..path.."[1:20]"))
    os.remove(path)
    assert(not tostring(err):match("SECRET"), err)
    for i = 0, 50 do
        _, err = run_lua_in(runtime, ("at_1_fail('@<anonymous file #%d>[1:30]', 'leak')"):format(i))
        assert(not tostring(err):match("OTHER RUNTIME"), err)
    end
end)

test("Sealing again does nothing", function()
    local runtime, output = sandbox()
    assert(runtime:run("public $x = 1"))
    runtime:seal()
    assert(runtime:run("say $x"))
    assert_equal(output(), "1\n")
end)

test("Sandboxes keep what the host provides", function()
    local runtime, output = capturing_runtime{
        environment = {double_it = function(x) return 2 * x end},
        modules = {["game/api"] = api},
    }
    assert(runtime:run("use \"game/api\""))
    runtime:seal()
    assert(runtime:run("greet \"Ann\"\nsay (double it 21)"))
    assert_equal(output(), "Hi Ann\n42\n")
end)

test("Each runtime has its own random numbers", function()
    -- Seeding or drawing numbers in one runtime doesn't change another's
    local a = capturing_runtime()
    local b = capturing_runtime()
    local _, a1 = a:run("seed random with 5\nreturn (random integer 1000000)")
    local _, b1 = b:run("seed random with 5\nreturn (random integer 1000000)")
    a:run("random number\nrandom number")
    local _, b2 = b:run("return (random integer 1000000)")
    local _, a2 = a:run("return (random integer 1000000)")
    assert_equal(a1, b1)   -- same seed, same number
    assert(b2 ~= a2 or b1 ~= a1)
end)

test("A seed makes a runtime's random numbers reproducible", function()
    local function first_three(seed)
        local vm = sandbox()
        local _, list = vm:run("seed random with "..seed..
            "\nreturn ((random integer 1000000) for $ in (1 to 3))")
        return table.concat(list, ",")
    end
    assert_equal(first_three(123), first_three(123))
    assert(first_three(123) ~= first_three(124))
    -- The same on every Lua version
    assert_equal(first_three(123), "532335,203990,987629")
end)

-------------------------------------------------------------------------------------
-- Resource limits

local function assert_ran_out(limit, ok, signal)
    assert(not ok, "the code finished, but it should have run out of "..limit)
    assert(type(signal) == "table" and signal.limit == limit,
        "expected to run out of "..limit..", but got: "..tostring(signal))
end

-- Run Lua code in a sandbox's runtime environment, with the runtime's limits
local function run_limited_lua_in(runtime, code)
    local fn = assert(load(code, "attack", "t", runtime.environment.RUNTIME_ENV))
    return require("nomsu_limits").run_limited(runtime.limits, function() return pcall(fn) end)
end

test("An infinite loop runs out of instructions", function()
    local runtime = sandbox({limits = {instructions = 1e6}})
    assert_ran_out("instructions", runtime:run("repeat:\n    $x = 1"))
end)

test("An error near the instruction limit still reports the real error", function()
    local code = 'sya "hi"'
    local runtime = sandbox()
    local ok, err = runtime:run(code)
    assert_equal(ok, false)
    assert(err:match("Maybe you meant"), err)
    assert(err:match("in main chunk"), err)
    assert(not err:match("try_with_budget"), err)
    -- Once a limit is high enough for the code to run and raise its error, every higher
    -- limit must report that error, however little is left for the error's details
    local reported, without_details = false, false
    for limit = 1000, 150000, 1000 do
        -- LuaJIT's hooks don't run in code that's already compiled
        if jit then jit.flush() end
        runtime.limits = {instructions = limit}
        ok, err = runtime:run(code)
        assert_equal(ok, false)
        if type(err) == "string" then
            reported = true
            assert(err:match("sya"), err)
            without_details = without_details or err:match("attempt to call") ~= nil
        else
            assert(not reported, "Ran out of "..tostring(err.limit).." with a limit of "..limit)
        end
    end
    assert(reported and without_details, "The limits didn't cover the case being tested")
end)

test("A long computation runs out of time", function()
    local runtime = sandbox({limits = {seconds = 0.2}})
    local start = os.clock()
    assert_ran_out("time", runtime:run("repeat:\n    $x = 1"))
    assert(os.clock() - start < 2, "it took too long to stop")
end)

test("Using too much memory runs out of memory", function()
    local runtime = sandbox({limits = {memory = 10 * 1024}})
    -- One call that makes a lot of text
    assert_ran_out("memory", runtime:run("$s = (\"x\", rep 1000000000)"))
    -- Text that doubles in size each time
    assert_ran_out("memory", runtime:run("$s = \"x\"\nrepeat 40 times:\n    $s = \"\\$s\\$s\""))
    -- A table that keeps growing
    assert_ran_out("memory", runtime:run("$t = {}\nrepeat:\n    add \"\\(#$t) item\" to $t"))
end)

test("A catastrophic pattern match is stopped", function()
    local runtime = sandbox({limits = {instructions = 1e6, seconds = 5}})
    local start = os.clock()
    -- This pattern backtracks for a very long time in Lua's C matcher
    assert_ran_out("instructions",
        runtime:run([[return (("a", rep 5000), matching "a-a-a-a-a-a-a-b")]]))
    assert(os.clock() - start < 2, "it took too long to stop")
    -- Ordinary patterns still work
    local ok, matches = runtime:run([[return (all matches of "[^,]+" in "a,b,c,d")]])
    assert(ok, matches)
    assert_equal(#matches, 4)
    local ok2, trimmed = runtime:run([[return ("  hi  ", matching "%s*(%g+)%s*")]])
    assert(ok2 and trimmed == "hi", tostring(trimmed))
end)

test("Every pattern-matching path a sandbox has is guarded", function()
    local runtime = sandbox({limits = {instructions = 1e6, seconds = 5}})
    for _, code in ipairs{
        [[return (all matches of "a-a-a-a-a-a-a-b" in ("a", rep 5000))]],
        [[return (("a", rep 5000), split "a-a-a-a-a-a-a-b")]],
        [[return (("a", rep 5000), with "a-a-a-a-a-a-a-b" -> "")]],
    } do
        assert_ran_out("instructions", runtime:run(code))
    end
    for _, fn in ipairs{"match", "find", "gmatch", "gsub"} do
        local code = ("return string.%s(string.rep('a', 5000), 'a-a-a-a-a-a-a-b', %s)")
            :format(fn, fn == "gsub" and "''" or "nil")
        assert_ran_out("instructions", run_limited_lua_in(runtime, code))
    end
end)

test("Sandboxed code can't change or get around the pattern guard", function()
    local runtime = sandbox({limits = {instructions = 1e6}})
    local ok, kinds = run_limited_lua_in(runtime,
        "return lua_type_of(('').set_pattern_guard)..' '..lua_type_of(('').dump)..' '..lua_type_of(Text.dump)")
    assert(ok, kinds)
    assert_equal(kinds, "nil nil nil")
end)

test("(try) can't catch running out of a limit", function()
    local runtime = sandbox({limits = {instructions = 1e6}})
    assert_ran_out("instructions", runtime:run([[
repeat:
    try:
        repeat:
            $x = 1
    ..if it fails:
        $failed = (yes)
]]))
end)

test("pcall() and coroutines can't get around limits", function()
    local runtime = sandbox({limits = {instructions = 1e6}})
    for _, code in ipairs{
        "while true do pcall(function() while true do end end) end",
        "while true do xpcall(function() while true do end end, function(e) return e end) end",
        "local co = coroutine_from(function() while true do end end)\nresume(co)",
        "coroutine_wrap(function() while true do end end)()",
        "while true do resume(coroutine_from(function() while true do end end)) end",
        "pcall(resume, nil)\nwhile true do end",
    } do
        local ok, err = run_limited_lua_in(runtime, code)
        assert_ran_out("instructions", ok, err)
    end
end)

test("Limits always end with the run, however the code was stopped", function()
    -- The pattern guard stops code outside the instruction hook, so the hook's counter
    -- is at a different point each time. (On LuaJIT, a hook that went off after the
    -- code stopped, but before the run finished, used to leave the limits active.)
    local Limits = require("nomsu_limits")
    local subject = ("a"):rep(5000)
    for n = 1, 2000 do
        local ok, finished, signal = pcall(Limits.run_limited, {instructions = 1e7}, function()
            for _ = 1, n do end
            return subject:matches("a-a-a-a-a-a-a-b")
        end)
        assert(ok and finished == false, "run "..n.." didn't finish: "..tostring(finished))
        assert_ran_out("instructions", finished, signal)
    end
end)

test("Code run without limits doesn't count against them", function()
    local Limits = require("nomsu_limits")
    local runtime = sandbox({
        limits = {instructions = 1e6},
        environment = {
            -- The host's own work, which uses a lot of instructions
            host_work = function()
                return Limits.run_unlimited(function()
                    local x = 0
                    for i = 1, 3e6 do x = x + 1 end
                    -- Limited runs inside it get limits of their own
                    local inner = sandbox({limits = {instructions = 1e6}})
                    local ok, signal = inner:run("repeat:\n    $x = 1")
                    return signal and signal.limit or "finished"
                end)
            end,
        },
    })
    local ok, value = runtime:run("return (host work)")
    assert(ok, value)
    assert_equal(value, "instructions")
    -- The outer run's limits still work afterwards
    assert_ran_out("instructions", runtime:run("host work\nrepeat:\n    $x = 1"))
end)

test("A nested run's limit signal never reaches the code that started it", function()
    local Limits = require("nomsu_limits")
    -- The outer run's hook fires every 1000 instructions, so padding the host code by
    -- each amount up to that makes sure the hook lands at the end of the nested run
    for padding = 0, 1100 do
        local value = Limits.run_limited({instructions = 1e6}, function()
            return Limits.run_unlimited(function()
                for _ = 1, padding do end
                Limits.run_limited({instructions = 5000}, function() while true do end end)
                return "finished"
            end)
        end)
        assert_equal(value, "finished")
    end
end)

test("Limits start over for each run", function()
    local runtime = sandbox({limits = {instructions = 1e6}})
    assert_ran_out("instructions", runtime:run("repeat:\n    $x = 1"))
    local ok, value = runtime:run("return (1 + 1)")
    assert(ok, value)
    assert_equal(value, 2)
end)

test("Limited runs don't change the program running Nomsu", function()
    local runtime = sandbox({limits = {instructions = 1e6, memory = 10 * 1024}})
    assert_ran_out("instructions", runtime:run("repeat:\n    $x = 1"))
    assert(debug.gethook() == nil, "a debug hook was left behind")
    if jit then assert(jit.status(), "the JIT was left off") end
    assert_equal(#("x"):rep(20 * 1024 * 1024), 20 * 1024 * 1024)
end)

test("A sealed runtime's result is a plain copy", function()
    local runtime = sandbox()
    -- A plain-table result is a copy that shares nothing with the sandbox
    local ok, result = runtime:run("public $game = {.scores = {.alice = 1}}\nreturn $game")
    assert(ok, result)
    assert_equal(result.scores.alice, 1)
    result.scores.alice = 999
    local _, again = runtime:run("return $game.scores.alice")
    assert_equal(again, 1)   -- mutating the copy didn't change the sandbox
    -- plain_copy is exposed, and refuses things that aren't plain data
    assert(nomsu.plain_copy({a = {b = 1}}).a.b == 1)
    assert(not pcall(nomsu.plain_copy, function() end))
    assert(not pcall(nomsu.plain_copy, setmetatable({}, {})))
end)

test("A result that isn't plain data is refused", function()
    local runtime = sandbox()
    -- A result with a metatable could run sandboxed code later (via __index, etc.)
    local ok, err = runtime:run([[
(loop) means:
    repeat:
        do nothing
$x = {}
set $x's metatable to {.__index = (-> (loop))}
return $x]])
    assert(not ok)
    assert(tostring(err):match("plain table"), err)
    local ok2, err2 = runtime:run("return (-> 1)")
    assert(not ok2)
    assert(tostring(err2):match("plain data"), err2)
end)

test("An unsealed runtime returns live objects", function()
    local runtime = capturing_runtime()
    local ok, live = runtime:run("$x = {}\nset $x's metatable to {}\nreturn $x")
    assert(ok and type(live) == "table", tostring(live))
end)


-------------------------------------------------------------------------------------
-- (use) after sealing

-- A module with a safe export and a raw dangerous value
local helper_module = [[
#!/usr/bin/env nomsu -V8.0.0
public:
    (add $a and $b) means ($a + $b)
    $raw_io = $io
    $raw_string = $string
]]

local function with_helper()
    local runtime, output = capturing_runtime{
        modules = {helper = helper_module},
    }
    -- Load the module before sealing, without importing its names, so that using it
    -- after sealing is the only way its exports become available
    runtime.root:Module("helper")
    runtime:seal()
    return runtime, output
end

test("A sandbox can use a module that was loaded before it was sealed", function()
    local runtime = with_helper()
    local ok, sum = runtime:run("use \"helper\"\nreturn (add 2 and 3)")
    assert(ok, sum)
    assert_equal(sum, 5)
end)

test("A sandbox can't use a module that wasn't loaded before it was sealed", function()
    local runtime = sandbox()
    local ok, err = runtime:run("use \"filesystem\"")
    assert(not ok)
    assert(tostring(err):match("isn't available"), err)
end)

test("(use) in a sandbox doesn't bring in a raw dangerous value", function()
    local runtime = with_helper()
    -- $raw_io wasn't imported, so it's nil (the raw io library was filtered out)
    local ok, is_nil = runtime:run("use \"helper\"\nreturn ($raw_io == (nil))")
    assert(ok, is_nil)
    assert_equal(is_nil, true)
end)

test("(use) in a sandbox doesn't bring in the shared string library", function()
    local runtime = with_helper()
    -- The real string library is shared by every string's metatable, so changing it would
    -- change string methods outside the sandbox
    local ok, is_nil = runtime:run("use \"helper\"\nreturn ($raw_string == (nil))")
    assert(ok, is_nil)
    assert_equal(is_nil, true)
end)

test("A sandbox's exit code is always a number", function()
    local runtime = sandbox({limits = {instructions = 1e6}})
    local ok, signal = runtime:run(
        "$code = {}\nset $code's metatable to {.__tostring = (-> \"hi\")}\nexit $code")
    assert_equal(ok, false)
    assert_equal(signal.exit, 1)
end)

io.write(("\n%d/%d library tests passed\n"):format(tests - failures, tests))
os.exit(failures == 0 and 0 or 1)