Legion.Sandbox (Legion v0.4.0)

View Source

Sandboxed code evaluation with AST-level safety checks.

Evaluates Elixir code strings in a spawned process with:

  • AST validation — before evaluation, the code is parsed and walked to reject dangerous forms (defmodule, import, spawn, send, receive, etc.) and calls to modules not in the allow-list.
  • Module allow-list — only built-in safe modules (Kernel, Enum, Map, String, …) and explicitly passed modules may be called. If only some functions from a module should be exposed, wrap them in a dedicated facade module.
  • Timeout — evaluation runs in a monitored process that is killed if it exceeds the deadline.

Examples

iex> {:ok, {4, _}} = Legion.Sandbox.execute("2 + 2", 5_000)

iex> {:ok, {6, _}} = Legion.Sandbox.execute("Enum.sum([1, 2, 3])", 5_000)

iex> {:error, msg} = Legion.Sandbox.execute("System.halt()", 5_000)
iex> msg =~ "Module System is not allowed"
true

iex> {:error, msg} = Legion.Sandbox.execute("import Enum", 5_000)
iex> msg =~ "import is not allowed"
true

Summary

Functions

execute(code_string, timeout_ms, allowed_modules \\ [], bindings \\ [])

Evaluates code_string in a sandboxed process.

timeout_ms controls the maximum execution time (:infinity to disable). allowed_modules are aliased and made available to the evaluated code (on top of the built-in safe modules).

Returns {:ok, {result, new_bindings}} on success, or {:error, reason} on validation failure, runtime exception, crash, or timeout. The returned new_bindings can be passed to subsequent calls to preserve variable scope.