Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Introduction

Every project grows a small crowd of scripts. A hook that runs before each commit. A tool that rebuilds an index. A helper an editor calls every time you save. They start as a few lines of shell, then someone needs JSON and reaches for Python, then someone needs a package and reaches for Node.

Each of those scripts can do anything the person running it can do. It can read your SSH keys, delete your home directory, or call out to the network. Usually none of them do, but nothing stops them, and nothing tells you what each one actually touches.

airsl is a different arrangement. It runs Lua scripts inside a Rust program, and the program decides what each script may reach. A script that wants to read a file has to be given a folder it may read. A script that wants to run git has to be given git. Everything else is refused, and the refusal tells you exactly what was missing.

Two ways to use it

You can use airsl in two ways, and this book covers both.

  As a command                        As a library
  ────────────                        ────────────
  $ airsl run script.lua              let engine = Engine::builder()
                                          .policy(Policy::confined())
  You write Lua. The command line         .build()?;
  says what the script may touch.
                                      You write Rust. Your program decides
                                      what the scripts it runs may touch.

The command is the quickest way in, and it is how most of the early chapters work. The library is for when you are building a program that runs other people's scripts: plugins, extensions, user configuration. The same rules apply in both, because the command is built on the library.

Who this book is for

You are an engineer. You have written scripts before, and you may have written Rust. You do not need to know Lua. Lua is small, and this book explains what it uses as it goes.

If you only want to run scripts, chapters 1 to 5 are enough. If you want to embed airsl in your own program, read on into chapters 6 to 8. Chapter 9 is for the curious: how it is built, and why.

How this book is organised

ChapterWhat you will do
1. Getting StartedInstall airsl and run your first script
2. A First ProjectBuild a small tool, hit the sandbox, and test it
3. Asking PermissionGrant files, environment variables and programs
4. When Scripts MisbehaveStop runaway scripts and fail safely
5. The ToolboxTour the modules every script can use
6. Embedding airsl in RustRun scripts from your own program
7. Writing Your Own ModuleGive scripts a new capability
8. ExtensionsLoad third-party code with a negotiated set of permissions
9. Under the HoodHow airsl is built, and what it can and cannot promise

Every chapter has its own small example, so you can start wherever you like. The appendix collects the reference material: every command-line flag, every module function, and the three presets side by side.

Getting Started

In this chapter you will install the airsl command, run a first script, ask airsl what a script is allowed to do, and set up your editor to complete airsl scripts. The question about what a script is allowed to do is the important one. By the end of the chapter you will have seen the whole idea behind airsl in three lines of output.

Installation

airsl ships as a single prebuilt binary for macOS, Linux and Windows. You do not need Rust, Lua or a C compiler to run it.

macOS and Linux

$ curl -LsSf https://airsstack.github.io/airsl/install.sh | sh

Windows

powershell -ExecutionPolicy Bypass -c "irm https://airsstack.github.io/airsl/install.ps1 | iex"

The installer puts airsl in ~/.local/bin (%USERPROFILE%\.local\bin on Windows) and adds that folder to your PATH. Open a new terminal so the change takes effect, then check it worked:

$ airsl --version
airsl <version>

If you would rather the installer left your PATH alone, set AIRSL_CLI_NO_MODIFY_PATH=1 before running it.

These commands always install the newest release. To install a particular one instead, name it in AIRSL_VERSION:

$ curl -LsSf https://airsstack.github.io/airsl/install.sh | AIRSL_VERSION=<version> sh

Building from source

If you already have a Rust toolchain, you can build airsl yourself:

$ cargo install --locked airsl-cli

This needs a C compiler, because airsl compiles Lua itself from its C source and links it into the binary. That is also why the prebuilt binary needs nothing else installed: Lua is already inside it.

Running scripts outside airsl

To use require("airsstack") in stock Lua 5.4, LuaJIT or Neovim, install the native module with LuaRocks. Running Scripts in Stock Lua shows how.

Other ways to install

Each release also carries a plain archive for every platform, a checksum for each archive, and a signed record of which build produced it. The installation appendix covers downloading by hand, choosing between the Linux builds, and verifying what you downloaded.

Hello, airsl

Make a new folder for the examples in this chapter, and save this as greet.lua:

-- greet.lua
local who = arg[1] or "world"
print("hello, " .. who)

Run it:

$ airsl run greet.lua
hello, world

$ airsl run greet.lua airsl
hello, airsl

If you have not written Lua before, three things in this script are worth knowing:

  • -- starts a comment.
  • local declares a variable. Without it, a variable is global.
  • .. joins two strings.

arg is how a script reads its command-line arguments. arg[1] is the first argument after the script's name, the same as $1 in a shell script. Lua counts from 1, not 0. When no argument is given, arg[1] is nil, and nil or "world" gives "world".

Everything after the script's path is passed to the script untouched, even arguments that start with -:

$ airsl run greet.lua --loud
hello, --loud

So far this looks like any other script runner. The next page shows where it is different.

The output in this book was recorded on Linux, in a folder under /home/you. On your machine the paths in messages will name your own folders. On macOS, some system paths appear under their real location: /tmp shows as /private/tmp, and /etc as /private/etc.

What Does a Script Get?

Before airsl runs a script, it decides what that script may do. You can ask it what that decision is:

$ airsl doctor
airsl <version>
  lua:          Lua 5.4
  language:     restricted
  root table:   airsstack
  grants:       access stdin,stdout,stderr,clock,cwd,require,zones
  memory:       67108864 bytes
  instructions: 100000000 instructions
  modules:      json, path, fs, env, proc, regex, hash, time, glob, stdio, hook, ext

Read the last four lines. They are the whole idea behind airsl.

  grants:        access stdin,stdout,…  ← may use its standard streams, the clock and the like,
                                           but no folders, variables or programs
  memory:        64 MiB                 ← may use this much memory
  instructions:  100 million            ← may run this long
  modules:       json, path, fs, …      ← has these tools available

A script gets a full set of tools, but no permission to use the ones that reach files, variables or programs. It can parse JSON, match regular expressions and build file paths, because none of that touches anything. It can write to its standard streams and read the clock. But it cannot read a file, see an environment variable, or run a program until you say it may.

It also gets two limits. If a script uses more than 64 MiB of memory, or runs more than a hundred million instructions, airsl stops it. A script with a bug that loops forever cannot hang your terminal.

Three presets

What doctor just showed is the default preset, called confined. There are two others:

$ airsl doctor --policy trusted
airsl <version>
  lua:          Lua 5.4
  language:     full
  root table:   airsstack
  grants:       unrestricted
  memory:       unlimited
  instructions: unlimited
  modules:      json, path, fs, env, proc, regex, hash, time, glob, stdio, hook, ext
PresetMeant forPermissionsLimits
trustedscripts you wrote and fully trusteverythingnone
confined (default)everyday scriptshost access, plus whatever else you grant64 MiB, 100M instructions
purecalculations with no I/O at allonly what you grant16 MiB, 10M instructions

You will meet all three properly in chapter 3. For now, the default is the one to get used to.

Grants on the command line

doctor takes the same preset and grant flags as run, so it shows exactly what run would build from them. Ask about pure and it reports no grants at all:

$ airsl doctor --policy pure
airsl <version>
  lua:          Lua 5.4
  language:     minimal
  root table:   airsstack
  grants:       none
  memory:       16777216 bytes
  instructions: 10000000 instructions
  modules:      json, path, fs, env, proc, regex, hash, time, glob, stdio, hook, ext

Add --allow-access to give a pure script one kind of host access, here the standard error stream:

$ airsl doctor --policy pure --allow-access stderr
airsl <version>
  lua:          Lua 5.4
  language:     minimal
  root table:   airsstack
  grants:       access stderr
  memory:       16777216 bytes
  instructions: 10000000 instructions
  modules:      json, path, fs, env, proc, regex, hash, time, glob, stdio, hook, ext

Nothing Is Allowed by Default lists the kinds of host access, and the command-line reference lists every flag.

Summary

  • airsl run script.lua runs a script, and arg[1] reads its first argument.
  • airsl doctor shows what a script would be allowed to do.
  • airsl doctor --policy pure --allow-access stderr shows the policy for the flags you give it, without running anything.
  • By default, a script has tools but no permission to reach files, variables or programs, and it has limits on memory and running time.

In A First Project you will write a script that needs a permission, watch it get refused, and then grant it. First, Editor Support sets up your editor to complete airsstack calls.

Editor Support

Your editor can complete airsstack.json.encode and warn you when you misspell it. It needs a description of what airsl provides, and airsl writes that description for you. This page uses the Lua language server, the engine behind the Lua support in VS Code, Neovim, Zed and others.

Make a folder with a script in it. Save this as hello.lua:

local text = airsstack.json.encode({ name = "airsl" })
print(text)

The script runs fine with airsl run hello.lua, but the language server has never heard of airsstack. This is what its checker says:

$ lua-language-server --check . --checklevel=Information
Initializing ...
hello.lua:1:14 [Warning] Undefined global `airsstack`. (undefined-global)
    local text = airsstack.json.encode({ name = "airsl" })
                 ^^^^^^^^^
>>>>>>>>>>>>>>>>>>>> 1/1 [Found 1 problems in 1 files]
Diagnosis complete, 1 problems found

Setting a project up

Run this in the project's folder:

$ airsl lua setup
created .airsl/types/airsstack.lua
created .luarc.json

To set up another folder, give its path: airsl lua setup path/to/project.

Check the script again:

$ lua-language-server --check . --checklevel=Information
Initializing ...
>>>>>>>>>>>>>>>>>>>> 2/2
Diagnosis completed, no problems found

The warning is gone, and your editor now completes every airsstack module and checks each call. A misspelled function is reported. Save a copy of the script as typo.lua with encode spelled encod, and the checker answers:

$ lua-language-server --check . --checklevel=Information
Initializing ...
typo.lua:1:29 [Warning] Undefined field `encod`. (undefined-field)
    local text = airsstack.json.encod({ name = "airsl" })
                                ^^^^^
>>>>>>>>>>>>>>>>>>>> 3/3 [Found 1 problems in 1 files]
Diagnosis complete, 1 problems found

A script can also take the modules from require("airsstack"), which returns the same table as the global. The language server follows it the same way. Change typo.lua to this, and it reports the misspelled field on the local:

local airsstack = require("airsstack")
local text = airsstack.json.encod({ name = "airsl" })
print(text)
$ lua-language-server --check . --checklevel=Information
Initializing ...
typo.lua:2:29 [Warning] Undefined field `encod`. (undefined-field)
    local text = airsstack.json.encod({ name = "airsl" })
                                ^^^^^
>>>>>>>>>>>>>>>>>>>> 3/3 [Found 1 problems in 1 files]
Diagnosis complete, 1 problems found

Completion works from the same type. For the form itself, see Requiring the modules by name.

Scripts that run outside airsl

The same description fits a script that runs in stock Lua with the native module. Two things in it hold only inside airsl. The global airsstack exists only there, so code meant for stock Lua should take the table with local airsstack = require("airsstack"), even though the editor accepts the bare global. And ext exists only there too, so the editor completes it where a script run in stock Lua has none. Running Scripts in Stock Lua covers the module.

What it writes

Setup writes two things:

  • .airsl/types/airsstack.lua, a file that describes every built-in module. It holds only descriptions, and nothing in it runs.
  • An entry in .luarc.json, the language server's settings file: .airsl/types is added to workspace.library. That entry is how the server finds the description.

If the project has no .luarc.json but has a .luarc.jsonc, setup edits that one instead.

Settings you already have are kept. Here is a .luarc.json that holds two settings of its own, after setup:

{
  "diagnostics.globals": [
    "vim"
  ],
  "runtime.version": "Lua 5.4",
  "workspace.library": [
    ".airsl/types"
  ]
}

When setup has to change the file, it writes the whole file again with its keys sorted. Your settings stay, but the file's own layout does not. A file that already has the entry is not touched.

Setup only edits a file of plain JSON. If yours has comments, setup refuses, writes nothing, and says what to do:

$ airsl lua setup
airsl: will not edit `./.luarc.json`: it is not plain JSON (key must be a string at line 2 column 3); add ".airsl/types" to `workspace.library` by hand

Add the entry yourself, to the workspace.library list, and the language server will find the file.

Running it again

It is safe to run setup as often as you like. When nothing needs to change, it says so:

$ airsl lua setup
unchanged .airsl/types/airsstack.lua
unchanged .luarc.json

Run it again after you upgrade airsl. The description comes from the version you have installed, and a new version may add functions. Setup rewrites only what is out of date:

$ airsl lua setup
updated .airsl/types/airsstack.lua
unchanged .luarc.json

Should .airsl/ be committed?

You can put .airsl/ in .gitignore. It is generated, and anyone can recreate it with airsl lua setup. The .luarc.json entry is the part that matters. It is what lets the language server find the description, so commit that file, and teammates only need to run setup once.

Summary

  • airsl lua setup writes a description of the built-in modules and tells the language server where it is.
  • Your existing settings are kept. A file with comments is refused, and you add the entry yourself.
  • Run it again after upgrading airsl.
  • The description declares ext, which only airsl provides. For running scripts in stock Lua, see Running Scripts in Stock Lua.
  • To describe a module of your own, see Writing Your Own Module.

Running Scripts in Stock Lua

airsl is not the only place an airsstack script can run. The same modules are also a native module for the Lua you already have: Lua 5.4 or LuaJIT, which includes the Lua inside Neovim. You install it with LuaRocks, and then require("airsstack") works in that Lua.

Use it when you want json, fs, regex and the rest in a script, a test, or a plugin that runs outside airsl. The scripts in this chapter, and a few more, are in the examples folder of the repository, each with the output it prints.

What the module is

In stock Lua, require("airsstack") returns a table with every airsl module except ext: json, path, fs, env, proc, regex, hash, time, glob, stdio and hook. ext only exists inside airsl, which is the program that fires extension events.

It sets no global, so keep the table in a local. Save this as hello.lua:

-- The smallest use of the native module: load it, look at what came back, use three modules.
--
-- `require("airsstack")` returns one table and sets no global, so a script keeps it in a local.
-- Everything is printed with `print`, never mixed with `airsstack.stdio.write`: under LuaJIT the
-- two are separate buffers, and a run piped into a file could reorder their lines.

local airsstack = require("airsstack")

-- `pairs` walks a table in an order that differs between runs, so the names are sorted before
-- they are printed.
local names = {}
for name in pairs(airsstack) do
  names[#names + 1] = name
end
table.sort(names)
print("modules: " .. table.concat(names, ", "))

-- `ext` exists only inside the `airsl` program, which is what fires extension events.
print("ext: " .. tostring(airsstack.ext))

-- The module is reachable through `require` and nothing else.
print("global airsstack: " .. tostring(rawget(_G, "airsstack")))
print("package.loaded holds the same table: " .. tostring(package.loaded.airsstack == airsstack))
print("a second require returns it again: " .. tostring(require("airsstack") == airsstack))

-- `{ 1, 2.5 }` has no integer-or-float question to answer, so both Lua versions print the same
-- line. The examples under `lua54/` and `luajit/` are about the numbers that do differ.
print(airsstack.json.encode({ name = "airsl", numbers = { 1, 2.5 } }))
print(airsstack.path.join("src", "main.lua"))
print(airsstack.hash.sha256("abc"))

Once the module is installed, as the next sections show, Lua 5.4 and LuaJIT print the same lines:

$ lua5.4 hello.lua
modules: env, fs, glob, hash, hook, json, path, proc, regex, stdio, time
ext: nil
global airsstack: nil
package.loaded holds the same table: true
a second require returns it again: true
{"name":"airsl","numbers":[1,2.5]}
src/main.lua
ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad

It runs with the same authority as the Lua that loaded it. There are no grants to give, and no memory or instruction ceiling. Stock Lua has no sandbox for the module to join. If you need limits, run the script with airsl.

The two packages

There is one package for each Lua, and a Lua loads only its own:

LuaPackage
Lua 5.4airsstack
LuaJIT, and Neovimairsstack-luajit

LuaRocks files each package under the Lua it is for: airsstack under 5.4, and airsstack-luajit under 5.1, the version LuaJIT implements. That is why the commands below name the version.

Installing

If you have airsl, it can run LuaRocks for you:

$ airsl lua setup --native
created .airsl/types/airsstack.lua
created .luarc.json
Installing https://luarocks.org/airsstack-0.3.0-1.macosx-aarch64.rock

airsstack 0.3.0-1 depends on lua 5.4 (5.4-1 provided by VM: success)
No existing manifest. Attempting to rebuild...
airsstack 0.3.0-1 is now installed in ~/.luarocks (license: Apache-2.0)

require("airsstack") works once you run: eval "$(luarocks path)"
$ airsl lua setup --native --lua luajit
unchanged .airsl/types/airsstack.lua
unchanged .luarc.json
Installing https://luarocks.org/airsstack-luajit-0.3.0-1.macosx-aarch64.rock

airsstack-luajit 0.3.0-1 depends on lua 5.1 (5.1-1 provided by VM: success)
airsstack-luajit 0.3.0-1 depends on luajit >= 2.1 (2.1.1770848219-1 provided by VM: success)
No existing manifest. Attempting to rebuild...
airsstack-luajit 0.3.0-1 is now installed in ~/.luarocks (license: Apache-2.0)

require("airsstack") works once you run: eval "$(luarocks --lua-version 5.1 path)"

The first two lines are the editor files, then LuaRocks prints its own install output, and the last line is airsl's hint for luarocks path. Both commands ran in the same folder, so the second one finds the editor files already written and reports them as unchanged. The transcripts in this chapter show your home folder as ~, where LuaRocks prints the full path. They are from macOS on Apple Silicon, so the package file name ends in macosx-aarch64; yours names your platform. The command asks LuaRocks which Lua it targets and installs the matching package into your own tree, which needs no administrator rights. Name the Lua with --lua 5.4 or --lua luajit to choose one. It installs the package version that matches your airsl, so run it again after you upgrade airsl.

The command also writes the editor files that Editor Support describes, into the current folder or into DIR if you give one, and it writes them even if the install then fails. If you only want the module, use LuaRocks directly.

Without airsl, ask LuaRocks directly. --lua-version names the Lua the package is for, and airsstack-luajit is only listed for 5.1, so the second line fails without it unless LuaRocks already targets 5.1:

$ luarocks --lua-version 5.4 install --local airsstack
Installing https://luarocks.org/airsstack-0.3.0-1.macosx-aarch64.rock

airsstack 0.3.0-1 depends on lua 5.4 (5.4-1 provided by VM: success)
No existing manifest. Attempting to rebuild...
airsstack 0.3.0-1 is now installed in ~/.luarocks (license: Apache-2.0)

$ luarocks --lua-version 5.1 install --local airsstack-luajit
Installing https://luarocks.org/airsstack-luajit-0.3.0-1.macosx-aarch64.rock

airsstack-luajit 0.3.0-1 depends on lua 5.1 (5.1-1 provided by VM: success)
airsstack-luajit 0.3.0-1 depends on luajit >= 2.1 (2.1.1770848219-1 provided by VM: success)
No existing manifest. Attempting to rebuild...
airsstack-luajit 0.3.0-1 is now installed in ~/.luarocks (license: Apache-2.0)

A --local install is outside the folders Lua searches. Tell your shell where it is. On macOS and Linux:

$ eval "$(luarocks --lua-version 5.4 path)"   # Lua 5.4
$ eval "$(luarocks --lua-version 5.1 path)"   # LuaJIT

On Windows, in cmd:

> luarocks path > lrpath.bat
> call lrpath.bat

In PowerShell:

> $env:LUA_PATH = luarocks path --lr-path
> $env:LUA_CPATH = luarocks path --lr-cpath

These set the paths for the current terminal only. For LuaJIT, give luarocks the version it installed for, as in the Unix lines above: luarocks --lua-version 5.1 path.

Where a binary package is published, LuaRocks installs it without compiling anything. That covers macOS on Apple Silicon and Intel, Windows on x64, and Linux with glibc 2.17 or newer on x86_64 and aarch64. See No binary package for everything else, and If require fails if the module does not load.

Building from the repository

You can also build a package from a clone. A build, from a clone or from LuaRocks' own recipe, needs:

  • git,
  • Rust 1.94 or newer, with cargo. If you use rustup, you need do nothing: the repository names Rust 1.94 in its rust-toolchain.toml, and rustup fetches it for the build,
  • a C compiler,
  • the Lua headers for the Lua you target, and
  • LuaRocks. It fetches the build tool of the package, luarocks-build-rust-mlua, by itself, as the output below shows. The exception is a LuaRocks that runs on Lua 5.1, such as the one on Ubuntu: see Ubuntu with apt.

Run LuaRocks from the clone, and give it a tree to install into. This builds the Lua 5.4 package:

$ git clone https://github.com/airsstack/airsl
$ cd airsl
$ luarocks --lua-version 5.4 make --tree lua54-tree crates/airsl-lua/rockspecs/airsstack-[0-9]*-1.rockspec
Missing dependencies for airsstack 0.3.0-1:
   luarocks-build-rust-mlua 0.2.7 (not installed)

airsstack 0.3.0-1 depends on luarocks-build-rust-mlua 0.2.7 (not installed)
Installing https://luarocks.org/luarocks-build-rust-mlua-0.2.7-1.src.rock


No existing manifest. Attempting to rebuild...
   Compiling airsl-lua v0.3.0 (~/airsl/crates/airsl-lua)
   Compiling airsl v0.3.0 (~/airsl/crates/airsl)
    Finished `release` profile [optimized] target(s) in 16.30s
luarocks-build-rust-mlua 0.2.7-1 is now installed in ~/airsl/lua54-tree (license: MIT)


airsstack 0.3.0-1 depends on lua 5.4 (5.4-1 provided by VM: success)
airsstack 0.3.0-1 is now installed in ~/airsl/lua54-tree (license: Apache-2.0)

The first lines are LuaRocks fetching the build tool for the package. This run had Rust's build cache warm, so it shows two Compiling lines, one for airsl-lua and one for airsl. The first build in a fresh clone prints many more, one for each crate it compiles, and takes longer. Now point your shell at the tree and run the hello-require example from the clone:

$ eval "$(luarocks --lua-version 5.4 --tree lua54-tree path)"
$ lua5.4 crates/airsl-lua/examples/common/hello-require/main.lua
modules: env, fs, glob, hash, hook, json, path, proc, regex, stdio, time
ext: nil
global airsstack: nil
package.loaded holds the same table: true
a second require returns it again: true
{"name":"airsl","numbers":[1,2.5]}
src/main.lua
ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad

For LuaJIT, use the LuaJIT rockspec and tell LuaRocks to build for Lua 5.1, the version LuaJIT implements:

$ luarocks --lua-version 5.1 make --tree luajit-tree crates/airsl-lua/rockspecs/airsstack-luajit-[0-9]*-1.rockspec
Missing dependencies for airsstack-luajit 0.3.0-1:
   luarocks-build-rust-mlua 0.2.7 (not installed)

airsstack-luajit 0.3.0-1 depends on luarocks-build-rust-mlua 0.2.7 (not installed)
Installing https://luarocks.org/luarocks-build-rust-mlua-0.2.7-1.src.rock


No existing manifest. Attempting to rebuild...
   Compiling airsl-lua v0.3.0 (~/airsl/crates/airsl-lua)
   Compiling airsl v0.3.0 (~/airsl/crates/airsl)
    Finished `release` profile [optimized] target(s) in 17.45s
luarocks-build-rust-mlua 0.2.7-1 is now installed in ~/airsl/luajit-tree (license: MIT)


airsstack-luajit 0.3.0-1 depends on lua 5.1 (5.1-1 provided by VM: success)
airsstack-luajit 0.3.0-1 depends on luajit >= 2.1 (2.1.1770848219-1 provided by VM: success)
No existing manifest. Attempting to rebuild...
airsstack-luajit 0.3.0-1 is now installed in ~/airsl/luajit-tree (license: Apache-2.0)

Missing dependencies for airsstack-luajit 0.3.0-1:
   lua 5.1 (not installed)
   luajit >= 2.1 (not installed)

Then point your shell at that tree and run the same example:

$ eval "$(luarocks --lua-version 5.1 --tree luajit-tree path)"
$ luajit crates/airsl-lua/examples/common/hello-require/main.lua
modules: env, fs, glob, hash, hook, json, path, proc, regex, stdio, time
ext: nil
global airsstack: nil
package.loaded holds the same table: true
a second require returns it again: true
{"name":"airsl","numbers":[1,2.5]}
src/main.lua
ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad

The Missing dependencies list at the end is a LuaRocks quirk on the first build into a tree. You can ignore it: the line before it says the package is installed, and it is.

How it differs from airsl

A script that runs in airsl can behave a little differently in stock Lua. Save this as differences.lua:

local airsstack = require("airsstack")

print(airsstack.json.encode({ 2.0, 2 ^ 53 }))
print(utf8 ~= nil)

airsstack.env.set("GREETING", "hello")
print(airsstack.env.get("GREETING"))
print(os.getenv("GREETING"))
print(airsstack.proc.run({ arg[-1], "-e", "io.write(os.getenv('GREETING'))" }).stdout)

In Lua 5.4:

$ lua5.4 differences.lua
[2.0,9007199254740992.0]
true
hello
nil
hello

In LuaJIT:

$ luajit differences.lua
[2,9007199254740992]
false
hello
nil
hello
  • JSON of a whole-number float. Lua 5.4 tells 2 from 2.0, so 2.0 stays 2.0. LuaJIT has one kind of number, so it writes 2, and 2^53 as 9007199254740992. airsl runs Lua 5.4, so it writes the first form. The examples integers-and-json and numbers-and-json show this on its own for each Lua.

  • No utf8 in LuaJIT. The utf8 library is part of Lua 5.3 and later.

  • No limits. There is no memory or instruction ceiling, as described above.

  • env.set and os.getenv. env.set changes what env.get and the programs proc.run starts see. Lua's own os.getenv does not see it, as the nil shows. The script starts the Lua that runs it, arg[-1], so it needs no shell.

  • Output order in LuaJIT. When standard output goes to a file or a pipe, text from stdio.write and hook can come out before print lines that ran earlier. Lua 5.4 keeps the order. Save this as order.lua:

    local airsstack = require("airsstack")
    
    print("one")
    airsstack.stdio.write("two\n")
    print("three")
    
    $ lua5.4 order.lua > out.txt; cat out.txt
    one
    two
    three
    $ luajit order.lua > out.txt; cat out.txt
    two
    one
    three
    

    Write everything through one of the two, print or stdio.write, if the order matters.

Pointing LuaRocks at Lua 5.4 or LuaJIT

LuaRocks builds for one Lua at a time, and some systems set it up for another. If luarocks install or airsl lua setup --native reports that LuaRocks installs for a Lua the module does not support, or cannot find the Lua you named, tell LuaRocks where your Lua lives. Two flags do it: --lua-version names the version (5.4, or 5.1 for LuaJIT) and --lua-dir names the folder that holds the Lua's bin and include folders.

airsl lua setup --native takes no --lua-dir, and it takes --lua 5.4 or --lua luajit for the version. To have both work, store the folder in LuaRocks' configuration once, as the next section shows for Homebrew. The config command with lua_dir writes your user configuration for that version, so the flag is no longer needed for it.

Homebrew on macOS

Homebrew's lua formula is Lua 5.5 or newer, and lua@5.4 is keg-only: Homebrew installs it but does not link it onto your PATH. So on a new install LuaRocks targets the newer Lua and does not find Lua 5.4. A Mac whose lua is still a 5.4 that was never upgraded needs no --lua-dir for it, as the transcripts under Installing show. Where LuaRocks does not find the Lua, give it the folder:

$ luarocks --lua-version 5.4 --lua-dir "$(brew --prefix lua@5.4)" install --local airsstack
Installing https://luarocks.org/airsstack-0.3.0-1.macosx-aarch64.rock

airsstack 0.3.0-1 depends on lua 5.4 (5.4-1 provided by VM: success)
No existing manifest. Attempting to rebuild...
airsstack 0.3.0-1 is now installed in ~/.luarocks (license: Apache-2.0)

$ luarocks --lua-version 5.1 --lua-dir "$(brew --prefix luajit)" install --local airsstack-luajit
Installing https://luarocks.org/airsstack-luajit-0.3.0-1.macosx-aarch64.rock

airsstack-luajit 0.3.0-1 depends on lua 5.1 (5.1-1 provided by VM: success)
airsstack-luajit 0.3.0-1 depends on luajit >= 2.1 (2.1.1770848219-1 provided by VM: success)
No existing manifest. Attempting to rebuild...
airsstack-luajit 0.3.0-1 is now installed in ~/.luarocks (license: Apache-2.0)

Give luarocks path the same two flags, and run your script with the interpreter in that folder, because no lua5.4 is on your PATH:

$ eval "$(luarocks --lua-version 5.4 --lua-dir "$(brew --prefix lua@5.4)" path)"
$ "$(brew --prefix lua@5.4)/bin/lua5.4" hello.lua
modules: env, fs, glob, hash, hook, json, path, proc, regex, stdio, time
ext: nil
global airsstack: nil
package.loaded holds the same table: true
a second require returns it again: true
{"name":"airsl","numbers":[1,2.5]}
src/main.lua
ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad

To stop repeating --lua-dir, store the folder once for each Lua:

$ luarocks --lua-version 5.4 config --scope user lua_dir "$(brew --prefix lua@5.4)"
Wrote
	variables.LUA = "/opt/homebrew/opt/lua@5.4/bin/lua5.4"
	variables.LUA_BINDIR = "/opt/homebrew/opt/lua@5.4/bin"
	variables.LUA_DIR = "/opt/homebrew/opt/lua@5.4"
	variables.LUA_INCDIR = "/opt/homebrew/opt/lua@5.4/include/lua5.4"
	variables.LUA_LIBDIR = "/opt/homebrew/opt/lua@5.4/lib"
to
	~/.luarocks/config-5.4.lua
$ luarocks --lua-version 5.1 config --scope user lua_dir "$(brew --prefix luajit)"
Wrote
	variables.LUA = "/opt/homebrew/opt/luajit/bin/luajit"
	variables.LUA_BINDIR = "/opt/homebrew/opt/luajit/bin"
	variables.LUA_DIR = "/opt/homebrew/opt/luajit"
	variables.LUA_INCDIR = "/opt/homebrew/opt/luajit/include/luajit-2.1"
	variables.LUA_LIBDIR = "/opt/homebrew/opt/luajit/lib"
to
	~/.luarocks/config-5.1.lua

LuaRocks lists what it stored. The folders above are the Apple Silicon ones: Homebrew's prefix is /opt/homebrew there and /usr/local on an Intel Mac. Each command makes LuaRocks remember the folder for that version, and also makes that version the one LuaRocks targets when you name none, so the last one you run decides. After that, airsl lua setup --native --lua 5.4 or --lua luajit works without --lua-dir.

Ubuntu with apt

The luarocks package targets Lua 5.1 from the lua5.1 package, not LuaJIT. A Lua 5.1 that is not LuaJIT cannot load airsstack-luajit, and the package needs LuaJIT 2.1, which LuaRocks does not find in that Lua. airsl lua setup --native sees this before it writes anything and refuses:

airsl: `luarocks` found no LuaJIT for Lua 5.1: its Lua 5.1 is not LuaJIT, or it has none, and `airsstack-luajit` needs LuaJIT
       install Lua 5.4 and run again with `--lua 5.4` to install it for Lua 5.4
       or run `luarocks --lua-version 5.1 config --scope user lua_dir <LuaJIT prefix>` to point `luarocks` at LuaJIT
       https://airsstack.github.io/airsl/ch01-05-stock-lua.html#pointing-luarocks-at-lua-54-or-luajit shows how to point `luarocks` at Lua 5.4 or LuaJIT

luarocks install on its own stops in the same place, later, with a LuaRocks error. LuaRocks 3.12 prints:

Error: Could not satisfy dependency luajit >= 2.1: No results matching query were found for Lua 5.1.

So on Ubuntu, name the Lua yourself: airsl lua setup --native --lua 5.4.

For LuaJIT, point LuaRocks at a folder that holds only LuaJIT: a bin/luajit and the LuaJIT headers in include. Pass it as --lua-dir, or store it once with luarocks --lua-version 5.1 config --scope user lua_dir <LuaJIT prefix>, as Homebrew on macOS does. After that, airsl lua setup --native --lua luajit works. For Lua 5.4, --lua-version 5.4 is enough after apt install lua5.4 liblua5.4-dev.

If you build from source, LuaRocks needs the build tool in its own Lua 5.1 tree first:

$ luarocks --lua-version 5.1 install --local luarocks-build-rust-mlua 0.2.7

Windows

Download the LuaRocks zip from the LuaRocks site and use its luarocks.exe. A luarocks.bat wrapper is not enough, because airsl lua setup --native starts luarocks.exe itself. Give it the folder of your Lua build:

> luarocks --lua-version 5.4 --lua-dir C:\lua54 install --local airsstack
> luarocks --lua-version 5.1 --lua-dir C:\luajit install --local airsstack-luajit

Two more things matter on Windows.

  • The packages load the Lua library by its name: lua54.dll for airsstack and lua51.dll for airsstack-luajit. They also need the Visual C++ 2015 or newer runtime. Use a Lua that ships its DLL under that name. A Lua linked statically into its lua.exe has no DLL for the module to find.
  • LuaRocks finds the interpreter through your PATH. Put the bin folder of your Lua on it, which is the folder you gave to --lua-dir plus \bin, before you run luarocks path. Without it, LuaRocks reports for LuaJIT that it could not find Lua 5.1 in PATH.

Neovim

Neovim embeds LuaJIT, so it needs airsstack-luajit. Neovim does not search LuaRocks' folders, so the script asks LuaRocks for them and adds them to package.cpath, but only when require cannot already find the module. This works on every platform, because LuaRocks writes the folders with the right separators and file extension. Save this as nvim-airsstack.lua:

-- Loading the native module inside Neovim, which embeds LuaJIT, so the package is
-- `airsstack-luajit`.
--
-- Neovim does not search LuaRocks' folders, so the script asks LuaRocks where its C modules are
-- and adds them to `package.cpath`. It asks only when `require` cannot already find the module,
-- which is also what lets `LUA_CPATH` point it at a build that was never installed.
--
-- Output goes through `io.write`. Under `nvim -l`, `print` writes to standard error, and
-- `airsstack.stdio.write` is a different buffer from `io.write`, so the script keeps to one
-- channel and its lines stay in order.

if not pcall(require, "airsstack") then
  local cpath = vim.fn.system({ "luarocks", "--lua-version", "5.1", "path", "--lr-cpath" })
  assert(vim.v.shell_error == 0, cpath)
  package.cpath = package.cpath .. ";" .. vim.trim(cpath)
end

local airsstack = require("airsstack")

local function say(line)
  io.write(line, "\n")
end

say(airsstack.json.encode({ editor = "neovim", lua = _VERSION, jit = type(jit) == "table" }))
say("sha256: " .. airsstack.hash.sha256("abc"))
say("path: " .. airsstack.path.join("lua", "plugin", "init.lua"))
say("global airsstack: " .. tostring(rawget(_G, "airsstack")))

luarocks must be on your PATH, as it is when you install the package. On Windows, your Lua's bin folder must be on it too, as Windows says. Run the file with Neovim's -l option, which needs Neovim 0.9 or newer:

$ nvim -l nvim-airsstack.lua
{"editor":"neovim","jit":true,"lua":"Lua 5.1"}
sha256: ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad
path: lua/plugin/init.lua
global airsstack: nil

The script writes with io.write, not print. Under nvim -l, print writes to standard error, so a pipe or a redirect would not capture it, while io.write and airsstack.stdio.write write to standard output. Those two are separate buffers, so pick one of them and keep to it if the order of the lines matters.

Official Neovim builds embed LuaJIT, but some distributions build Neovim with plain Lua 5.1, which cannot load the package. To check yours, run :lua print(jit and jit.version) in Neovim. It prints a LuaJIT version when the package can load, and nil when it cannot.

No binary package

Some platforms have no binary package. Those are musl Linux, such as Alpine, and any platform not listed under Installing, such as 32-bit systems.

The native module is not supported on musl Linux. No package is built for it. LuaRocks there does not tell musl from glibc Linux, so luarocks install installs the glibc package, which cannot load on musl, and the failure shows only when you require the module.

airsl lua setup --native stops you before that. An airsl from a musl archive refuses --native before it writes any file or starts LuaRocks:

airsl: this `airsl` is built for musl Linux, and `airsstack` has no package for musl: the glibc package `luarocks` installs cannot load there
       on a glibc system, install the package with `luarocks` yourself:
       luarocks --lua-version 5.4 install --local airsstack 0.3.0
       luarocks --lua-version 5.1 install --local airsstack-luajit 0.3.0
       https://airsstack.github.io/airsl/ch01-05-stock-lua.html#no-binary-package says what works on musl and where no package exists

The refusal goes by how airsl was built, not by the system it runs on, so a musl airsl on a glibc system is refused too. The archives say when the installer picks that build. There the luarocks lines in the message work.

On any other platform without a binary package, LuaRocks builds the package from its recipe. The requirements are the ones listed under Building from the repository.

If require fails

  • module 'airsstack' not found. Lua is not looking where LuaRocks installed the package. Lua prints the list of places it looked after that line. Run the luarocks path line for your shell from Installing, in the same terminal as the script.
  • An error from the dynamic linker. The package was built for another Lua. Loading airsstack, the Lua 5.4 package, into Neovim on macOS ends with symbol not found in flat namespace '_luaL_tolstring'. Other systems word it differently. Install the package for your Lua, as The two packages shows, and run it with that Lua.
  • A failure on Windows. Check the Lua DLL name and the Visual C++ runtime under Windows.
  • Alpine or another musl Linux. There is no package for it, and airsl lua setup --native refuses to install one, as No binary package says.

Summary

  • require("airsstack") in stock Lua 5.4 or LuaJIT returns the airsl modules except ext, with no global, full authority and no limits.
  • airsstack is for Lua 5.4, airsstack-luajit is for LuaJIT and Neovim.
  • airsl lua setup --native or luarocks install --local installs it, and luarocks path makes your shell find it.
  • LuaJIT writes whole-number floats as integers, has no utf8, and can reorder stdio.write output against print.
  • Where LuaRocks targets the wrong Lua, pass --lua-version and --lua-dir, or store the folder with luarocks config.

A First Project: Counting Headings

In this chapter you will build a small tool that lists the headings in a Markdown file. It is a deliberately ordinary task, because what makes it interesting is not the code. It is the moment the script is refused, and what that refusal tells you.

Along the way you will:

  1. read a file, and get refused
  2. grant the permission the script needs
  3. split the script into a module
  4. test that module without granting anything at all

Make a new folder and save this as notes.md:

# Shopping

milk, eggs

## Hardware

a hammer

Reading the file

Save this as headings.lua:

-- headings.lua
local text = airsstack.fs.read("notes.md")
local found = airsstack.regex.find_all([[(?m)^#+ .+$]], text)

for _, heading in ipairs(found) do
  print(heading)
end

Everything airsl adds to Lua lives under one global table, airsstack. airsstack.fs works with files and airsstack.regex matches regular expressions. The [[...]] is Lua's raw string, so the backslashes and brackets in a pattern need no escaping. ipairs walks a list in order.

Run it:

$ airsl run headings.lua
airsl: lua error in headings.lua: fs.read denied: `notes.md` is outside the granted read roots: none are granted
stack traceback:
	[C]: in field 'read'
	headings.lua:2: in main chunk

The lines after the first are a stack traceback. Read them from the bottom up: line 2 of headings.lua called read. Later examples in this book leave the traceback out to keep the output short.

Why it was refused

The script is not broken. It asked to read a file, and nobody had said it may.

Look closely at the message, because every refusal in airsl has the same shape:

fs.read denied: `notes.md` is outside the granted read roots: none are granted
└──────┬─────┘  └────┬───┘                                    └──────┬──────┘
   what was   what it wanted                                 what it had
   attempted

It tells you the operation, the file, and what the script was allowed to read. Here, nothing. When no folder was granted at all, the file is shown as the script wrote it. When some folder was granted, it is shown as a full path, as in the next refusal below.

Notice also what was not refused. The airsstack.regex call would have worked fine. Matching text reaches nothing outside the script, so it needs no permission. The same is true of building paths, encoding JSON and formatting times. Only the tools that reach out into your machine ask first.

Granting what it needs

Give the script permission to read the current folder:

$ airsl run --allow-read . headings.lua
# Shopping
## Hardware

One flag, and anyone reading the command can see exactly what this script may touch. That matters more than it might seem. When this command lives in a hook or a CI job, the permission is written down right next to it, instead of hidden inside the script.

A grant is a place, not a switch. If you grant a different folder, the script is refused again:

$ airsl run --allow-read /tmp headings.lua
airsl: lua error in headings.lua: fs.read denied: `/home/you/notes/notes.md` is outside the granted read roots: /tmp

This time the message lists /tmp, so you can see at once that the grant points at the wrong folder.

Splitting it into a module

The script does two jobs: it reads a file, and it finds headings. Only the first needs permission. Pull the second out into its own file, markdown.lua:

-- markdown.lua
local M = {}

function M.headings(text)
  return airsstack.regex.find_all([[(?m)^#+ .+$]], text)
end

return M

A Lua module is just a file that returns a table. Now headings.lua loads it with require and keeps only the part that does I/O. It also takes the file name as an argument instead of hard-coding it:

-- headings.lua
local markdown = require("markdown")

local text = airsstack.fs.read(arg[1])
for _, heading in ipairs(markdown.headings(text)) do
  print(heading)
end
$ airsl run --allow-read . headings.lua notes.md
# Shopping
## Hardware

require only looks in the script's own folder, and in folders beneath it. A module name cannot contain .. or a path separator, so a script cannot reach for require("../../secrets"). You can still organise modules into subfolders: require("lib.markdown") loads lib/markdown.lua.

require is a permission of its own: the require member of host access. confined, the preset airsl run starts from, holds it, which is why this example needs no flag. Under pure every call except require("airsstack") is refused until --allow-access require gives it back. What granting it reveals about your folders is covered in what airsl promises.

What a module receives

When require loads a module, it hands the module two values in ...: the module's own name and the path of its file. The name is the one the caller wrote, such as lib.toc. The path always uses / as its separator.

A module can use its name to require a sibling, without spelling out the folder again. Try it in a new folder, separate from the project above. It holds three files: toc.lua, lib/toc.lua and lib/markdown.lua, which is a copy of markdown.lua from the previous section. Save this as lib/toc.lua:

-- lib/toc.lua
local name, path = ...
local base = name:match("^(.-)[^.]*$")
local markdown = require(base .. "markdown")

local M = {}

function M.print(text)
  print("-- " .. name .. " (" .. path:match("[^/]*$") .. ")")
  for _, heading in ipairs(markdown.headings(text)) do
    print(heading)
  end
end

return M

name is lib.toc. The pattern keeps everything up to the last dot, so base is lib., and base .. "markdown" is lib.markdown. The second pattern keeps only the file name from path.

Save this as toc.lua:

-- toc.lua
require("lib.toc").print("# Shopping\n## Hardware\n")
$ airsl run toc.lua
-- lib.toc (toc.lua)
# Shopping
## Hardware

Requiring the modules by name

The airsstack global is not the only way to reach the modules. require("airsstack") returns the same table, so you can bind it to a local:

-- local_name.lua
local airsstack = require("airsstack")

print(airsstack.json.encode({ ok = true }))
print(airsstack == _G.airsstack)
$ airsl run local_name.lua
{"ok":true}
true

require("airsstack") works under every preset, including pure, where every other require call is refused until the require member is granted. A file named airsstack.lua beside the script is never loaded by that name.

Testing it

Here is the payoff from the split. markdown.headings takes text and returns a list. It reads nothing, so it can be tested without granting anything.

Save this as markdown_test.lua:

-- markdown_test.lua
local markdown = require("markdown")

return {
  finds_every_level = function()
    local found = markdown.headings("# One\ntext\n## Two\n")
    assert(#found == 2, "expected 2 headings, got " .. #found)
  end,

  ignores_a_hash_in_the_middle_of_a_line = function()
    assert(#markdown.headings("this is not a # heading") == 0)
  end,
}

A test file is any file named *_test.lua or test_*.lua. It returns a table of functions, one per test. A test passes if its function returns, and fails if it raises an error, so Lua's own assert is all you need. #found is the length of the list.

$ airsl test .
./markdown_test.lua
  ok    finds_every_level
  ok    ignores_a_hash_in_the_middle_of_a_line

2 passed, 0 failed (1 files)

There is no --allow-read on that command. The tests only exercise the pure part of the code, so they run with no permission at all.

Summary

  • Everything airsl adds lives under the airsstack global table.
  • A script is refused when it reaches for something it was not granted, and the refusal names what it wanted and what it had.
  • --allow-read DIR grants a place, not a general permission.
  • require loads modules from the script's own folder and nowhere else, and needs the require member of host access, which confined holds.
  • require("airsstack") returns the same table as the global, under every preset.
  • Code that does no I/O needs no permission, which makes it easy to test. Keep the I/O at the edges.

The next chapter looks at every kind of permission a script can be given.

Asking Permission

In the last chapter, a script was refused until it was given a folder to read. This chapter covers the permissions a script can be given, and the rules behind them.

Four of them name a place, a variable or a program, and each one has its own flag:

FlagWhat it grantsExample
--allow-read DIRreading files under DIR--allow-read ./docs
--allow-write DIRwriting files under DIR--allow-write ./build
--allow-env NAMEreading and setting the variable NAME--allow-env HOME
--allow-exec PROGRAMrunning the program PROGRAM--allow-exec git

Every flag can be repeated, so a script can be granted several folders, names or programs.

A permission in airsl is called a grant. Each grant names exactly what it covers: a folder, a variable, a program. There is no "may read files" or "may run programs". There is only "may read files here" and "may run this program".

A fifth, smaller kind of permission names no place at all: writing output, reading the clock, using a relative path. It is called host access, and it has its own flag, --allow-access. It is covered under Host access.

Nothing Is Allowed by Default

Under the default preset, a script starts with no permission to touch files, environment variables or programs. This page explains the three rules that follow from that. It then introduces a second, smaller kind of permission, called host access.

The tools are always there

Every module is present, even when the script has no permission to use it. You can always write airsstack.fs.read(...). Whether the call succeeds is a separate question, answered when it runs.

This is on purpose. If airsstack.fs disappeared when a script had no file grant, then if airsstack.fs then would quietly change its meaning, from "does this runtime have files?" to "am I allowed?", and a script that checked it would silently skip work instead of telling you why.

A refusal is an error, never an answer

When a script asks about something it was not granted, it gets an error. It never gets a value that could be mistaken for a fact.

Consider a script checking whether a config file exists:

if airsstack.fs.exists("/etc/myapp.conf") then
  -- ...
end

If exists returned false for a folder the script was not allowed to look in, the script would report "no config file" when the truth was "not allowed to look". Those are very different problems to debug. So exists raises an error instead, and so does every other function that asks about something outside the script's grants.

Refusals can be caught

A refusal is an ordinary Lua error, so pcall catches it like any other. pcall calls a function and returns true plus its result, or false plus the error:

-- check.lua
local ok, err = pcall(airsstack.fs.read, "/etc/hosts")
if not ok then
  local message = tostring(err):match("^[^\n]*")
  print("could not read: " .. message)
end
$ airsl run check.lua
could not read: fs.read denied: `/etc/hosts` is outside the granted read roots: none are granted

The error is an error object rather than a plain string. tostring turns it into text, which includes a stack traceback after the first line, and match("^[^\n]*") keeps only that first line.

A script can use this to fall back gracefully. But usually it is better to let the error stop the script, so that whoever runs it sees exactly what was missing.

Host access

A folder, a variable and a program are permissions you name. Some things a script does have nothing to name: writing its output, reading the clock, resolving a relative path. These are called host access, and there are seven members:

MemberWhat it lets a script do
stdinread standard input
stdoutwrite standard output
stderrwrite standard error
clockread the clock
cwduse a relative path, which resolves against the working folder
requireload other files from the script's own folder with require
zonesparse a time that names a time zone, such as America/New_York

Chapter 5 says which member each function needs.

trusted and confined hold all seven, so nothing in this book so far has been refused for want of one. pure holds none. A pure script that calls airsstack.time.now is refused, and the message names the member it lacks. --allow-access gives members back, one at a time. Repeat the flag for more than one. Here is a script that tries the clock and writes what happened:

-- clock.lua
local ok, err = pcall(airsstack.time.now)
local out = airsstack.stdio
out.write((ok and "the clock works" or tostring(err):match("^[^\n]*")) .. "\n")
$ airsl run --policy pure clock.lua
airsl: lua error in clock.lua: stdio.write denied: `stdout` is not granted — no access is granted
stack traceback:
	[C]: in field 'write'
	clock.lua:4: in main chunk

$ airsl run --policy pure --allow-access stdout clock.lua
time.now denied: `clock` is not granted — the granted access is stdout
$ airsl run --policy pure --allow-access stdout --allow-access clock clock.lua
the clock works

The first run is refused before it can say anything, because the script cannot write without stdout. The message ends with what the script does hold, which here is nothing.

airsl doctor shows the members a policy holds on its grants: line. See Grants on the command line.

--allow-access changes nothing under confined, which already holds every member, and it is ignored under trusted, like every other grant flag.

Host access does not remove parts of Lua itself; those belong to the preset. See Host access does not reach Lua's own functions.

Files

The example on this page is a tiny backup tool. It copies a file from one folder into another, which needs one read grant and one write grant.

-- backup.lua
local from, to = arg[1], arg[2]

local text = airsstack.fs.read(from)
airsstack.fs.write(to, text)
print("copied " .. #text .. " bytes")

Set up two folders and run it:

$ mkdir -p config backups
$ echo "port = 8080" > config/app.toml

$ airsl run --allow-read config --allow-write backups backup.lua config/app.toml backups/app.toml
copied 12 bytes

Reading and writing are separate

A read grant does not let a script write, and a write grant does not let it read. Try writing back into the folder the script may only read:

$ airsl run --allow-read config --allow-write backups backup.lua config/app.toml config/copy.toml
airsl: lua error in backup.lua: fs.write denied: `/home/you/project/config/copy.toml` is outside the granted write roots: /home/you/project/backups

The common shape is a wide read grant and a narrow write grant: read the whole project, write only to its build folder. Keeping the two lists separate is what lets you say that.

It also means a write grant is not readable. If a script writes a file and then wants to read it back, grant the folder both ways:

$ airsl run --allow-read backups --allow-write backups script.lua

A grant covers everything below it

--allow-read config covers config/app.toml, config/env/prod.toml, and anything else beneath config. It does not cover config's parent, or a sibling folder.

Paths are checked after they are fully resolved, so a script cannot sneak out of a granted folder:

  granted:  /home/you/project/config

  config/app.toml                    ✓  inside
  config/../secrets.txt              ✗  ".." leaves the folder
  config/link-to-home/.ssh/id_rsa    ✗  a symlink that points outside is followed, then refused

The check happens inside airsl, in Rust, right before the file is opened. A Lua script never holds an open file. It only ever holds a name, and asks airsl to act on it.

Asking about files counts as reading

Listing a folder, checking whether a file exists, and reading a file's size all need a read grant, because each one tells the script something about the folder. A write grant alone is not enough to list the folder you are writing into.

What fs can do

To…Use
read a whole file, or its linesfs.read, fs.read_lines
write or add to a filefs.write, fs.append
replace a file so no reader ever sees half of itfs.atomic_write
create a file only if nobody else hasfs.create_exclusive
look at a pathfs.exists, fs.is_file, fs.is_dir, fs.stat
list a folder, or walk it recursivelyfs.list, fs.walk
create and removefs.mkdir, fs.remove, fs.remove_dir
copy, move, comparefs.copy, fs.rename, fs.same_content

Chapter 5 shows these in use, and the module appendix lists every function.

Environment Variables

Your shell's environment holds more than it seems: API tokens, cloud credentials, the path to your SSH agent. A script that needs HOME should not see all of that along with it. So environment grants are by name, one variable at a time.

-- whoami.lua
local user = airsstack.env.get("USER")
local home = airsstack.env.get("HOME")
print(user .. " lives in " .. home)
$ airsl run --allow-env USER --allow-env HOME whoami.lua
you lives in /home/you

Denied and unset are different

Asking for a variable that was not granted raises an error:

$ airsl run --allow-env HOME whoami.lua
airsl: lua error in whoami.lua: env.get denied: `USER` is not granted — the allowed names are HOME

Asking for a variable that was granted but is not set returns nil. That difference is what lets a script tell "you did not give me API_URL" apart from "API_URL is not set", which are two very different things to fix.

env.all() returns a table of every granted variable that is set. It never includes variables the script was not granted.

Setting a variable

env.set changes a variable for the rest of the script, and for any program the script runs:

airsstack.env.set("GREETING", "hello")
print(airsstack.env.get("GREETING"))   --> hello

The variable needs a grant, the same as reading it. And the change stays inside airsl. It never changes the environment of the program that started the script. A script should not be able to quietly reconfigure its host.

Running Programs

This example asks git which branch you are on:

-- branch.lua
local result = airsstack.proc.run({"git", "branch", "--show-current"})

if result.status ~= 0 then
  airsstack.stdio.error("git failed: " .. result.stderr)
else
  airsstack.stdio.write("on branch " .. result.stdout)
end
$ airsl run --allow-exec git branch.lua
on branch main

No shell, ever

proc.run takes a list: the program, then each argument as its own string. There is no version that takes a single command string.

That one rule removes a whole family of bugs. When a command is a string, something has to split it into words, and a file name with a space or a quote in it gets split wrong. Worse, a file name like x; rm -rf ~ gets run. With a list, there is nothing to split. Each argument arrives exactly as you wrote it.

A failing program is not an error

run gives back a table with three fields:

FieldHolds
statusthe exit code; 0 means success
stdouteverything the program printed
stderreverything it printed as errors

If git exits with a non-zero status, that is not a Lua error. The script asked what happened, and run tells it. Check status yourself, as the example does.

Running a program the script was not granted is an error, like every other refusal.

The grant matches the name you wrote

--allow-exec git allows {"git", ...}. It does not allow {"/usr/bin/git", ...}, even if that is the same file. The grant is compared with the program name exactly as the script spelled it, so use the bare name, and let airsl find it on PATH the way your shell would.

proc.which("git") returns the full path airsl would run, or nil if it cannot find one.

On Windows, git finds git.exe the same way. One limit: airsl runs .exe programs only, so tools that install as .cmd scripts, such as npm and npx, cannot be run through proc on Windows.

Presets

Grants decide what a script may touch through airsstack. A preset decides everything around that: which parts of Lua itself the script can use, and how much memory and time it may spend. Choose one with --policy.

confined: the default

This is what every example so far has used. The script gets the everyday parts of Lua (string, table, math, utf8, coroutine, and the harmless parts of os such as os.time) plus the airsstack modules. It holds every kind of host access, and no folder, variable or program grants until you add them. It runs under a 64 MiB memory limit and a 100 million instruction limit.

What it does not get are the parts of Lua that reach outside the script without asking:

  • io, which opens files directly
  • os.execute, os.remove, os.getenv and the other os functions that touch the system
  • load, dofile and the other functions that run code from a string or file
  • Lua's own require, which is replaced by the confined one you met in chapter 2

Each of those has an airsstack replacement that asks for a grant first.

trusted: for your own scripts

$ airsl run --policy trusted script.lua

A trusted script gets all of Lua, including io and os, and every airsstack module with no restrictions. There are no limits on memory or time. The grant flags are ignored, because there is nothing left to restrict.

Use it for scripts you wrote yourself and would happily run as a shell script. It is also the easy first step when you move existing scripts onto airsl: run them as trusted to start with, then tighten them to confined one grant at a time.

pure: no I/O at all

$ airsl run --policy pure script.lua

A pure script gets only string, table, math and utf8. It has no os, so it cannot even read the clock, and no print. It holds no host access. Anything that would reach outside the script, such as writing output, is refused until you add it with --allow-access, as Nothing Is Allowed by Default showed. Its limits are tighter: 16 MiB of memory and 10 million instructions.

Two details follow from keeping a script repeatable. math.random gives the same numbers on every fresh run, and math.randomseed() with no seed is refused, because that form reads the clock. math.randomseed(42) with a seed works.

require is there, but it refuses every call except require("airsstack") until you grant the require member. With the member, it loads files from the script's own folder, just as it does under confined. Requiring the modules by name explains the one call that always works.

Use pure to evaluate something that should be a pure calculation, such as a configuration file written in Lua, or an expression a user typed in. What it promises, and the three things it does not control, are in chapter 9.

Side by side

trustedconfinedpure
Lua's io, os.execute, loadyesnono
os.time, os.clockyesyesno
printyesyesno
math.randomdifferent each rundifferent each runthe same each run
math.randomseed() with no seedyesyesrefused
Host accessallallnone
requireLua's ownscript's folder onlyrefuses all but require("airsstack"); with the require member, script's folder only
airsstack modulesunrestrictedonly what is grantedonly what is granted
Memory limitnone64 MiB16 MiB
Instruction limitnone100 million10 million

Summary

  • There are four kinds of grant: read a folder, write a folder, use a variable, run a program. Host access covers the rest, and only pure starts without it.
  • Each grant names exactly what it covers.
  • A refusal is always an error that names what was missing.
  • Presets decide which parts of Lua a script sees, and how much it may spend.

The next chapter looks at those spending limits, and at what happens when a script fails.

When Scripts Misbehave

Grants stop a script from touching what it should not. They do nothing about a script that simply goes wrong: one that loops forever, eats all your memory, or has a typo in it.

This chapter covers the two tools airsl has for that:

  • limits, which stop a script that runs too long or uses too much memory
  • failing open, which keeps a broken script from breaking whatever ran it

Memory and Time Limits

Here is the smallest possible runaway script:

-- forever.lua
while true do end

It touches nothing, so no grant could stop it. Without a limit it would hang your terminal until you killed it. Under airsl it stops on its own:

$ airsl run forever.lua
airsl: script `forever.lua` exceeded its instruction limit of 100000000

Two limits

Every confined script runs under two limits:

LimitDefaultWhat it stops
instructions100 milliona loop that never ends
memory64 MiBa script that keeps allocating

An instruction is one step of the Lua virtual machine. A hundred million is far more than an ordinary script needs. It is a ceiling, not a target.

Change either limit with a flag. Pass a number to set it, or none to remove it. This script keeps growing a table until something stops it:

-- hungry.lua
local t = {}
for i = 1, 1e9 do
  t[i] = ("x"):rep(1024) .. i
end
$ airsl run --instruction-limit 1000000 forever.lua
airsl: script `forever.lua` exceeded its instruction limit of 1000000

$ airsl run --memory-limit 10000000 hungry.lua
airsl: script `hungry.lua` exceeded its memory limit of 10000000 bytes

$ airsl run --memory-limit none big-report.lua

What the limits promise, exactly

The limits are close, not exact. airsl checks the instruction count every ten thousand instructions, so a script may run a little past its limit before it is stopped. That is plenty of precision to catch a runaway loop, and checking more often would slow every script down.

The memory limit covers the whole Lua state. When you run one script per command, that is the same thing as the script. When a Rust program runs many scripts on the same engine (chapter 6), memory left behind by earlier scripts counts until Lua's garbage collector frees it.

A limit is not a bug in the script

When a script hits a limit, airsl reports it differently from an ordinary error. An ordinary error means "the script has a problem". Hitting a limit means "the script was stopped from harming the machine", which you almost always want to know about. The next page shows why that difference matters.

Failing Safely

Scripts often run on behalf of something else: a git hook, an editor, an AI coding agent. Those callers read a script's exit code as a decision. For an agent's PreToolUse hook, for example, a non-zero exit can block the action the hook was watching.

That means a script with a typo in it does not just fail. It blocks whatever it was attached to. If the hook watches every file read, a single syntax error stops the agent from reading any file at all.

--fail-open

--fail-open tells airsl that a failure must not escape:

$ echo 'this is not lua' > broken.lua

$ airsl run broken.lua; echo "exit=$?"
airsl: lua error in broken.lua: syntax error: broken.lua:1: syntax error near 'is'
exit=1

$ airsl run --fail-open broken.lua; echo "exit=$?"
exit=0

With --fail-open, any error is swallowed and airsl exits with 0. A broken hook does nothing, instead of breaking the session it runs in.

It is a command-line flag rather than something you write in the script for a simple reason. A syntax error stops Lua before the script's first line runs, so a setting inside the script would never be read in exactly the case it exists for.

Seeing the error anyway

Silence is right for the caller, but you still need to debug the script. Set AIRSL_DEBUG=1 to print the error while keeping the exit code at 0:

$ AIRSL_DEBUG=1 airsl run --fail-open broken.lua; echo "exit=$?"
airsl: lua error in broken.lua: syntax error: broken.lua:1: syntax error near 'is'
exit=0

Limits are always reported

There is one thing --fail-open does not hide. If a script is stopped for hitting a memory or instruction limit, airsl always prints it:

$ airsl run --fail-open forever.lua; echo "exit=$?"
airsl: script `forever.lua` exceeded its instruction limit of 100000000
exit=0

The exit code is still 0, so the caller is still protected. But a hook that eats memory or loops until it is stopped is a problem with your machine, not a message the script chose to send, and keeping quiet about it would leave you with a slow session and no idea why.

Catch syntax errors before they ship

--fail-open keeps a broken hook harmless, but it also keeps it quiet. A typo can ship and nobody notices that the hook stopped working. airsl check catches that ahead of time. It compiles every .lua file under a folder without running any of them. In a folder holding forever.lua and broken.lua:

$ airsl check .
2 file(s) compiled, 1 failed

./broken.lua
    lua error in ./broken.lua: syntax error: ./broken.lua:1: syntax error near 'is'

Run it in CI next to airsl test. Tests cover the modules your hook uses, but the hook's own entry script is usually not loaded by any test, and check is what covers it.

Summary

  • Every confined script has a memory limit and an instruction limit. Change them with --memory-limit and --instruction-limit, or remove them with none.
  • --fail-open makes any failure exit with 0, for scripts that run on behalf of another program.
  • AIRSL_DEBUG=1 shows the error anyway, and hitting a limit is always shown.
  • airsl check finds syntax errors without running anything.

The Toolbox

Lua is a small language, and its standard library is small too. It has no JSON, no real regular expressions, no way to list a folder, and no way to run a program without going through a shell. Scripts written in plain Lua tend to fill those gaps by calling out to Python or sed, which brings back every problem airsl exists to solve.

So airsl adds twelve modules of its own, all under the airsstack table:

airsstack
├── text          json · regex
├── files         path · fs · glob
├── the system    env · proc
├── utilities     time · hash
└── the outside   stdio · hook · ext

json, regex and ext need nothing at all. The rest ask first, because they reach outside the script: the disk, the environment, other programs, the clock, the current folder, or the standard streams. Some ask for a grant of a place or a name. Others ask for a member of host access, a short list of things a script may use that confined holds and pure does not. Host access is described in chapter 3.

ModuleNeeds a grant?
json, regex, extnever
fsread or write grant, for every function; a relative path also needs cwd
envthe variable's name
procthe program's name
globonly glob.walk, which reads folders; a relative root also needs cwd
hashonly hash.hash_file, which reads a file; a relative path also needs cwd
pathonly path.absolute of a relative path: cwd
timenow and monotonic: clock. parse with a pattern that names a time zone: zones
stdioread, lines: stdin. write: stdout. error: stderr. isatty: the stream it asks about
hookpayload: stdin. emit, context: stdout

This chapter is a tour, one small example per page. For the full list of functions, see the module appendix. env and proc were covered in chapter 3, and ext belongs to chapter 8.

Throughout this chapter, local a = airsstack is used to keep lines short. It is an ordinary Lua variable that refers to the same table.

Text: JSON and Regular Expressions

The example on this page reads a JSON description of a package and checks that its version looks like 1.2.3.

-- version.lua
local a = airsstack

local package = a.json.decode([[{"name": "demo", "version": "1.4.0-beta"}]])

local parts = a.regex.captures([[^(\d+)\.(\d+)\.(\d+)(?:-(?<pre>.+))?$]], package.version)
if not parts then
  error("not a version: " .. package.version)
end

print("major " .. parts[1] .. ", minor " .. parts[2] .. ", patch " .. parts[3])
print("pre-release: " .. (parts.pre or "none"))

print(a.json.encode({ name = package.name, major = tonumber(parts[1]) }))
$ airsl run version.lua
major 1, minor 4, patch 0
pre-release: beta
{"major":1,"name":"demo"}

JSON

json.decode turns JSON text into Lua tables, and json.encode turns them back. json.encode_pretty does the same with indentation, for files people will read.

Object keys always come out sorted. In the output above, major comes before name even though the script wrote them the other way round. That is on purpose. Lua tables have no order of their own, so without sorting the same table could encode differently on every run. With sorting, the same data always produces the same bytes, which is what you want for any file you commit, diff or cache.

Two things in JSON have no exact match in Lua:

  • null cannot be nil, because a key set to nil is the same as a missing key. So decode turns null into a special marker value, and encode turns that marker back into null. Watch out: the marker is not nil, so if value.a then is true when a was null. Compare against a value you decoded from "null" if you need to test for it.
  • An empty list cannot be told apart from an empty object, because both are an empty Lua table. An empty table you build yourself encodes as {}. If you need [], a.json.decode("[]") gives you a table that encodes as one.

Both markers can only come from decoding JSON. There is not yet a way to write them directly in Lua.

Regular expressions

Lua has its own patterns, but they are not regular expressions. They have no | for alternatives, no \b for word boundaries, and no named groups. airsstack.regex gives you real regular expressions instead, with the same syntax as Rust's regex crate.

To…Use
test for a matchregex.is_match(pattern, text)
get the first match, or every matchregex.find, regex.find_all
get the groups of the first matchregex.captures
replace the first match, or every matchregex.replace, regex.replace_all
split text on a patternregex.split

captures returns a table where [1], [2] and so on are the numbered groups, and named groups are also there under their names, like parts.pre above. If the pattern does not match, it returns nil.

In a replacement, $1 and $name refer to groups:

print(a.regex.replace_all([[(\w+)@(\w+)]], "bob@home, amy@work", "$2:$1"))
--> home:bob, work:amy

If you use the same pattern many times, compile it once. The compiled pattern has the same functions, without the pattern argument:

local number = a.regex.compile([[\d+]])
print(#number.find_all("3 apples and 12 pears"))   --> 2

Files and Paths

The example on this page finds every TODO comment in a project's Lua files, and prints where each one is.

-- todos.lua
local a = airsstack
local root = arg[1] or "."

for _, file in ipairs(a.glob.walk(root, "**/*.lua")) do
  local lines = a.fs.read_lines(a.path.join(root, file))
  for number, line in ipairs(lines) do
    local note = a.regex.find([[TODO.*]], line)
    if note then
      print(file .. ":" .. number .. ": " .. note)
    end
  end
end

Point it at a project's src folder:

$ airsl run --allow-read src todos.lua src
lib/parse.lua:12: TODO handle tabs
main.lua:3: TODO read the path from arg

The script lives outside src, which is just as well: run over its own folder, it would also find the TODO in its own pattern.

Three modules, three jobs

  path    builds and takes apart path strings        a relative path needs `cwd`
  glob    matches path patterns                      walk needs a read grant
  fs      reads and writes files                     always needs a grant

They are separate because building a path touches nothing, while opening one does. A script that only works out file names can do that with no permission at all. The one exception is absolute, described below.

path

Every function in path works on strings. None of them looks at the disk.

a.path.join("lib", "parse.lua")          --> lib/parse.lua
a.path.dirname("lib/parse.lua")          --> lib
a.path.basename("lib/parse.lua")         --> parse.lua
a.path.stem("lib/parse.lua")             --> parse
a.path.ext("lib/parse.lua")              --> lua
a.path.ext("Makefile")                   --> (an empty string)
a.path.normalize("lib/./x/../parse.lua") --> lib/parse.lua
a.path.relative_to("/repo/lib/x.lua", "/repo")   --> lib/x.lua

ext returns an empty string, not nil, when there is no extension, so "no extension" is never confused with "something went wrong".

Paths are always written with /, on every platform, including Windows. A script never has to care which way the slashes go.

path.absolute

path.absolute(p) makes a relative path absolute, by putting the folder the script was started in before it. That folder is something the script could not otherwise learn, so a relative path needs the cwd member of host access. A path that is already absolute needs nothing, and comes back unchanged.

confined holds cwd, so under the default preset the call just works. Under pure, a script that calls airsstack.path.absolute("lib/parse.lua") is refused:

$ airsl run --policy pure absolute.lua
airsl: lua error in absolute.lua: path.absolute denied: the relative path `lib/parse.lua` needs `cwd`, which is not granted — no access is granted

--allow-access cwd gives it back.

glob

glob.match(pattern, path) tells you whether a path matches a pattern. glob.walk(root, pattern) finds every file under root that matches, and returns their paths relative to root.

PatternMatches
*.luamain.lua, but not lib/parse.lua: * stops at a /
**/*.luamain.lua and lib/parse.lua: **/ crosses any number of folders, including none
*.{lua,md}main.lua and README.md

fs

Reading:

local text  = a.fs.read("notes.md")          -- the whole file, as a string
local lines = a.fs.read_lines("notes.md")    -- a list of lines, without line endings
local info  = a.fs.stat("notes.md")          -- { kind = "file", size = 42, modified = …, readonly = false }

Writing:

a.fs.write("out.txt", text)      -- replace the file
a.fs.append("log.txt", "line\n") -- add to the end

Lists come back sorted. fs.list, fs.walk and glob.walk always return names in the same order, whatever order the disk happens to store them in. Run the same script twice and you get the same output.

Two functions worth knowing

fs.atomic_write(path, text) replaces a file so that anyone reading it sees either the old contents or the new contents, never half of each. Use it for any file another program might be reading while you write it, such as an index or a cache.

fs.create_exclusive(path, text) creates a file only if it does not exist yet, as one step that nobody can interrupt. It returns true if this call created it, and false if the file was already there. That makes it a way to do something exactly once, even when several copies of a script start at the same moment:

if a.fs.create_exclusive("build/.claimed", "") then
  -- only one copy of the script gets here
end

Checking fs.exists and then writing would not work. Two copies could both check, both see nothing, and both write.

Two rules before any file is touched

fs, glob.walk and hash.hash_file all check the path before they look at the disk, and refuse without revealing anything about it. Two rules apply, in this order.

No roots granted. If nothing is granted for the kind of access the call needs, the call is refused at once, with the path exactly as the script wrote it. Here read-hosts.lua reads /etc/hosts:

$ airsl run --policy pure read-hosts.lua
airsl: lua error in read-hosts.lua: fs.read denied: `/etc/hosts` is outside the granted read roots: none are granted

A relative path needs cwd. A relative path means "from the folder the script was started in". Unless the script holds the cwd member of host access, a relative path is refused even when it would have landed inside a granted folder. Here read-notes.lua reads notes.md:

$ airsl run --policy pure --allow-read /usr read-notes.lua
airsl: lua error in read-notes.lua: fs.read denied: the relative path `notes.md` needs `cwd`, which is not granted — no access is granted

The end of the message lists the host access the script does hold. With --allow-access stderr added it reads the granted access is stderr. Passing --allow-access cwd lets the relative path through to the usual check against /usr.

confined holds cwd, so only the first rule can refuse a script there, as in chapter 2.

Time and Hashing

The example on this page writes a small build stamp: when the build ran, and a short fingerprint of its input.

-- stamp.lua
local a = airsstack

local input = a.fs.read(arg[1])

a.stdio.write(a.json.encode_pretty({
  built_at = a.time.format(a.time.now()),
  input    = a.hash.sha256(input):sub(1, 12),
}))

Run it on the notes.md from chapter 2:

$ airsl run --allow-read . stamp.lua notes.md
{
  "built_at": "2026-10-22T05:47:36Z",
  "input": "709eaf88c4ad"
}

encode_pretty already ends its output with a newline, so the script writes it with stdio.write, which adds nothing, instead of print, which would add a second one.

time

FunctionReturns
time.now()the current time, as whole seconds since 1970
time.format(seconds)that moment as text, like 2026-10-22T05:30:00Z
time.format(seconds, pattern)that moment in your own format, like "%Y-%m-%d"
time.parse(text)text back into seconds; it also takes an optional pattern
time.monotonic()a reading for measuring how long something took

format always needs a moment to format. It never quietly uses "now". That keeps it predictable: the same number always formats to the same text. It also always uses UTC, so the output does not change with the time zone of the machine it runs on.

a.time.format(1700000000)              --> 2023-11-14T22:13:20Z
a.time.format(1700000000, "%Y-%m-%d")  --> 2023-11-14

monotonic is for timing, not for dates. It is not affected when the system clock is changed, but the number on its own means nothing. Subtract one reading from another to get the seconds in between:

local start = a.time.monotonic()
-- ... some work ...
print(("took %.3f seconds"):format(a.time.monotonic() - start))

There is no sleep. A script that could pause for as long as it liked would get around the instruction limit from chapter 4.

Reading the clock needs clock

now and monotonic read the host's clock, so each needs the clock member of host access. format needs nothing: it renders a number it is given and never looks at the clock. confined holds clock. Under pure, a script that calls airsstack.time.now() is refused:

$ airsl run --policy pure now.lua
airsl: lua error in now.lua: time.now denied: `clock` is not granted — no access is granted

monotonic gives the same refusal with time.monotonic in front. --allow-access clock gives both back.

Named zones need zones

time.parse with no pattern, or with a pattern that reads only a numeric offset such as %z, needs nothing. A pattern that names a time zone, such as %Q for America/New_York, makes time.parse read the host's time zone database. That is a second thing a script could learn about the machine, so it needs the zones member:

-- zone.lua
local t = airsstack.time.parse("2024-07-01 12:00 America/New_York", "%Y-%m-%d %H:%M %Q")
airsstack.stdio.write(t .. "\n")
$ airsl run zone.lua
1719849600

$ airsl run --policy pure zone.lua
airsl: lua error in zone.lua: time.parse denied: the named time zone `America/New_York` needs `zones`, which is not granted — no access is granted

Text that does not match the pattern fails with the usual parse error, before zones is consulted. Because the script writes its answer with stdio.write, the second run also needs stdout. --allow-access zones --allow-access stdout makes it print the same number as the first.

hash

FunctionReturns
hash.sha256(text)the SHA-256 of text, as hex
hash.sha1(text)the SHA-1 of text, as hex
hash.hash_file(path)the SHA-256 of a file; needs a read grant
hash.hex(text)the bytes of text, as hex

Use SHA-256 for anything new. SHA-1 is there for compatibility, for when a script has to produce the same names an older tool produced with something like shasum | cut -c1-8.

Standard Streams and Hooks

Under confined, Lua's own io library is gone, because it can open any file. A script still needs its standard input and output, though, and airsstack.stdio provides them. Each stream is a member of host access, so a script uses a stream only if it holds that member. confined holds all three, which is why every example in this chapter runs without a flag.

FunctionDoesNeeds
stdio.read()reads all of standard input, as one stringstdin
stdio.lines()reads all of standard input, as a list of linesstdin
stdio.write(text)writes to standard output, exactly as givenstdout
stdio.error(text)writes to standard error, exactly as givenstderr
stdio.isatty(stream)whether "stdin", "stdout" or "stderr" is a terminalthe stream it names

Under pure, which holds none of them, each call is refused before it reads or writes anything, and the refusal names the member:

$ airsl run --policy pure read.lua
airsl: lua error in read.lua: stdio.read denied: `stdin` is not granted — no access is granted

$ airsl run --policy pure write.lua
airsl: lua error in write.lua: stdio.write denied: `stdout` is not granted — no access is granted

$ airsl run --policy pure error.lua
airsl: lua error in error.lua: stdio.error denied: `stderr` is not granted — no access is granted

--allow-access stdin, --allow-access stdout and --allow-access stderr give them back one at a time. stdio.lines is refused the same way as read, with stdio.lines at the front. isatty is refused for the stream it names, and with no argument that is stdout, so isatty() under pure fails like this:

$ airsl run --policy pure isatty.lua
airsl: lua error in isatty.lua: stdio.isatty denied: `stdout` is not granted — no access is granted

write and error add nothing to what they are given, not even a newline. Lua's print always adds one. When your output is going to be read by another program, every byte counts, so write is the safer choice.

Writing a hook

Many tools let you attach a script that runs when something happens. AI coding agents are a common example: before the agent edits a file, it runs your hook, hands it a JSON description of what it is about to do on standard input, and reads back any JSON the hook prints.

airsstack.hook handles that exchange. This hook adds a reminder whenever the agent is about to touch a Lua file:

-- remind.lua
local a = airsstack

local payload = a.hook.payload()
local file = payload.tool_input and payload.tool_input.file_path

if file and a.path.ext(file) == "lua" then
  a.hook.context("PreToolUse", "Reminder: run `airsl test` after changing Lua files.")
end
$ echo '{"tool_input":{"file_path":"lib/parse.lua"}}' | airsl run remind.lua
{"hookSpecificOutput":{"additionalContext":"Reminder: run `airsl test` after changing Lua files.","hookEventName":"PreToolUse"}}

$ echo '{"tool_input":{"file_path":"README.md"}}' | airsl run remind.lua

The second run prints nothing, and that is correct. A hook with nothing to say says nothing.

FunctionDoesNeeds
hook.payload()reads standard input as JSON; an empty input gives an empty tablestdin
hook.context(event, text)prints the reply that adds text to the agent's contextstdout
hook.emit(value)prints any Lua value as JSON, for replies context does not coverstdout

A hook reads and writes the same streams as stdio, so it needs the same members. Under pure the check comes first, even when standard input is empty:

$ airsl run --policy pure payload.lua
airsl: lua error in payload.lua: hook.payload denied: `stdin` is not granted — no access is granted

$ airsl run --policy pure emit.lua
airsl: lua error in emit.lua: hook.emit denied: `stdout` is not granted — no access is granted

hook.context is refused with the same text as emit, with hook.context in front.

context builds the nested reply shape for you, which is easy to get subtly wrong by hand.

When you attach a hook like this, run it with --fail-open, as described in chapter 4, so that a bug in the hook never blocks the agent.

Calling airsl from a hook

A hook is usually started by a small shell script. This one stays silent if airsl is not installed, instead of failing:

#!/bin/sh
DIR=$(CDPATH= cd -- "$(dirname -- "$0")" 2>/dev/null && pwd) || exit 0
command -v airsl >/dev/null 2>&1 || exit 0
airsl run --fail-open "$DIR/remind.lua" || exit 0
exit 0

Every path through it exits 0. If the hook never seems to run, check that the program running it can find airsl. A hook runner may start a shell that never reads your profile, and so never sees the PATH change the installer made. Writing the full path, "$HOME/.local/bin/airsl", removes the question.

Testing and Checking

You met airsl test in chapter 2. This page covers the rest of what it does, using a small module that formats file sizes.

-- size.lua
local M = {}

function M.human(bytes)
  if bytes < 1024 then
    return bytes .. " B"
  end
  return ("%.1f KiB"):format(bytes / 1024)
end

return M
-- size_test.lua
local size = require("size")

return {
  small_sizes_stay_in_bytes = function()
    assert(size.human(512) == "512 B")
  end,

  larger_sizes_use_kibibytes = function()
    local got = size.human(2048)
    assert(got == "2.0 KiB", "got " .. got)
  end,
}
$ airsl test .
./size_test.lua
  ok    larger_sizes_use_kibibytes
  ok    small_sizes_stay_in_bytes

2 passed, 0 failed (1 files)

How tests are found and run

  • A test file is named *_test.lua or test_*.lua, anywhere under the folder you name.
  • It returns a table. Each function in the table is one test, and its key is the test's name. Tests run in name order, so the output is the same on every run.
  • A test passes by returning, and fails by raising an error. assert(condition, message) raises when condition is false, so it is usually all you need.
  • Each file gets a fresh engine. One test file cannot leave global variables behind that change how the next one behaves.
  • Finding no tests is a failure. If airsl test finds no test files, it exits non-zero. Otherwise a typo in a folder name would look exactly like a passing test suite in CI.

airsl test takes the same --policy and grant flags as airsl run. When your tests need to read fixture files, grant the folder:

$ airsl test --allow-read tests/fixtures tests/

Even better, write tests that need no grants at all. As chapter 2 showed, if you keep the I/O at the edges of a script, the logic in the middle can be tested with no permission.

Checking without running

airsl check compiles every .lua file under a folder, and runs none of them. It finds syntax errors in files your tests never load, such as the entry script of a hook.

$ airsl check .
2 file(s) compiled, 0 failed

A good CI job runs both:

$ airsl check scripts/
$ airsl test scripts/

Summary

  • json and regex handle text, and JSON keys always come out sorted.
  • path builds paths, glob matches them, and fs reads and writes them. Only fs and glob.walk need a grant.
  • time.format always needs a moment and always uses UTC, so output is the same everywhere.
  • stdio replaces Lua's io for the standard streams, and hook handles the agent hook exchange.
  • airsl test runs test files with a fresh engine each, and airsl check catches syntax errors.

That is everything a script can do from the command line. The next chapter moves to Rust, and shows how to run scripts from your own program.

Embedding airsl in Rust

So far you have used airsl as a command. This chapter uses it as a library, from inside your own Rust program.

That is the case airsl was really built for. Imagine a program that lets its users customise it with scripts: a build tool with user-written rules, a server with user-written handlers, an editor with user-written commands. Your program runs code you did not write, so it needs to decide what that code may reach. Everything you have seen from the command line, every grant and every limit, is available from Rust, because the airsl command is itself a small program built on this library.

Add it to your project:

$ cargo add airsl

Building it needs a C compiler, because airsl compiles Lua from its C source and links it into your program. There is no system Lua to install, and nothing to configure.

Your First Engine

An engine is a Lua interpreter together with its rules. You build one, then hand it scripts to run.

use airsl::{Engine, Policy, Script};

fn main() -> Result<(), airsl::Error> {
    let engine = Engine::builder().policy(Policy::confined()).build()?;

    let script = Script::from_source("return 6 * 7", "answer")?;
    let answer: i64 = engine.eval_to(&script)?;

    println!("the answer is {answer}");
    Ok(())
}
$ cargo run
the answer is 42

You cannot forget the policy

Look at the builder again: Engine::builder().policy(...).build(). The policy call is not optional. If you leave it out, there is no build method to call, and the program does not compile.

let engine = Engine::builder().build()?;
// error[E0599]: no method named `build` found for struct `EngineBuilder<Missing>`

So "did I remember to sandbox this?" is a question your program can never get wrong. Every engine has a policy, because there is no way to make one without.

Policy::confined(), Policy::trusted() and Policy::pure() are the same three presets you used with --policy in chapter 3.

Two ways to run a script

MethodUse it when
engine.eval(&script)you run the script for what it does, and ignore what it returns
engine.eval_to::<T>(&script)you want the value the script returns, converted to T

T can be any type Lua values convert into: String, i64, f64, bool, Option<_>, or a tuple for a script that returns several values.

Script::from_source takes the code and a name. The name appears in error messages, so pick one that will tell you where the script came from.

Scripts, Arguments and Values

Real scripts live in files. This example loads one from disk, passes it arguments, and reads back a structured result.

Save the script next to your Cargo.toml as scripts/summary.lua:

-- scripts/summary.lua
local words = 0
for _ in arg[1]:gmatch("%S+") do
  words = words + 1
end

return airsstack.json.encode({ words = words, title = arg[2] })

And the program:

use airsl::{Engine, Policy, Script};

fn main() -> Result<(), airsl::Error> {
    let engine = Engine::builder().policy(Policy::confined()).build()?;

    let script = Script::from_file("scripts/summary.lua")?
        .with_args(["the quick brown fox", "Animals"]);

    let json: String = engine.eval_to(&script)?;
    println!("{json}");
    Ok(())
}
$ cargo run
{"title":"Animals","words":4}

Arguments

with_args fills the script's arg table, exactly as airsl run does from the command line. The first value becomes arg[1].

Files and require

A script loaded with Script::from_file knows which folder it lives in, so it can require the modules next to it, as you saw in chapter 2.

require needs the require member of host access. Policy::confined() holds it. Policy::pure() does not, so a pure script's require is refused, except require("airsstack"), until the policy gives it back; Granting shows how. What granting it reveals about the script's folder is covered in what airsl promises.

A script built with Script::from_source has no folder. Under a policy that grants require below trusted, such as confined, its require answers only require("airsstack"), as described in Requiring the modules by name. Any other name, require("lib") for example, fails with module `lib` cannot be loaded: the script has no directory to load modules from. Under trusted it keeps Lua's own require, and under pure other names are refused as above. To give it a folder, use .with_root(dir).

Getting structured data back

The simplest way to return structured data is to have the script encode it as JSON, then decode it on the Rust side with serde_json. JSON keys come out sorted, so the same result always produces the same string, which also makes results easy to compare in tests.

For a few plain values, return them directly and let eval_to take a tuple:

use airsl::{Engine, Policy, Script};
fn main() -> Result<(), airsl::Error> {
let engine = Engine::builder().policy(Policy::confined()).build()?;
let script = Script::from_source("return 'ok', 3", "pair")?;
let (status, count): (String, i64) = engine.eval_to(&script)?;
assert_eq!((status.as_str(), count), ("ok", 3));
Ok(())
}

Granting from Rust

Every flag from chapter 3 has a Rust equivalent. This example grants a script one folder to read, one to write, one environment variable and one program:

use airsl::{Engine, GrantSet, Policy};

fn main() -> Result<(), airsl::Error> {
    let policy = Policy::confined().with_grants(
        GrantSet::declared()
            .with_fs(|fs| fs.read("/srv/app/config").write("/srv/app/cache"))
            .with_env(|env| env.read(["APP_ENV"]))
            .with_proc(|proc| proc.allow(["git"])),
    );

    let engine = Engine::builder().policy(policy).build()?;
    let _ = engine;
    Ok(())
}

That is the same as this command line:

$ airsl run --allow-read /srv/app/config --allow-write /srv/app/cache \
            --allow-env APP_ENV --allow-exec git script.lua

GrantSet::declared() starts with all seven host access members and no folder, variable or program. It is the baseline confined uses. Each with_ call adds one kind of grant:

MethodGrantsCommand-line flag
with_fs(|fs| fs.read(dir))reading under dir--allow-read
with_fs(|fs| fs.write(dir))writing under dir--allow-write
with_env(|env| env.read(names))using those variables--allow-env
with_proc(|proc| proc.allow(names))running those programs--allow-exec

The calls chain, so fs.read(a).read(b).write(c) grants two read folders and one write folder.

Host access

Chapter 3 introduced the seven host access members. In Rust they are the variants of HostAccess: Stdin, Stdout, Stderr, Clock, Cwd, Require and Zones. with_access adds one, and allows asks whether a grant set holds one. It matches the --allow-access flag.

Two constructors give you a starting point:

ConstructorHoldsUse it for
GrantSet::declared()all seven members, and no folder, variable or programconfined, and anything built on it
GrantSet::sealed()nothing at allpure, and anything built on it

GrantSet::default() is the same as declared().

To widen Policy::pure(), start from sealed() and add what you want. Starting from declared() or default() would hand back all seven members, and the policy would no longer be pure. There is no method to take a member away, so build upward from sealed():

use airsl::{Engine, GrantSet, HostAccess, Policy, Script};

fn main() -> Result<(), airsl::Error> {
    // `sealed()` holds no host access, so this policy has exactly what it names.
    let policy = Policy::pure().with_grants(
        GrantSet::sealed()
            .with_access(HostAccess::Stdout)
            .with_access(HostAccess::Clock),
    );
    let engine = Engine::builder().policy(policy).build()?;

    let script = Script::from_source(
        r#"
        airsstack.stdio.write("clock works: " .. tostring(airsstack.time.now() > 0) .. "\n")
        local ok, err = pcall(airsstack.stdio.error, "to stderr\n")
        airsstack.stdio.write(tostring(err):match("^[^\n]*") .. "\n")
        "#,
        "demo",
    )?;
    engine.eval(&script)?;

    println!("grants: {}", engine.policy().grants());
    Ok(())
}
$ cargo run
clock works: true
stdio.error denied: `stderr` is not granted — the granted access is stdout, clock
grants: access stdout,clock

The script can write and read the clock, and stderr is refused with a message naming what it does hold.

Host access does not reach Lua's own functions

Host access bounds the airsstack modules and the confined require. The parts of Lua that a preset keeps, such as print and os.time on confined, do not ask it. This engine has the confined preset and a grant set that holds nothing:

use airsl::{Engine, GrantSet, Policy, Script};

fn main() -> Result<(), airsl::Error> {
    let policy = Policy::confined().with_grants(GrantSet::sealed());
    let engine = Engine::builder().policy(policy).build()?;

    let script = Script::from_source(
        r#"
        print("print still works")
        print("os.time still works: " .. tostring(os.time() > 0))
        local _, err = pcall(airsstack.time.now)
        print(tostring(err):match("^[^\n]*"))
        "#,
        "surface",
    )?;
    engine.eval(&script)
}
$ cargo run
print still works
os.time still works: true
time.now denied: `clock` is not granted — no access is granted

To keep a script from printing or reading the clock through Lua itself, use pure, whose surface has neither.

Changing the limits

Limits work the same way, through with_limits:

#![allow(unused)]
fn main() {
use airsl::{InstructionLimit, MemoryLimit, Policy, ResourceLimits};

let policy = Policy::confined().with_limits(ResourceLimits::new(
    Some(MemoryLimit::mebibytes(8)),
    Some(InstructionLimit::count(1_000_000)),
));
let _ = policy;
}

Pass None for a limit to remove it, or start from ResourceLimits::none() for no limits at all.

Checking what you built

An engine can tell you its own policy. The output is the same text airsl doctor prints:

use airsl::{Engine, Policy};
fn main() -> Result<(), airsl::Error> {
let engine = Engine::builder().policy(Policy::confined()).build()?;
println!("language: {}", engine.policy().language());
println!("grants:   {}", engine.policy().grants());
Ok(())
}

This is worth doing in your program's own diagnostics. When a user asks why their script was refused, the answer is whatever this prints.

One Engine, Many Scripts

Building an engine is not free. It starts a Lua interpreter and installs twelve modules into it. Running a small script on an engine that already exists is about thirty times faster than building a new one for it.

So if your program runs scripts often, such as once per request or once per keystroke, build the engine once and keep it:

use airsl::{Engine, Policy, Script};

fn main() -> Result<(), airsl::Error> {
    let engine = Engine::builder().policy(Policy::confined()).build()?;
    let double = Script::from_source("return tonumber(arg[1]) * 2", "double")?;

    let mut total = 0;
    for n in 1..=3 {
        total += engine.eval_to::<i64>(&double.clone().with_args([n.to_string()]))?;
    }

    println!("total: {total}");
    Ok(())
}
$ cargo run
total: 12

What starts fresh, and what carries over

When you reuse an engine, some things are reset for each script and some are kept:

Fresh for every scriptKept between scripts
the instruction limit, which starts again from zeromodules loaded with require, so each is loaded once
the arg tableglobal variables a script set
the folder require looks inmemory not yet freed by Lua's garbage collector

The right-hand column is the part to watch. If one script sets a global variable, the next script on the same engine sees it. That is useful for a set of scripts that work together, and a problem for scripts that should not affect each other.

The rule is simple: share an engine only between scripts that trust each other. Give scripts from different sources their own engines.

Sharing an engine between threads

Engine is Send + Sync, so you can put it in an Arc and use it from several threads:

use std::sync::Arc;
use std::thread;

use airsl::{Engine, Policy, Script};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let engine = Arc::new(Engine::builder().policy(Policy::confined()).build()?);

    let handles: Vec<_> = (0..4)
        .map(|n| {
            let engine = Arc::clone(&engine);
            thread::spawn(move || -> Result<i64, airsl::Error> {
                let script = Script::from_source("return tonumber(arg[1])", "echo")?
                    .with_args([n.to_string()]);
                engine.eval_to(&script)
            })
        })
        .collect();

    for handle in handles {
        println!("{}", handle.join().expect("thread panicked")?);
    }
    Ok(())
}

Each script still gets its own arguments, because the engine runs one script at a time and makes the others wait. That is the thing to understand about sharing: it saves you building a new engine, but it does not make scripts run in parallel. A single Lua interpreter can only do one thing at a time, however you hold it. If you need scripts to run in parallel, give each thread its own engine.

Handling Failures

When a script fails, eval and eval_to return an airsl::Error. Most of the time you print it and move on. But one question is worth asking every time: did the script fail, or was it stopped?

use airsl::{Engine, ExhaustedLimit, Policy, Script};

fn main() -> Result<(), airsl::Error> {
    let engine = Engine::builder().policy(Policy::confined()).build()?;
    let script = Script::from_source("while true do end", "spin")?;

    if let Err(error) = engine.eval(&script) {
        match error.exhausted_limit() {
            Some(ExhaustedLimit::Instructions) => eprintln!("stopped: it never finished"),
            Some(ExhaustedLimit::Memory) => eprintln!("stopped: it used too much memory"),
            Some(_) => eprintln!("stopped: it hit a limit"),
            None => eprintln!("the script failed: {error}"),
        }
    }
    Ok(())
}
$ cargo run
stopped: it never finished

The Some(_) arm is required. ExhaustedLimit is marked #[non_exhaustive], which leaves room for a new kind of limit in a future version without breaking your code.

exhausted_limit returns Some only when the engine itself stopped the script. That is worked out from what the engine actually did, never from the error's text, so a script cannot pretend to have hit a limit by raising an error with the right words in it, or hide a real one.

Failing open from Rust

A program that runs scripts as hooks has the same problem --fail-open solves on the command line (chapter 4): a broken script must not break the program that ran it. FailurePolicy names that choice:

VariantMeans
FailurePolicy::Reporta failure is reported to whoever ran the script; the default
FailurePolicy::FailOpena failure is swallowed, because the caller must keep going

Whichever you choose, a limit being hit is still worth reporting. The airsl command does exactly that:

use airsl::{Engine, FailurePolicy, Policy, Script};
fn main() -> Result<(), airsl::Error> {
let engine = Engine::builder().policy(Policy::confined()).build()?;
let script = Script::from_source("error('boom')", "hook")?;
let policy = FailurePolicy::FailOpen;
if let Err(error) = engine.eval(&script) {
    let stopped = error.exhausted_limit().is_some();
    if !policy.swallows_errors() || stopped {
        eprintln!("{error}");
    }
}
Ok(())
}

Summary

  • Engine::builder().policy(...).build() makes an engine, and it will not compile without a policy.
  • eval runs a script and eval_to returns its value.
  • GrantSet and ResourceLimits give you every grant and limit the command line has.
  • Reuse engines between scripts that trust each other. It is much faster than building new ones.
  • error.exhausted_limit() tells a stopped script apart from a failed one.

The next chapter goes one step further, and adds a module of your own to the airsstack table.

Writing Your Own Module

The twelve built-in modules cover what most scripts need. But your program almost certainly has things of its own that scripts should be able to reach: its configuration, its data, its way of logging. A host module is how you give them that, without handing over anything more.

In this chapter you will write a module called notes. Scripts call notes.add("..."), and your Rust program collects what they added.

  Lua script                             Rust program
  ──────────                             ────────────
  myapp.notes.add("disk is 91% full")  ──►  Vec<String> ["disk is 91% full"]

The module

A host module is a type that implements the HostModule trait. The trait has three methods: name, which says what the module is called, install, which puts its functions into a Lua table, and describe, which lists those functions so editors can complete and check them.

#![allow(unused)]
fn main() {
// The `notes` host module that the "Writing Your Own Module" chapter builds, shared by the two
// programs that show it being used.
//
// It lives in its own file, pulled in with `include!`, so the module the chapter prints is the
// module both programs run, not two copies that can drift apart. Installing it into an engine is
// `main.rs`; setting up an editor for it is `setup.rs`.

use std::sync::{Arc, Mutex};

use airsl::description::{Function, LuaType, ModuleDescription};
use airsl::mlua::{Lua, Table};
use airsl::{HostModule, InstallContext, ModuleName};

struct Notes {
    name: ModuleName,
    collected: Arc<Mutex<Vec<String>>>,
}

impl HostModule for Notes {
    fn name(&self) -> &ModuleName {
        &self.name
    }

    fn install(
        &self,
        lua: &Lua,
        table: &Table,
        _context: &InstallContext<'_>,
    ) -> airsl::Result<()> {
        let fail = |e| airsl::Error::lua("notes", e);

        let collected = Arc::clone(&self.collected);
        let add = lua
            .create_function(move |_, text: String| {
                collected.lock().expect("notes lock poisoned").push(text);
                Ok(())
            })
            .map_err(fail)?;

        table.set("add", add).map_err(fail)
    }

    fn describe(&self) -> airsl::Result<ModuleDescription> {
        ModuleDescription::builder("Notes a script leaves for the host program.")
            .function(Function::new("add", "Records one note.").param(
                "text",
                LuaType::STRING,
                "The note to record.",
            ))
            .build()
    }
}
}

install receives the Lua state, the table that will become myapp.notes, and a context that this module does not need yet. It creates a Rust function and stores it in the table under the name add. When a script calls notes.add("..."), Lua calls that closure with the string.

describe says the same thing as data: notes has one function, add, that takes a string called text. Nothing runs when it is called. It is the list that Editor Support turns into completion in your editor. It is a promise that has to stay true, so the last section shows how to check it.

airsl::mlua is the Lua binding airsl itself uses. Always import it from airsl rather than adding mlua to your own Cargo.toml. If the two versions ever differ, the compiler reports type errors that never mention the real cause.

Installing it

Start from the built-in modules, add yours, and give the engine its own root table name:

//! A host module of your own, installed next to the built-ins under a root table named for your
//! program.
//!
//! This is the program the "Writing Your Own Module" chapter shows: a `notes` module whose `add`
//! function collects strings from a script, and an engine that reads them back.
//!
//! Run it with `cargo run -p airsl --example notes-module`. The editor setup for the same module
//! is in `setup.rs`.

#![expect(
    clippy::expect_used,
    reason = "the notes lock is only held for a push and is never poisoned"
)]

include!("notes.rs");

use airsl::{Engine, Policy, RootTable, Script};

fn main() -> Result<(), airsl::Error> {
    let collected = Arc::new(Mutex::new(Vec::new()));

    let mut modules = airsl::modules::stdlib()?;
    modules.insert(Box::new(Notes {
        name: ModuleName::new("notes")?,
        collected: Arc::clone(&collected),
    }))?;

    let engine = Engine::builder()
        .policy(Policy::confined())
        .root_table(RootTable::new("myapp")?)
        .stdlib(modules)
        .build()?;

    let script = Script::from_source(
        r#"
          myapp.notes.add("disk is 91% full")
          myapp.notes.add("backup finished in " .. 42 .. "s")
        "#,
        "report",
    )?;
    engine.eval(&script)?;

    for note in collected.lock().expect("notes lock poisoned").iter() {
        println!("note: {note}");
    }
    Ok(())
}
$ cargo run
note: disk is 91% full
note: backup finished in 42s

Two things happened here besides adding the module.

airsl::modules::stdlib() is the list of built-ins. You add to it, so scripts keep json, regex and the rest alongside your module. You could also start from an empty ModuleSet and offer only your own.

RootTable::new("myapp") renamed the global. Scripts now write myapp.notes.add and myapp.json.encode, instead of airsstack.…. Your users are writing scripts for your program, so the global should carry your program's name. Scripts can also write require("myapp") to get the same table.

A module that asks permission

notes needs no permission, because collecting strings reaches nothing. A module that does reach something, such as one that writes to a database or calls an API, should check a grant first, just as fs does.

The InstallContext that install receives carries the engine's policy. Read the grants from it:

fn install(&self, lua: &Lua, table: &Table, context: &InstallContext<'_>) -> airsl::Result<()> {
    let may_write = !context.grants().fs().write_roots().is_empty();
    // ...create functions that refuse when `may_write` is false
}

Two rules keep a module like this honest:

  1. Check inside the Rust function, before doing the work. Never trust the script to check for itself. A check written in Lua is one a script can skip.
  2. Read the grants from the context. Do not keep a separate copy. The context holds the policy the engine was built with, the same one engine.policy() and airsl doctor report, so what your module enforces can never drift from what your program says it enforces.

And when the module refuses, raise an error that names what was granted, so the person reading it knows what to change. The custom-module example shows a complete module that does this.

Keeping the description honest

A description that lists a function install never sets, or leaves one out, sends your editor and your users the wrong way. airsl::luals::verify catches that. It installs the module into a scratch Lua state, compares what it finds with what describe says, and returns an error that names the difference. Call it from your own tests.

airsl::luals::setup does for your program what airsl lua setup does for the built-ins. Give it a project folder, your module set and your root table, and it writes the description file your editor reads, then adds it to the language server's settings file. The description file is named after the root table, so here it is .airsl/types/myapp.lua.

//! Setting up an editor for a host module of your own, and the test that keeps its description
//! true.
//!
//! This is the second program the "Writing Your Own Module" chapter shows. Run it with
//! `cargo run -p airsl --example notes-module-setup` from a scratch folder: it writes `.airsl/`
//! and `.luarc.json` into the folder you run it from. Its test checks that the description matches
//! what the module installs; run it with `cargo test -p airsl --example notes-module-setup`. The
//! module itself is in `notes.rs`.

#![cfg_attr(
    test,
    expect(
        clippy::unwrap_used,
        reason = "tests unwrap known-valid fixtures; a panic is the intended failure signal"
    )
)]
#![expect(
    clippy::expect_used,
    reason = "the notes lock is only held for a push and is never poisoned"
)]

include!("notes.rs");

use std::path::Path;

use airsl::RootTable;
use airsl::luals::setup;

fn notes() -> Result<Notes, airsl::Error> {
    Ok(Notes {
        name: ModuleName::new("notes")?,
        collected: Arc::new(Mutex::new(Vec::new())),
    })
}

fn main() -> Result<(), airsl::Error> {
    let root = RootTable::new("myapp")?;

    let mut modules = airsl::modules::stdlib()?;
    modules.insert(Box::new(notes()?))?;

    let report = setup(Path::new("."), &modules, &root)?;
    println!("{report}");
    Ok(())
}

#[cfg(test)]
mod tests {
    use airsl::luals::verify;

    use super::*;

    #[test]
    fn notes_describes_what_it_installs() {
        verify(&notes().unwrap(), &RootTable::new("myapp").unwrap()).unwrap();
    }
}

cargo test runs the check. cargo run in your project's folder sets it up:

$ cargo test --quiet

running 1 test
.
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

$ cargo run --quiet
created .airsl/types/myapp.lua
created .luarc.json

setup checks every module with verify first, so a description that has drifted stops it before it writes anything.

Summary

  • A host module implements HostModule: a name, an install that fills a Lua table, and a describe that lists what install sets.
  • Import mlua through airsl::mlua.
  • Add your module to airsl::modules::stdlib() to keep the built-ins.
  • Name the root table after your program with RootTable.
  • A module that reaches outside the script checks its grant in Rust, from the InstallContext.
  • Call airsl::luals::verify in your tests, and airsl::luals::setup to write the editor files for your own root table.

Extensions

So far, the person running a script has also decided what it may touch: you wrote the grant flags, or your program built the policy. An extension turns that around. It is code someone else wrote, which comes with its own description of what it needs. Your program reads that description, decides how much of it to allow, and only then runs the code.

This is the model Redis uses for its scripts, and the model editors use for plugins. The extension asks; the host decides.

  extension.toml says          your program allows          the extension gets
  ───────────────────          ───────────────────          ──────────────────
  read  ~/notes          ∩     read  ~/notes, ~/docs   =    read  ~/notes
  run   git, tar               run   git                    ✗ refused: tar is not allowed

In this chapter you will:

  1. write a small extension that counts words
  2. describe what it needs in a manifest
  3. see how a host bounds what an extension may ask for
  4. try it from the command line, then load it from Rust

Two kinds of extension

KindHow it runsExample
a scriptruns once from top to bottom, then endseverything in chapters 1 to 5
a registered extensionloads once, registers handlers, and is called each time an event happensthis chapter

A registered extension pays the cost of starting once, and is then called again and again. As chapter 6 showed, calling into an engine that already exists is many times faster than building a new one, so this shape is what makes extensions cheap enough to call on every event.

Writing an Extension

An extension is a folder with two things in it: a manifest called extension.toml, and a Lua entry script.

word-count/
├── extension.toml
└── main.lua

The entry script

-- word-count/main.lua
airsstack.ext.on("count", function(payload)
  local words = airsstack.regex.find_all([[\w+]], payload.text)

  local longest = ""
  for _, word in ipairs(words) do
    if #word > #longest then
      longest = word
    end
  end

  return { words = #words, longest = longest }
end)

The entry script runs once, when the extension loads. It does not do the work itself. It calls ext.on to say "when the count event happens, call this function". Each time the host fires count, the function receives the event's payload as a table, and whatever it returns goes back to the host as JSON.

The manifest

# word-count/extension.toml
[extension]
name    = "word-count"
version = "0.1.0"
entry   = "main.lua"
api     = 1

[capabilities]
regex = true

[limits]
memory       = "8MB"
instructions = 1_000_000
SectionSays
[extension]who the extension is, which file to run, and which version of the extension API it was written for
[capabilities]what it needs; this one needs only regex, which reaches nothing
[limits]how much it expects to spend; a host will never give it more than its own limits

Asking for more

An extension that needs files, variables or programs asks for them the same way:

[capabilities]
fs.read  = ["$NOTES_HOME"]
fs.write = ["$NOTES_HOME/.index"]
env.read = ["NOTES_HOME"]
proc.run = ["git"]

[capabilities.optional]
proc.run = ["tar"]

Three rules apply to everything in [capabilities]:

A request is a maximum, never a right. The host compares what the extension asks for with what it is willing to allow. Asking for fs.read = ["/"] is not an error, it just will not be granted.

Required means required. If anything under [capabilities] cannot be granted, the extension does not load at all. It never starts in a half-working state, quietly failing at whatever it could not do. Anything it can genuinely live without goes under [capabilities.optional].

Variables are filled in by the host. $NOTES_HOME is replaced with a value the host supplies, never one the extension supplies. Otherwise an extension could point the variable at / and widen its own grant.

An unknown key is an error, not something to skip. A misspelled fs.raed that was silently ignored would be a permission the author believed they had asked for.

Checking what was granted

Inside the extension, ext.granted() returns what the host actually allowed. Use it to check for an optional capability:

local granted = airsstack.ext.granted()
if granted.proc and granted.proc.run["tar"] then
  -- tar was allowed, so archives can be made
end

How the Host Decides

Between reading a manifest and running an extension, the host makes its decision in three steps. Each step can only narrow what the extension gets, never widen it.

  manifest ──► ① ceiling ──► ② approver ──► ③ start
               │              │              │
               what the       a final yes    build an engine with the
               host will      or no          agreed policy, then run
               ever allow                    the entry script

① The ceiling

The ceiling is the most the host is ever willing to allow, written as an ordinary policy. The manifest's request is compared against it, item by item, and each item ends up in one of three states:

ResultMeans
grantedit was asked for, and it is inside the ceiling
reducedit was asked for, and only part of it is inside the ceiling
deniedit was asked for, and it is outside the ceiling

A denied required capability stops the extension right here. Nothing else runs.

Limits work the same way. If the manifest asks for 8 MB of memory and the ceiling allows 64 MiB, the extension gets 8 MB. If it asks for more than the ceiling allows, it gets the ceiling.

② The approver

If the request survives the ceiling, an approver gives the final answer. airsl comes with two:

ApproverAnswer
ManifestApproveryes to whatever survived the ceiling
DenyAllno, always

A host can write its own. A common choice is to approve extensions from a trusted registry automatically, and to ask a person about anything else. The approver can only say no to what the ceiling allowed. It can never add to it.

③ Start

Only now does airsl build an engine, under the agreed policy, and run the extension's entry script. By the time any extension code runs, both checks have passed. That order is enforced by the types in the Rust API, not by convention: there is no way to start an extension that has not been approved.

Seeing the decision

airsl ext doctor shows the whole decision without running any of the extension's code:

$ airsl ext doctor ./word-count
extension:    word-count 0.1.0 (api 1, entry main.lua)
events:       none
ceiling:
  language:     restricted
  grants:       access stdin,stdout,stderr,clock,cwd,require,zones
  memory:       67108864 bytes
  instructions: 100000000 instructions
negotiated:
  language:     restricted
  grants:       access stdin,stdout,stderr,clock,cwd,require,zones
  memory:       8388608 bytes
  instructions: 1000000 instructions
requested:
  module       regex                    granted
decision:     approve

ceiling is what the host offered, here the confined defaults. negotiated is what the extension will actually run under: the same grants, and the smaller limits its manifest asked for.

The grants: line starts with access, the host access the extension may use. The ceiling decides it: the extension gets exactly the members the ceiling holds, no more and no fewer, and its manifest cannot ask for one. A confined ceiling holds all seven, as shown. A pure ceiling holds none, so a host that wants its extensions to read the clock or to require their own files has to put those members in the ceiling. The members are described in chapter 3.

When a request is outside the ceiling, the report says which item and why:

$ airsl ext doctor ./greedy
...
requested:
  fs.read      /                        denied    (outside the granted read roots: none)
decision:     deny — fs.read `/`: outside the granted read roots: none

To widen the ceiling, pass the same grant flags airsl run takes. --allow-access is accepted too, but this command's ceiling is confined, which already holds every member, so it changes nothing. --var NAME=VALUE supplies a manifest variable.

Firing an event

airsl ext fire loads the extension for real and fires one event at it. The payload is read from standard input, and the result is printed as JSON:

$ echo '{"text":"the quick brown fox"}' | airsl ext fire ./word-count count
{"longest":"quick","words":4}

It goes through exactly the same steps a Rust host would, so it is a quick way to try an extension before you write the host.

Hosting Extensions in Rust

ExtensionHost does everything from the last page in one place: it reads manifests, checks them against your ceiling, asks the approver, starts each extension, and fires events at them.

This host loads every extension in a folder, then fires one count event at all of them:

use airsl::extension::Ceiling;
use airsl::{EventName, ExtensionHost, Policy};
use serde_json::json;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut host = ExtensionHost::builder()
        .ceiling(Ceiling::new(Policy::confined())?)
        .events(["count"])?
        .build()?;

    let report = host.load_dir("extensions")?;
    for name in report.loaded() {
        println!("loaded: {name}");
    }
    for (dir, error) in report.failed() {
        println!("failed: {} ({error})", dir.display());
    }

    let payload = json!({ "text": "the quick brown fox jumps over the lazy dog" });
    for dispatch in host.broadcast(&EventName::new("count")?, &payload) {
        match dispatch.result() {
            Ok(Some(value)) => println!("{}: {value}", dispatch.name()),
            Ok(None) => println!("{}: (not subscribed)", dispatch.name()),
            Err(error) => println!("{}: error: {error}", dispatch.name()),
        }
    }
    Ok(())
}

With word-count and an extension that asks for too much side by side in extensions/:

$ cargo run
loaded: word-count
failed: extensions/greedy (extension `greedy` was not loaded: fs.read `/`: outside the granted read roots: none)
word-count: {"longest":"quick","words":9}

Walking through it

.ceiling(...) sets the most this host will ever allow. Ceiling::new refuses a policy that would bound nothing, such as Policy::trusted(), because an unlimited ceiling is no ceiling. Like the engine builder, there is no build() until you have given it a ceiling.

.events([...]) lists the events this host fires. An extension that calls ext.on for any other name is refused when it loads, so a typo in an event name shows up immediately rather than as a handler that is never called.

load_dir loads every subfolder that holds an extension.toml, in name order. It never stops at the first failure. Every outcome goes into the report, so one broken extension never hides the others. Use host.load(dir) instead to load a single extension.

broadcast fires an event at every loaded extension, in load order, and returns one result each. A failing handler does not stop the others either. Ok(None) means the extension did not subscribe to that event, which is normal.

Choices the host makes

A few settings on the builder are worth knowing:

MethodDoes
.approver(a)uses your own approver instead of ManifestApprover
.variables([("NAME", "value")])supplies values for $NAME in manifests
.root_table(RootTable::new("myapp")?)names the global extensions see, and the name require answers with that table
.modules(factory)chooses the modules each extension gets, including your own from chapter 7

Some things are deliberately left to you. Grants are fixed for the life of a loaded extension; to change what an extension may reach, load it again. And broadcast reports every failure but never disables an extension on its own. Whether three failures in a row means "stop calling this one" is your program's decision.

Keeping extensions working

The manifest's api = 1 is a promise from airsl. Within one API version, modules and events only ever gain new functions and names. Nothing an extension already relies on changes meaning or goes away. A change that would break that gets a new API number, and an extension that asks for an API version this airsl does not support is refused before any of its code runs.

Summary

  • An extension is a folder with an extension.toml and an entry script that registers handlers with ext.on.
  • The manifest asks; the host's ceiling and approver decide. Each step can only narrow the grant.
  • A required capability that cannot be granted stops the extension from loading at all.
  • airsl ext doctor shows the decision, and airsl ext fire tries an event.
  • ExtensionHost loads a folder of extensions and broadcasts events to them, reporting every failure without stopping.

Under the Hood

This chapter is for the curious, and for anyone who wants to work on airsl itself. It explains how the pieces you have used fit together, why they are shaped the way they are, and, just as importantly, what airsl can and cannot promise.

You do not need any of it to use airsl.

Three Layers

airsl is built from three layers, and the most useful thing to know about them is that they are separate. Each answers a different question, and each can be changed without the others.

  ┌─────────────────────────────────────────────────────────┐
  │ 3. Modules     json, fs, proc, …  and your own          │  what tools exist
  ├─────────────────────────────────────────────────────────┤
  │ 2. Policy      language · grants · limits               │  what is allowed
  ├─────────────────────────────────────────────────────────┤
  │ 1. The VM      Lua 5.4, compiled in                     │  what runs the code
  └─────────────────────────────────────────────────────────┘

1. The VM

airsl runs Lua 5.4 through the mlua crate. Lua's C source is compiled during the build and linked straight into the binary, which is why the build needs a C compiler and the result needs nothing at all.

It is Lua 5.4 rather than an older version or LuaJIT for one reason: from 5.3 onwards, Lua knows the difference between the integer 3 and the float 3.0. Older versions treat them as the same number. Without that difference, JSON output could not be the same byte for byte from one run to the next.

airsl always runs Lua 5.4. The native module for stock Lua also runs on LuaJIT, and Running Scripts in Stock Lua lists what differs there.

2. Policy

A policy is three separate answers:

PartAnswersSet with
languagewhich parts of Lua's own library the script seesthe preset
grantswhat the airsstack modules may touch, and which host access they have--allow-…, GrantSet
limitshow much memory and time the script may spend--memory-limit, ResourceLimits

Keeping them apart is what lets you say things like "all of Lua, but only 8 MB of memory", or "no limits, but nothing granted either". If they were one setting, most combinations could not be expressed.

The limits are armed before any module is installed, so there is no moment, however brief, when an engine exists without them.

3. Modules

Each module is a set of Rust functions placed into a Lua table under the root table, airsstack by default. The built-ins and your own modules are installed the same way, through the HostModule trait.

Each module receives the engine's policy when it is installed. That single shared policy is why airsl doctor, engine.policy() and what the modules actually enforce can never disagree: they are all reading the same thing.

Engines and evaluations

An engine runs one script at a time. It holds a lock for the whole of each evaluation, not just for each step, so two threads sharing an engine can never mix up each other's arguments.

Each evaluation resets three things before the script runs: the instruction count, the arg table, and the folder require looks in. Everything else in the Lua state carries over, as chapter 6 described.

Extensions on top

The extension system is not a fourth layer. It sits on top of the three: it reads a manifest, works out a policy from it, and then builds an ordinary engine with that policy. Once an extension is running, it is just an engine like any other.

The Rules Behind the Design

A handful of rules explain almost every decision in airsl. If you are adding to it, these are the ones to keep.

Every module is a capability

A module is the unit of permission. path and fs are separate because building a path needs no permission and opening one does. If they were one module, a script that only joins file names would have to be granted file access to do it.

So adding a function that makes a module need a grant it did not need before is not a small change. It changes what every user of that module has to grant.

Checks happen in Rust, never in Lua

Every grant is checked inside the Rust function, right before the operation. A Lua script never holds a file handle or a process handle. It holds a string, and asks Rust to act on it.

The alternative, a helper function in Lua that checks a path before opening it, does not work. A script that forgets to call the helper is unprotected, and nothing makes it call the helper. A check the script can skip is not a check.

Checking a path properly

Deciding whether a path is inside a granted folder sounds simple, and the simple version is wrong.

The tempting approach is to clean the path up as text, by resolving . and .., and see whether the result starts with the granted folder. Here is why that fails:

  granted:   /srv/app
  symlink:   /srv/app/link  →  /elsewhere

  path:      /srv/app/link/../secret

  as text:   /srv/app/secret      ✓ looks inside the folder
  on disk:   /elsewhere/../secret = /secret   ✗ is actually outside it

On disk, .. is applied after the symlink is followed, so the two answers differ. A text check would let the script read /secret.

What airsl does instead: it finds the deepest part of the path that really exists, and asks the operating system for that part's true location, with every symlink followed. It compares that against the grant. Below that point the path does not exist yet, so it cannot contain a symlink, and airsl accepts only plain names there. A .. below that point is refused rather than resolved.

The same input gives the same output

Determinism is treated as part of being correct, not as a nice extra:

  • JSON object keys are always sorted.
  • Folder listings are always sorted, by name, byte by byte.
  • time.format always uses UTC, and always needs an explicit moment.
  • Paths are always written with /, on every platform.

The reason is that non-determinism does not fail loudly. It shows up as a diff that should not be there, or a cache that never hits, and those are hard to trace back.

This rule is also why os.setlocale is withheld under confined, even though it is harmless in itself. Lua compares strings using the current locale, so a script that changed the locale would change the order of every table.sort in every script after it.

Present but refusing

Every module is installed under every preset, even when the script has no grant for it. An ungranted module refuses each call with a message that names what was granted. If modules disappeared instead, if airsstack.fs then would mean "am I allowed?" rather than "does this runtime have files?", and a script would skip its work silently instead of telling you why.

Stopped is not the same as failed

When a script hits a memory or instruction limit, the error says so in its type, not just its text. The engine works it out from its own instruction counter and from the VM's own error. A script can raise an error whose message reads exactly like a limit being hit, and it is still reported as an ordinary failure. That is why the command line can always report a limit being hit, even under --fail-open, without being fooled.

What airsl Can and Cannot Promise

A sandbox is only useful if you know exactly where its edges are. Here they are.

What it does promise

  • A script reaches only what its policy allows. Every module checks its grant in Rust before it acts, and Lua's own ways around the modules (io, os.execute, load and the rest) are removed below trusted.
  • A script cannot run forever or use unlimited memory, as long as the limits are on. The limits hold inside airsl. A script run in stock Lua through the native module has none; see Running Scripts in Stock Lua.
  • You can see the whole surface. airsl doctor and engine.policy() describe exactly what a script gets, and there is no way to add to an engine except through HostModule, which those reports include.
  • Starting a script is fast. It takes microseconds, and extension authors need no toolchain.

What pure guarantees

The pure preset is for calculations, and it makes a stronger promise than the others. Unless you give it more, a pure script reaches no standard input, standard output or standard error, no clock, no working folder, no file on the host and no time-zone database. It cannot print, because print is not there, and it cannot seed its random numbers from the clock, because math.randomseed() with no seed is refused.

So on a fresh engine, the same script given the same input produces the same output. Here is a script that draws a random number:

-- roll.lua
airsstack.stdio.write(math.random(1, 1000000) .. "\n")

Under pure, every run draws the same number. The script needs stdout to write its answer, which chapter 3 explains. Under confined, the number changes each run:

$ airsl run --policy pure --allow-access stdout roll.lua
275394
$ airsl run --policy pure --allow-access stdout roll.lua
275394
$ airsl run --policy confined roll.lua
693869
$ airsl run --policy confined roll.lua
561919

Each thing you grant opens its own route. A pure script that holds clock can read the time, so its output can then change from run to run.

Three things that can still differ

The guarantee has three exceptions. They come from the Lua interpreter itself, and airsl does not control them:

  • pairs order. Walking a table with pairs can visit string keys in a different order on each run. Collect the keys, sort them, and walk the sorted list.
  • Printed addresses. tostring of a table or function, and string.format("%p", value), show a memory address, which changes between runs.
  • table.sort ties. When the comparison treats two elements as equal, they can come out in a different order on each run. A comparison that breaks every tie gives one order. Here, people of the same age are ordered by name:
-- sort.lua
local people = {
  { name = "Mia", age = 30 },
  { name = "Ben", age = 25 },
  { name = "Zoe", age = 30 },
  { name = "Ann", age = 25 },
}
table.sort(people, function(a, b)
  if a.age ~= b.age then return a.age < b.age end
  return a.name < b.name
end)
for _, p in ipairs(people) do
  airsstack.stdio.write(p.age .. " " .. p.name .. "\n")
end
$ airsl run --policy pure --allow-access stdout sort.lua
25 Ann
25 Ben
30 Mia
30 Zoe

Reusing an engine

The promise is for a fresh engine. An engine that runs several scripts keeps the globals they set, and it keeps going along the same random sequence rather than starting it again. The second script then sees a different number from the first. Chapter 6 covers reuse. Use a new engine when each run must stand alone.

Granting require

A pure script can load its own sibling files once you grant require. Doing so shows the script the absolute location of its folder. Each module receives its own absolute path as its second argument, and error messages name it:

-- greeting.lua
local name, path = ...
airsstack.stdio.write("loading " .. name .. " from " .. path .. "\n")
return { hello = function(who) return "hello, " .. who end }
-- main.lua
local greeting = require("greeting")
airsstack.stdio.write(greeting.hello("world") .. "\n")
$ airsl run --policy pure --allow-access stdout --allow-access require main.lua
loading greeting from /home/you/proj/greeting.lua
hello, world

If that location should stay private, do not grant require, or keep the scripts in one file.

What it does not promise

  • No protection from a bug in a module. The sandbox lives at the boundary between Lua and Rust. If a module's Rust code has a bug, or Lua's own C code does, that bug runs inside your program with your program's full rights. A grant is a promise the module keeps, and there is nothing underneath to catch a module that breaks it.
  • No protection from a malicious module. A module you install can do anything Rust can do. Install only modules you trust.
  • No separation of CPU or memory between scripts on one engine. Scripts that share an engine share its state, as chapter 6 described.

Compared with WebAssembly

WebAssembly sandboxes at a deeper level. A WASM module runs in its own memory, so even a buggy host function cannot let it read the host's memory. Lua under airsl cannot offer that.

WASM also lets extension authors use any language that compiles to it. The price is a compiler toolchain for every author, a heavier runtime, and a much more awkward boundary for passing data back and forth.

airsl (Lua)WebAssembly
Where the sandbox isthe API boundarythe VM boundary
Survives a buggy host functionnoyes
Author needsa text editora compiler toolchain
Start-upmicrosecondsheavier
Passing dataLua tables and JSONbytes in linear memory

So the honest advice is this. For extensions you write yourself, review, or accept from a registry you control, Lua under airsl is a good trade, and Redis has shown it works for years. For running genuinely hostile code from strangers, WebAssembly is the stronger choice.

What is not built yet

A few things are known gaps rather than design choices:

  • Isolation between scripts on a reused engine. Global variables a script sets, and changes it makes to shared tables such as string, stay visible to the next script on the same engine. Until that is built, give scripts that do not trust each other separate engines.
  • proc cannot set a working folder, standard input or extra environment for one call. Scripts work around it, for example with git -C <dir>.
  • Exit codes other than 0 and 1. os.exit is withheld below trusted, so a script cannot choose its own exit code.
  • JSON null and empty arrays cannot be built from Lua. They can only come from decoding JSON.
  • Future modules: http, sqlite, cryptography beyond hashing, and bundling a script with its modules into one file are all planned, and none exists yet.

Appendix

The appendix holds the reference material: the tables to come back to once you know how airsl works.

For the Rust API, the reference is the generated documentation at docs.rs/airsl.

A. Command-Line Reference

airsl run    [OPTIONS] <script.lua> [args…]
airsl test   [OPTIONS] [<path>]
airsl check  [<path>]
airsl doctor [--policy <preset>] [GRANTS]
airsl lua setup  [--native [--lua 5.4|luajit]] [<DIR>]
airsl ext doctor <DIR>         [GRANTS] [LIMITS] [--event NAME] [--var NAME=VALUE]
airsl ext fire   <DIR> <EVENT> [GRANTS] [LIMITS] [--event NAME] [--var NAME=VALUE]

Commands

CommandDoes
runruns one script; everything after the script's path goes to arg
testruns every *_test.lua and test_*.lua under a folder; finding none is a failure
checkcompiles every .lua under a folder without running any; finding none is a failure
lua setupwrites a description of the built-in modules into a project and adds it to the language server's settings file, so your editor completes airsstack calls; see Editor Support. --native also installs the native module with LuaRocks, for running scripts in stock Lua; see Running Scripts in Stock Lua
doctorprints the policy a script would get from the preset and grant flags you give it
ext doctorprints what a host would grant, reduce and deny for an extension, without running it
ext fireloads an extension and fires one event; payload on stdin, result on stdout as JSON

Options for run, test and doctor

doctor takes --policy and the --allow-… flags. It takes no --memory-limit or --instruction-limit, and no --fail-open: it shows the preset's own limits.

OptionDoes
--policy <trusted|confined|pure>picks the preset; the default is confined
--allow-read DIRgrants reading under DIR; repeatable
--allow-write DIRgrants writing under DIR; repeatable; does not grant reading
--allow-env NAMEgrants reading and setting NAME; repeatable
--allow-exec PROGRAMgrants running PROGRAM, matched on the name as written; repeatable
--allow-access NAMEhost access the sandbox may use; repeatable. Only pure starts without them
--memory-limit <BYTES|none>replaces the preset's memory limit
--instruction-limit <COUNT|none>replaces the preset's instruction limit
--fail-openrun only: swallows any failure and exits 0

Under --policy trusted, the --allow-… flags are ignored, because nothing is restricted. Under --policy confined, --allow-access changes nothing, because confined already holds every kind of host access. Under --policy pure, it is the only way to give a script any.

The names are stdin, stdout, stderr, clock, cwd, require and zones. An unknown name is refused with that list, and the exit status is 2. Naming the same access twice is accepted and grants it once.

Options for ext doctor and ext fire

These take the same --allow-…, --memory-limit and --instruction-limit flags, which widen the host's ceiling. The ceiling always starts from confined. There is no --policy, because trusted cannot serve as a ceiling.

--allow-access is accepted here too, but it cannot change the ceiling: confined already holds every kind of host access.

OptionDoes
--event NAMEdeclares an event the host fires, beyond the one being fired; repeatable
--var NAME=VALUEsupplies a value for $NAME in the manifest; repeatable

Exit codes

Command01
runthe script finishedthe script failed or hit a limit; with --fail-open, always 0
testevery test passeda test failed, or no test files were found
checkevery file compileda file failed to compile, or no .lua files were found
lua setupboth files are set up or already wereany error, including a LuaRocks failure with --native; nothing is written when a check fails, and an install that fails leaves the type file and the settings entry written
ext doctorany decision, including denythe manifest or the ceiling is invalid
ext firethe event was fired and a result (or null) printedany error

Environment variables

VariableDoes
AIRSL_DEBUG=1prints errors that --fail-open would hide
AIRSL_CLI_NO_MODIFY_PATH=1read by the installer: leave PATH alone

A script that hits a memory or instruction limit is always reported on standard error, even under --fail-open.

B. Module Reference

Every module lives under the root table, airsstack unless the host renamed it. Every module is present under every preset. A call that needs a grant the script does not have raises an error that names what was granted.

json

No grant needed.

FunctionReturns
encode(value)compact JSON text; object keys sorted
encode_pretty(value)indented JSON text; object keys sorted
decode(text)a Lua value; null becomes a marker that is not nil and encodes back as null; [] becomes a table that encodes back as []

regex

No grant needed. Syntax is that of Rust's regex crate.

FunctionReturns
is_match(pattern, text)true or false
find(pattern, text)the first match, or nil
find_all(pattern, text)a list of every match
captures(pattern, text)groups of the first match by number and by name, or nil
replace(pattern, text, with)text with the first match replaced; $1 and $name refer to groups
replace_all(pattern, text, with)text with every match replaced
split(pattern, text)a list of the pieces between matches
compile(pattern)a table with all the functions above, bound to pattern

path

Works on strings only, and always writes /. Needs no grant, except that absolute(p) of a relative path needs the cwd member of host access.

FunctionReturns
join(a, b, …)the parts joined with /
dirname(p), basename(p)the folder part, the last part
stem(p), ext(p)the last part without, and only, its extension; ext gives "" when there is none
normalize(p)p with . and .. resolved as text; not a containment check
relative_to(p, base)p relative to base; an error if p is not under base
is_absolute(p)true or false
absolute(p)p made absolute against the current folder

fs

Needs a read or write grant for the path, as listed. A relative path also needs the cwd member of host access.

FunctionGrantReturns
read(p)readthe file's contents
read_lines(p)reada list of lines, without line endings
write(p, text)writenothing; replaces the file
append(p, text)writenothing; adds to the end
atomic_write(p, text)writenothing; readers never see a half-written file
create_exclusive(p, text)writetrue if this call created the file, false if it existed
exists(p), is_file(p), is_dir(p)readtrue or false
stat(p)read{ kind, size, modified, readonly }
list(p)readsorted names in the folder
walk(p)readsorted paths of everything below the folder, relative to it
mkdir(p)writenothing; creates missing parents too
remove(p), remove_dir(p)writenothing
copy(from, to)read from, write tonothing
rename(from, to)write bothnothing
same_content(a, b)read bothtrue if the files hold the same bytes
canonicalize(p)readthe real absolute path, symlinks followed
tempfile(), tempdir()write, on the system temp folderthe new path

glob

A relative root for walk also needs the cwd member of host access.

FunctionGrantReturns
match(pattern, path)nonetrue or false
walk(root, pattern)read rootsorted matching paths, relative to root

* and ? stop at /. **/ matches any number of folders, including none. {a,b} matches either.

env

Needs each variable's name to be granted.

FunctionReturns
get(name)the value, or nil if granted but unset
all()a table of every granted variable that is set
set(name, value)nothing; seen by later get calls and by programs proc runs, never by the host

proc

Needs each program's name to be granted.

FunctionReturns
run({program, arg, …}){ status, stdout, stderr }; a non-zero status is not an error
which(program)the full path that would run, or nil

time

now() and monotonic() need the clock member of host access. parse needs the zones member when its pattern names a time zone, and nothing otherwise. format needs nothing.

FunctionReturns
now()whole seconds since 1970
format(seconds [, pattern])text in UTC; the default is like 2023-11-14T22:13:20Z
parse(text [, pattern])seconds since 1970
monotonic()a reading in seconds, for measuring time between two readings

hash

A relative path for hash_file also needs the cwd member of host access.

FunctionGrantReturns
sha256(text)nonehex
sha1(text)nonehex; for compatibility with existing names only
hex(text)nonethe bytes of text as hex
hash_file(p)readthe SHA-256 of the file, as hex

stdio

read and lines need the stdin member of host access, write needs stdout, and error needs stderr. isatty needs the member for the stream it names.

FunctionReturns
read()all of standard input
lines()all of standard input, as a list of lines
write(text)nothing; writes to standard output with nothing added
error(text)nothing; writes to standard error with nothing added
isatty([stream])whether "stdin", "stdout" (the default) or "stderr" is a terminal

hook

payload() needs the stdin member of host access. context and emit need stdout.

FunctionReturns
payload()standard input decoded as JSON; an empty table for empty input
context(event, text)nothing; prints the reply that adds text to the agent's context
emit(value)nothing; prints value as JSON

ext

No grant needed. Only useful inside a registered extension.

FunctionReturns
on(event, handler)nothing; registers handler for an event the host declared
granted()the grants and limits this script actually received

C. Presets at a Glance

trustedconfined (default)pure
Meant foryour own scriptseveryday and third-party scriptspure calculations
RustPolicy::trusted()Policy::confined()Policy::pure()
doctor languagefullrestrictedminimal
Lua librarieseverything except debugstring, table, math, utf8, coroutine, safe osstring, table, math, utf8
io, packageyesnono
load, loadstring, dofile, loadfileyesnono
os.execute, exit, getenv, remove, rename, tmpname, setlocaleyesnono
os.time, os.clock, os.dateyesyesno
printyesyesno
math.randomdifferent each rundifferent each runthe same each run
math.randomseed() with no seedyesyesrefused
Host accessall seven membersall seven membersnone
requireLua's ownthe script's folder onlyrefuses all but require("airsstack"); with the require member, the script's folder only
airsstack modulesall, unrestrictedall, only what is grantedall, only what is granted
Memory limitnone64 MiB16 MiB
Instruction limitnone100 million10 million

utf8 is on every preset. Without it a script could only count bytes, not characters, and could not shorten text without the risk of cutting a character in half.

D. Installation Details

What the install commands run

install.sh and install.ps1 are small. They download the installer published with a release and run it. Without AIRSL_VERSION that is the latest release. With it, it is the release you named, and a version that was never released is refused with a link to the releases page.

Anything you pass along reaches the release's installer unchanged: its flags (--no-modify-path, --quiet), and its settings, such as AIRSL_CLI_INSTALL_DIR to put airsl in a folder other than ~/.local/bin.

$ curl -LsSf https://airsstack.github.io/airsl/install.sh | sh -s -- --no-modify-path
$ curl -LsSf https://airsstack.github.io/airsl/install.sh | AIRSL_CLI_INSTALL_DIR="$HOME/bin" sh

On Windows, set the variable in a PowerShell session, then run the installer from that session:

$env:AIRSL_VERSION = '<version>'; irm https://airsstack.github.io/airsl/install.ps1 | iex

The installer only runs when the session allows scripts. If it refuses, run Set-ExecutionPolicy RemoteSigned -Scope CurrentUser once, or use the powershell -ExecutionPolicy Bypass command from Installation.

Archives

Each release has one archive per platform. You can download one by hand instead of running the installer.

ArchiveRuns onNeeds at runtime
aarch64-apple-darwinmacOS on Apple Siliconnothing beyond macOS
x86_64-apple-darwinmacOS on Intelnothing beyond macOS
x86_64-unknown-linux-gnu, aarch64-unknown-linux-gnuLinux with glibca glibc at least as new as the build machine's
x86_64-unknown-linux-musl, aarch64-unknown-linux-muslany Linux, including Alpinenothing; fully static
x86_64-pc-windows-msvcWindowsnothing beyond Windows

On Linux, the installer picks the glibc build when your system's glibc is new enough, and the musl build otherwise. Both run the same scripts in the same way.

Scripts outside airsl

The archives are for the airsl command. The native module that runs scripts in stock Lua is a separate LuaRocks package, covered in Running Scripts in Stock Lua.

Verifying a download

Every archive has a .sha256 file next to it. The installer checks the archive against it when sha256sum is available.

Every archive also carries a GitHub artifact attestation, a signed record that ties the file to this repository and the build that made it. That catches even an archive swapped together with its checksum file:

$ gh attestation verify airsl-cli-x86_64-unknown-linux-musl.tar.xz --repo airsstack/airsl

Before any release is published, every archive is unpacked on the platform it targets and made to run the example scripts, pass the example tests, and refuse what it was not granted. An archive that fails is not published.

Unsigned binaries

The binaries are not signed with an Apple or Windows code-signing certificate. That only matters for an archive downloaded through a web browser. On macOS, Gatekeeper refuses to run it until you clear the download mark with xattr -d com.apple.quarantine airsl. On Windows, SmartScreen warns the first time. The installers download archives themselves, so neither happens.

A shadowed airsl

If you installed airsl with cargo install before, ~/.cargo/bin/airsl may come first on your PATH. The installer warns when that happens. cargo uninstall airsl-cli removes the old copy.

The latest main

To build the newest unreleased code:

$ cargo install --git https://github.com/airsstack/airsl --locked airsl-cli

E. Performance

These numbers come from cargo bench -p airsl on one machine. Treat them as a rough guide to the relative cost of things, not as a guarantee, and measure on your own hardware before relying on them.

Inside a Rust program

WhatWith limitsWithout limits
Building an engine128 µs102 µs
Running a trivial script on an existing engine4.6 µs3.4 µs
Running a script that makes 1000 module calls1073 µs955 µs
Building an engine and running a trivial script136 µs100 µs

Two things stand out.

Reusing an engine is about thirty times faster than building one. That is why chapter 6 recommends keeping an engine for scripts that trust each other.

The limits cost about a quarter of a small script's running time. The instruction limit has to be checked as the script runs. That is the price of being able to stop a script that never ends. You can turn the limits off, but make it a decision rather than a default.

From the command line

CommandTime per run
airsl run on a trivial script3.2 ms
python3 -c 'print("hi")'13.8 ms
sh -c 'echo hi'2.2 ms

Starting a process takes far longer than anything in the first table, so for the command line none of those costs matter. airsl starts about four times faster than Python, and within half again of a bare shell.

F. Lua Functions by Surface

Which of Lua's own libraries a script sees depends on its preset. The preset picks one of three surfaces, and airsl doctor shows the choice on its language: line:

Presetdoctor languageSurface
trustedfullevery safe Lua library, and io and package
confinedrestrictedstring, table, math, utf8, coroutine and the safe parts of os
pureminimalstring, table, math and utf8, with no print, os or coroutine

The listings below show every global and every library function each surface loads. They do not list airsstack, which holds the host modules; see B. Module Reference. For what each preset otherwise allows, see C. Presets at a Glance.

How these listings were made

This script prints the name of every global it finds, and for each library, the names of its functions. It skips _G, arg and airsstack. It is the file surfaces.lua, shown here as it is:

local skip = { _G = true, airsstack = true, arg = true }
local names = {}
for k in pairs(_G) do names[#names + 1] = k end
table.sort(names)
local base, libs = {}, {}
for _, k in ipairs(names) do
  local v = _G[k]
  if not skip[k] then
    if type(v) == "table" then
      local fns = {}
      for f in pairs(v) do fns[#fns + 1] = f end
      table.sort(fns)
      libs[#libs + 1] = k .. ": " .. table.concat(fns, " ")
    else
      base[#base + 1] = k
    end
  end
end
local out = "base: " .. table.concat(base, " ") .. "\n" .. table.concat(libs, "\n") .. "\n"
airsstack.stdio.write(out)

It writes through airsstack.stdio.write because that works on every surface. Run it under each preset. The pure run needs --allow-access stdout, because pure starts with no access to standard output:

$ airsl run --policy trusted surfaces.lua
$ airsl run --policy confined surfaces.lua
$ airsl run --policy pure --allow-access stdout surfaces.lua

The listings are that output, unedited. The first line, base:, holds the globals that are not libraries. Every other line is a library name followed by the names found in it.

full (trusted)

base: _VERSION assert collectgarbage dofile error getmetatable ipairs load loadfile next pairs pcall print rawequal rawget rawlen rawset require select setmetatable tonumber tostring type warn xpcall
coroutine: close create isyieldable resume running status wrap yield
io: close flush input lines open output popen read stderr stdin stdout tmpfile type write
math: abs acos asin atan atan2 ceil cos cosh deg exp floor fmod frexp huge ldexp log log10 max maxinteger min mininteger modf pi pow rad random randomseed sin sinh sqrt tan tanh tointeger type ult
os: clock date difftime execute exit getenv remove rename setlocale time tmpname
package: config cpath loaded loadlib path preload searchers searchpath
string: byte char dump find format gmatch gsub len lower match pack packsize rep reverse sub unpack upper
table: concat insert move pack remove sort unpack
utf8: char charpattern codepoint codes len offset

restricted (confined)

base: _VERSION assert collectgarbage error getmetatable ipairs next pairs pcall print rawequal rawget rawlen rawset require select setmetatable tonumber tostring type warn xpcall
coroutine: close create isyieldable resume running status wrap yield
math: abs acos asin atan atan2 ceil cos cosh deg exp floor fmod frexp huge ldexp log log10 max maxinteger min mininteger modf pi pow rad random randomseed sin sinh sqrt tan tanh tointeger type ult
os: clock date difftime time
string: byte char dump find format gmatch gsub len lower match pack packsize rep reverse sub unpack upper
table: concat insert move pack remove sort unpack
utf8: char charpattern codepoint codes len offset

minimal (pure)

base: _VERSION assert collectgarbage error getmetatable ipairs next pairs pcall rawequal rawget rawlen rawset require select setmetatable tonumber tostring type warn xpcall
math: abs acos asin atan atan2 ceil cos cosh deg exp floor fmod frexp huge ldexp log log10 max maxinteger min mininteger modf pi pow rad random randomseed sin sinh sqrt tan tanh tointeger type ult
string: byte char dump find format gmatch gsub len lower match pack packsize rep reverse sub unpack upper
table: concat insert move pack remove sort unpack
utf8: char charpattern codepoint codes len offset

Two entries in the minimal listing are not Lua's own:

  • require is present, but only as a stub. Unless you grant the require kind of host access, pure puts a function there that refuses every call except require("airsstack") with require denied. Grant it, and require loads files from the script's folder, as it does under confined. See Requiring the modules by name.
  • math.randomseed is airsl's own wrapper around Lua's. pure starts every engine with the generator seeded, so math.random repeats from run to run. The wrapper refuses a call with no argument, because that form seeds from the clock; math.randomseed(42) works as usual.