Skip to main content
KRAIT

Narsil: The Rust Security NIF

How Narsil — the Rust NIF at the heart of KRAIT's security — performs AST analysis, integrates with the BEAM, and enforces the seven rules.

Why Rust

KRAIT's security analyzer must be fast, memory-safe, and impossible for the host runtime to corrupt. Rust satisfies all three requirements. There are no garbage collection pauses during analysis, no null pointer exceptions, and no buffer overflows. The type system guarantees at compile time that Narsil will not crash the BEAM with a segfault.

Performance matters because every piece of generated code must be analyzed before execution. In a self-evolving agent that may produce dozens of candidate modules per evolution cycle, the analyzer is on the critical path. Narsil typically completes a full seven-rule analysis pass in under 2 milliseconds for a standard module.

How the NIF Integrates with the BEAM

Narsil is compiled as a Rust NIF (Native Implemented Function) using the rustler crate. It exposes a small API surface to the Elixir side: Narsil.validate/1 takes a binary containing Elixir source code and returns either {:ok, :safe} or {:error, violations} where violations is a list of rule IDs and descriptions.

The NIF is loaded once at application startup and runs on the BEAM's dirty CPU scheduler to avoid blocking normal Erlang process scheduling. Long-running analyses are automatically yielded to prevent scheduler starvation. From the Elixir side, calling Narsil feels like calling any other function — the Rust boundary is invisible.

What Narsil Validates

Narsil performs a multi-stage analysis pipeline. First, it parses the input into an Elixir AST using a Rust-native parser. Then it runs each of the seven KRAIT rules as independent analysis passes over the tree. Each pass maintains its own state — KRAIT-003 and KRAIT-004 carry taint maps, while KRAIT-006 carries a set of protected paths.

If any pass produces a violation, the entire module is rejected. There is no partial approval. Narsil returns all violations found so that the evolution system can learn from the rejection and produce a compliant candidate on the next iteration.

Immutability of Narsil Itself

Narsil is compiled ahead of time and shipped as a shared library. It is not interpreted, not JIT-compiled, and not modifiable at runtime. KRAIT-006 explicitly protects the path where the NIF binary resides. The agent cannot rewrite the analyzer any more than it can rewrite the CPU.