Legion.Sandbox.Elixir (Legion v0.5.0)

View Source

Sandboxed Elixir 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 and resource limits — evaluation runs through Legion.Sandbox.Runner, which kills it on timeout or exceeded memory / CPU budgets.

Examples

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

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

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

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

Summary

Functions

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

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).

limits bound what the evaluating process may take from the node - see Legion.Sandbox.Runner.run/3.

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