Skip to content

Lesson 3 of 9 · 28m

Sandboxing, Capabilities, and Host Boundaries

Build a least-privilege Lua environment using custom globals, controlled libraries, resource limits, allocation policy, and narrow host capabilities.

The dangerous sentence in embedding discussions is “these scripts are internal, so they are trusted.” Internal users make mistakes, copy snippets from the internet, connect the wrong tenant, and occasionally become external attackers after an account compromise. A sandbox is not only about malice. It is about making mistakes boring. Lua gives you enough machinery to design a narrow execution environment, but it does not magically enforce one.

Start with an empty environment

When loading text chunks, provide an explicit environment containing only what the script needs:

local env = {
    assert = assert, error = error, ipairs = ipairs, pairs = pairs,
    pcall = pcall, tonumber = tonumber, tostring = tostring, type = type,
    math = math, table = table, string = string,
}

local chunk, err = load(user_source, "customer_rule", "t", env)
if not chunk then return nil, err end
local ok, result = pcall(chunk)

Notice what is absent: os, io, debug, require, load, dofile, and package. Those are capabilities. If a clock, module loader, or logging facility is required, expose a narrow version intentionally.

Sandboxes are capability systems

A good sandbox is a menu, not a cage. Expose domain verbs implemented by the host:

return {
    now = function() return request.now_unix end,
    tenant_id = function() return request.tenant_id end,
    emit_metric = function(name, value)
        validate_metric(name, value)
        metrics.increment(name, value)
    end,
}

The script cannot open sockets, read files, or enumerate tenants because no such capability exists. Identity and authority are inputs, not global lookup services.

Time and memory are security boundaries

A pure Lua script can still deny service with while true do end. Use instruction-count hooks, host-enforced deadlines, memory ceilings through a custom lua_Alloc, queue isolation, or process containment for hostile plugins. Native host functions need their own timeouts; a Lua hook cannot interrupt code that never yields back to Lua.

Treat the debug library as privileged

debug exposes introspection and mutation powers that undermine naive sandbox assumptions. Do not expose it to ordinary scripts. If you need hooks, install them from the host before running the chunk and keep the API private. Similarly, be careful with load: accepting text mode ("t") avoids loading precompiled bytecode, which is not a safe portability or security boundary.

Validate at the boundary, not inside every script

Scripts receive plain data with documented types. Validate it once at the host boundary. If a rule expects amount_cents to be an integer and currency to be an uppercase three-letter code, enforce that before execution. A sandbox with sloppy input becomes a confusion engine because every script implements its own interpretation of reality.

Sandbox failure is usually leakage

The first leak is often indirect: a whitelisted module returns an object whose methods expose filesystem or network powers; a host callback accepts a table and trusts nested fields; a logging function concatenates secrets into telemetry; a metatable reveals a constructor. Review object graphs, not just top-level globals.

Field notes

  • pcall isolates errors, not infinite loops or memory exhaustion.
  • A custom allocator is one of the few practical ways to cap Lua-managed memory inside a process.
  • Text mode loading avoids bytecode surprises, but text is still hostile input.
  • For multi-tenant untrusted code, prefer separate processes or stronger isolation over clever in-process tricks.

Was this lesson helpful?

Sign in to rate