diff --git a/README.md b/README.md index ebd1e9e..541a01a 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,237 @@ -# moon-nix +# moon-nix (`mnix`) -A basic Nix implementation in MoonBit: fetch and install nixpkgs packages from a binary cache (proof of concept) \ No newline at end of file +A proof-of-concept implementation of the **binary-cache side of Nix** in +[MoonBit](https://www.moonbitlang.com) (native backend). It can install a +package from nixpkgs — with its full runtime closure — from + and run it: + +```console +$ mnix install hello +resolving 'hello' via https://hydra.nixos.org/job/nixpkgs/trunk/hello.x86_64-linux/latest-finished +target: /nix/store/sd779x86bjaqxj2lzh2jsir4h0zjz6d1-hello-2.12.3 +closure: 5 paths (all signatures verified) +fetching r3hvhzl5fxhrgn0rfy5g7rda17702pj4-glibc-2.44-57 (10416204 bytes, zstd) +... +$ mnix run hello +Hello, world! +``` + +It is **not** a Nix evaluator: it never evaluates nixpkgs, never builds +anything, and has no derivations/garbage collector/sandbox. See +[Limitations](#limitations). + +## What was demonstrated (real run, not mocked) + +On Linux x86_64, against the real cache.nixos.org / hydra.nixos.org: + +* `mnix install hello` → resolved `hello` to + `/nix/store/sd779x86…-hello-2.12.3`, fetched and **ed25519-verified** 5 + narinfos (hello, glibc, libidn2, libunistring, libgcc), downloaded 5 + zstd NARs, verified FileHash + NarHash/NarSize, unpacked them, linked + `bin/hello` into the profile. +* `mnix run hello` → `Hello, world!` (both with the default user-writable + store via a mount namespace, and with a native `/nix/store`). +* `mnix install ripgrep` + `mnix run rg …` works too (closure shares paths + with hello; already-present paths are skipped). + +## Build & usage + +Requires the MoonBit toolchain (`export PATH=$HOME/.moon/bin:$PATH`), a C +compiler, and OpenSSL 3 shared libs (loaded dynamically by +`moonbitlang/async` for HTTPS). + +```sh +moon build --target native --release +# binary: _build/native/release/build/cli/cli.exe (alias it to `mnix`) +moon check && moon test && moon fmt --check # 35+ unit tests +``` + +```text +mnix [--root DIR] [--store DIR] [--channel C] [--system S] [--cache URL] + + install [--no-profile] [--dry-run] -name | -name> + resolve print the store path an attribute maps to + closure print the verified transitive closure + search substring search of the channel's store-path names + list list the profile + remove remove from the profile (store paths are kept; no GC) + env print `export PATH=/bin:$PATH` + run [args…] run a command with the profile on PATH +``` + +* `--root` (default `~/.mnix`): state dir holding `store/`, `profile/`, + `cache/`. +* `--store` (default `/store`): where NARs are unpacked. Use + `--store /nix/store` to install into the real store location. +* `--channel` (default `nixos-unstable`): `nixos-unstable`, + `nixpkgs-unstable` or `nixos-YY.MM` (e.g. `nixos-25.05`). +* `--system` (default: from `uname -m`): e.g. `x86_64-linux`, + `aarch64-linux`. +* `--cache` (default `https://cache.nixos.org`; trusted key is always + `cache.nixos.org-1:6NCHdD59…`). + +### The `/nix/store` problem (read this) + +Binaries in cache.nixos.org have `/nix/store/...` hardcoded (ELF +interpreter, RPATH, script shebangs, strings). They cannot be relocated to +`~/.mnix/store` by simply moving files (real Nix would have to rebuild, or +rewrite hash-bearing paths — which changes the hash). `mnix` therefore +supports two honest modes: + +1. **Native `/nix/store`** (`--store /nix/store`): needs `/nix/store` to be + creatable/writable by the user (root-owned `/nix` created beforehand with + `sudo install -d -o $USER /nix /nix/store`, as multi-user Nix does). + Profile symlinks then just work: `~/.mnix/profile/bin/hello`. +2. **User-writable store + mount namespace** (default `~/.mnix/store`): + `mnix run` executes the command inside `unshare -rm` (unprivileged user + namespace) in which a tmpfs root mirrors `/` via recursive bind mounts + and `` is bind-mounted at `/nix/store`, then `chroot`s into it. No + root required, but it needs unprivileged user namespaces + (`/proc/sys/kernel/unprivileged_userns_clone`/`user.max_user_namespaces`) + and `unshare`, `mount`, `chroot` from util-linux/coreutils. Running + `~/.mnix/profile/bin/hello` *directly* (outside `mnix run`) fails unless + `/nix/store` happens to contain the same paths. (`proot`/`bwrap` would be + alternatives; bwrap did not work in the development sandbox, which is why + the raw `unshare` route was used.) + +In the development sandbox both modes worked (the sandbox user could create +`/nix/store`). + +## How name → store path resolution works (and why) + +Nix attribute → store path normally requires evaluating nixpkgs +(`nix-instantiate` + output hashing), which is out of scope. Two options +were investigated: + +* **`https://channels.nixos.org//store-paths.xz`** — a plain list + of *every* store path of the channel (232k lines for nixos-unstable). It + has no attribute names and, crucially, **mixes all platforms**: the same + `hello-…` name appears with several hashes (x86_64-linux, aarch64-linux, + darwin, …) and there is no way to tell which is which without downloading. + Good for *search* (names), unreliable for *install*. +* **Hydra's JSON API** — `https://hydra.nixos.org/job///./latest-finished` + with `Accept: application/json` returns the exact `out` store path of the + latest successful build of that attribute for that system. Everything + Hydra built is in cache.nixos.org. Mapping used: + `nixos-unstable|nixpkgs-unstable` → `nixpkgs/trunk` job `.`; + `nixos-YY.MM` → `nixos/release-YY.MM` job `nixpkgs..`. + +So: **`install ` / `resolve ` use Hydra** (exact, per-platform, +fails loudly if there is no successful build), **`search` uses +store-paths.xz** (downloaded once, decompressed with the pure-MoonBit xz +decoder, cached under `/cache`), and `install /nix/store/-name` +or `-name` bypasses resolution entirely. Caveat: Hydra's +`latest-finished` is the newest build in the jobset, which can be newer than +the current channel revision — it is not pinned to a channel commit. (A +fuller implementation would pin to the channel's evaluation id.) + +## Architecture + +```text + src/ + store nixbase32, sha256 helpers, StorePath parse/validate, NixError + narinfo .narinfo parser (StorePath, URL, Compression, FileHash, FileSize, + NarHash, NarSize, References, Deriver, Sig*, CA) + sign ed25519 verification of narinfo fingerprints + "1;;;;" + nar NAR reader/writer (regular, executable, symlink, directory) + cache HTTP(S) client, narinfo fetch+verify, NAR download, xz/zstd + decompression, FileHash/NarHash/size verification + closure transitive closure over References (deps-first order) + installer atomic unpack of a NAR tree into the store (tmp dir + rename) + resolve channel→Hydra job URLs, Hydra JSON parsing, store-paths search + profile profile dir with bin/ symlinks + manifest (list/add/remove) + cli `mnix` (argparse, config, commands, `run` namespace wrapper) +``` + +Pure logic (store, narinfo, sign, nar, closure, resolve, manifest) is +separated from I/O (cache, installer, profile, cli) and unit-tested. + +Reused mooncakes packages (all checked for the native backend): + +| need | package | notes | +| --- | --- | --- | +| HTTPS client, fs, process | `moonbitlang/async` 0.22.10 | TLS via dlopen'd OpenSSL; no redirect following (done manually), fs `write_file` fsyncs by default (disabled per file for NAR unpack) | +| sha256 | `moonbitlang/x` (crypto) 0.5.9 | | +| ed25519 | `hustcer/ed25519` 0.6.2 | pure MoonBit, "not audited, not constant-time" per its README — fine for *verification* of public data, noted | +| xz / LZMA2 | `lin2077-zeming/moonxz` 0.4.6 | pure MoonBit; read-only use | +| zstd | `gaato/zstd` 0.6.1 | pure MoonBit decoder | +| base64, argparse, json, utf8, buffer | `moonbitlang/core` | | + +cache.nixos.org currently serves **zstd** NARs for new paths (xz for some +older ones); both are supported. Other compressions (`bzip2`, …) fail loudly +with `unsupported`. + +### Verification chain (no silent fallbacks) + +1. narinfo parsed strictly (malformed lines/duplicate keys → error); the + StorePath hash must equal the requested hash. +2. Signature must verify under a trusted key (fails if absent, from an + unknown key, or invalid). Fingerprint covers path, NarHash, NarSize and + references, so references/closure edges are authenticated. +3. Compressed download: FileHash (sha256, nixbase32) and FileSize. +4. Decompressed NAR: NarSize and NarHash. +5. NAR parse is strict: names validated (no `/`, `.`, `..`), entries must be + strictly sorted, padding must be zero, no trailing bytes. +6. Missing closure members, HTTP errors, unknown compression, unwritable + store → hard error with a message; exit status 1. + +Unit tests include a **real** cache.nixos.org narinfo whose signature +verifies against the real public key (and fail when the path, size or +references are tampered), real xz/zstd outputs produced by the reference +`xz`/`zstd` tools, nixbase32 vectors (SHA-256 of the empty string, etc.), +NAR round trips, and real symlink/exec-bit unpacking. + +## Limitations + +* **No evaluator**: attribute resolution is Hydra/`store-paths.xz` + metadata only. Only attributes Hydra builds (nixpkgs `release.nix` jobs, + i.e. mostly top-level packages) resolve. `search` is by store-path name + and can't tell platforms apart. No `nix-env -qaP`-style description search. +* **Store path rewriting/relocation is impossible** (hash-bearing paths); + hence the `/nix/store` modes above. `mnix run` needs Linux user namespaces. +* **Linux only** in practice (the namespace wrapper; the cache client itself + is portable). `--system` can select e.g. `aarch64-linux` metadata but the + result can only run on that architecture. +* NARs are handled **in memory**; limited to < 2 GiB per NAR (the + `moonxz`/`zstd` APIs use `Int32` sizes). Large paths (e.g. big toolchains) + need a streaming design. +* Downloads are **sequential**, un-resumable, no retries, no progress bar, + no `Content-Length`/proxy handling. +* No store database (`/nix/var/nix/db`): no registration of valid paths, + references, or deriver; no `nix-store -q`; no garbage collector (`remove` + only deletes profile links); store files are chmod 0444/0555, directories + 0755 (real Nix makes them read-only and normalizes mtime to 1). +* The ed25519 implementation is not constant-time (irrelevant for verifying + public signatures). Only the NAR hash/signature are trusted — there is no + content-addressed (CA) path verification, no `.narinfo` `CA:` handling + beyond parsing it. +* Profile = a manifest + symlinks into `bin/` only (no `share/`, no + generations/rollback, no `nix profile` JSON format). +* `install ` can pick a build newer than the channel revision. +* Only the `out` output of an attribute is installed (not `man`, `dev`). + +## What a fuller implementation would need + +* A Nix language parser + lazy evaluator + builtins (`import`, `derivation`, + `fetchurl`, …) and nixpkgs' `lib`/stdenv to compute derivation paths + (ATerm `.drv` serialization, `hashDerivationModulo`, output path hashing) + — then substituting by *computed* path, as `nix-build` does. +* Store DB (SQLite schema), path validity registration, closure queries, + GC roots and garbage collection, locking, `nix-store --verify`. +* Streaming NAR/decompression with parallel, resumable fetches and + retries; `.ls`/`nar listing` and `Range` support; other compressions + (bzip2, brotli); other binary caches/keys; `file://`/`ssh://` stores. +* Real profiles with generations (`nix profile`/`nix-env`), `buildEnv`-style + merged `share`/`lib`, conflict resolution, multiple outputs, `meta`. +* Building (sandboxed builders, namespaces, fixed-output derivations). +* A pinned channel mechanism (channel eval id → exact package set). + +## Stretch goal: Nix expression evaluator + +Not implemented. The binary-cache path was prioritised and an evaluator +subset would not have contributed to the install flow. + +## License + +Apache-2.0. Third-party mooncakes keep their own licenses. diff --git a/src/cache/cache.mbt b/src/cache/cache.mbt index 00f4e6e..214e04e 100644 --- a/src/cache/cache.mbt +++ b/src/cache/cache.mbt @@ -13,7 +13,7 @@ pub fn Cache::new( url~ : String = default_cache_url, keys~ : Array[String] = [@sign.cache_nixos_org_key], ) -> Cache raise @store.NixError { - let trusted_keys = keys.map(fn(k) { @sign.PublicKey::parse(k) }) + let trusted_keys = keys.map(k => @sign.PublicKey::parse(k)) let url = url.trim_end(chars="/").to_owned() { url, trusted_keys, } } diff --git a/src/cache/cache_wbtest.mbt b/src/cache/cache_wbtest.mbt new file mode 100644 index 0000000..14f511a --- /dev/null +++ b/src/cache/cache_wbtest.mbt @@ -0,0 +1,101 @@ +///| +// Produced by the reference tools: `xz -9e` and `zstd -19` over "mnix xz interop vector\n" +let xz_vector : Bytes = b"\xfd\x37\x7a\x58\x5a\x00\x00\x04\xe6\xd6\xb4\x46\x04\xc0\x1b\x17\x21\x01\x1c\x00\x00\x00\x00\x00\x00\x00\x00\x00\x26\x02\x80\x23\x01\x00\x16\x6d\x6e\x69\x78\x20\x78\x7a\x20\x69\x6e\x74\x65\x72\x6f\x70\x20\x76\x65\x63\x74\x6f\x72\x0a\x00\x00\x52\x9c\xd4\x07\xd7\xbc\x89\xa2\x00\x01\x37\x17\xd8\x90\x52\x33\x1f\xb6\xf3\x7d\x01\x00\x00\x00\x00\x04\x59\x5a" + +///| +let zstd_vector : Bytes = b"\x28\xb5\x2f\xfd\x24\x17\xb9\x00\x00\x6d\x6e\x69\x78\x20\x78\x7a\x20\x69\x6e\x74\x65\x72\x6f\x70\x20\x76\x65\x63\x74\x6f\x72\x0a\x14\xec\xed\x50" + +///| +let plain : Bytes = b"mnix xz interop vector\n" + +///| +test "decompress reference xz output" { + assert_eq(decompress("xz", xz_vector), plain) +} + +///| +test "decompress reference zstd output" { + assert_eq(decompress("zstd", zstd_vector), plain) +} + +///| +test "decompress none passes through; unknown fails loudly" { + assert_eq(decompress("none", plain), plain) + assert_true(@store.raises(() => decompress("bzip2", plain))) + assert_true(@store.raises(() => decompress("xz", plain))) // not xz data +} + +///| +fn info_for(raw : Bytes, compression : String) -> @narinfo.NarInfo { + { + store_path: "/nix/store/8padfyi6z9ipfq35j86krpvpvx3j3r3v-demo-1", + url: "nar/x.nar.\{compression}", + compression, + file_hash: @store.sha256_nix32(raw), + file_size: raw.length().to_int64(), + nar_hash: @store.sha256_nix32(plain), + nar_size: plain.length().to_int64(), + references: [], + deriver: None, + sigs: [], + ca: None, + } +} + +///| +test "verify_nar_download accepts consistent download" { + assert_eq(verify_nar_download(info_for(xz_vector, "xz"), xz_vector), plain) + assert_eq( + verify_nar_download(info_for(zstd_vector, "zstd"), zstd_vector), + plain, + ) +} + +///| +test "verify_nar_download rejects tampering" { + let ni = info_for(zstd_vector, "zstd") + // corrupted download bytes -> FileHash mismatch + let bad = Bytes::from_array( + FixedArray::makei(zstd_vector.length(), fn(i) { + if i == zstd_vector.length() - 1 { + (zstd_vector[i].to_int() ^ 1).to_byte() + } else { + zstd_vector[i] + } + }), + ) + assert_true(@store.raises(() => verify_nar_download(ni, bad))) + // wrong NarHash + assert_true( + @store.raises(() => { + verify_nar_download( + { ..ni, nar_hash: @store.sha256_nix32(b"other"), }, + zstd_vector, + ) + }), + ) + // wrong NarSize + assert_true( + @store.raises(() => { + verify_nar_download({ ..ni, nar_size: 3L, }, zstd_vector) + }), + ) + // wrong FileSize + assert_true( + @store.raises(() => { + verify_nar_download({ ..ni, file_size: 3L, }, zstd_vector) + }), + ) +} + +///| +test "redirect location resolution" { + inspect( + resolve_location("https://a.org/x/y", "https://b.org/z"), + content="https://b.org/z", + ) + inspect( + resolve_location("https://a.org/x/y", "/z"), + content="https://a.org/z", + ) +} diff --git a/src/cache/moon.pkg b/src/cache/moon.pkg index faf0613..5ff86ac 100644 --- a/src/cache/moon.pkg +++ b/src/cache/moon.pkg @@ -8,3 +8,9 @@ import { "lin2077-zeming/moonxz/lib" @xz, "gaato/zstd", } + +import { + "experiments/moon-nix/narinfo", +} for "wbtest" + +supported_targets = "+native" diff --git a/src/cli/commands.mbt b/src/cli/commands.mbt index 58c6f11..c20e976 100644 --- a/src/cli/commands.mbt +++ b/src/cli/commands.mbt @@ -6,7 +6,7 @@ fn pname_of(name : String) -> String { if chars[i] == '-' && i + 1 < chars.length() { let n = chars[i + 1] if n >= '0' && n <= '9' { - return name[0:i].to_string() + return name[0:i].to_owned() } } } @@ -23,7 +23,7 @@ async fn resolve_target( return (sp, pname_of(sp.name)) } // "-" base name given directly? - if target.length() > 33 && target[32:33].to_string() == "-" { + if target.length() > 33 && target[32:33].to_owned() == "-" { let sp = @store.StorePath::parse_base(target) return (sp, pname_of(sp.name)) } @@ -237,6 +237,12 @@ async fn cmd_run( None => "" } let extra : Map[String, String] = { "PATH": "\{cfg.profile.dir}/bin:\{path}" } + // The OS spawns argv[0] using *our* PATH, not the child's: resolve + // profile commands to their symlink explicitly. + let candidate = "\{cfg.profile.dir}/bin/\{argv[0]}" + if !argv[0].contains("/") && @installer.lexists(candidate) { + argv[0] = candidate + } try { if cfg.store_dir == @store.default_store_dir { @process.run(argv[0], argv[1:], extra_env=extra) diff --git a/src/cli/config.mbt b/src/cli/config.mbt index d2552e0..f04ca79 100644 --- a/src/cli/config.mbt +++ b/src/cli/config.mbt @@ -25,7 +25,7 @@ async fn detect_system() -> String raise @store.NixError { if code != 0 { raise Io("uname -m exited with \{code}") } - let arch = out.text().trim().to_string() catch { + let arch = out.text().trim().to_owned() catch { e => raise Io("decoding uname output: \{e}") } match arch { @@ -49,7 +49,7 @@ async fn load_config(m : @argparse.Matches) -> Config raise @store.NixError { } } let store_dir = match opt(m, "store") { - Some(s) => s.trim_end(chars="/").to_string() + Some(s) => s.trim_end(chars="/").to_owned() None => "\{root}/store" } let channel = @resolve.Channel::parse(opt(m, "channel").unwrap()) diff --git a/src/cli/main.mbt b/src/cli/main.mbt index de13e49..21a19a8 100644 --- a/src/cli/main.mbt +++ b/src/cli/main.mbt @@ -93,7 +93,7 @@ fn build_command() -> @argparse.Command { positionals=[ PositionArg( "command", - num_args=@argparse.ValueRange::new(lower=1), + num_args=@argparse.ValueRange(lower=1), allow_hyphen_values=true, ), ], @@ -107,7 +107,7 @@ async fn run_cli() -> Int32 { // `run` takes arbitrary trailing arguments: split argv at the subcommand // so flags meant for the child are not interpreted by mnix. let argv = @env.args() - let args = argv[1:].to_array() + let args = argv[1:].to_owned() let mut run_tail : Array[String]? = None let mut head = args for i in 0.. Int32 { } } if ok { - head = args[0:i + 1].to_array() - run_tail = Some(args[i + 1:].to_array()) + head = args[0:i + 1].to_owned() + run_tail = Some(args[i + 1:].to_owned()) } break } diff --git a/src/cli/moon.pkg b/src/cli/moon.pkg index c271c70..5171aee 100644 --- a/src/cli/moon.pkg +++ b/src/cli/moon.pkg @@ -10,7 +10,6 @@ import { "moonbitlang/core/argparse", "moonbitlang/core/env", "moonbitlang/core/encoding/utf8", - "moonbitlang/async", "moonbitlang/async/fs", "moonbitlang/async/process", "lin2077-zeming/moonxz/lib" @xz, diff --git a/src/installer/installer.mbt b/src/installer/installer.mbt index 3f0871f..d315109 100644 --- a/src/installer/installer.mbt +++ b/src/installer/installer.mbt @@ -17,6 +17,7 @@ async fn write_node(path : String, node : @nar.Node) -> Unit { path, contents, create_mode=CreateNew, + sync=NoSync, permission=if executable { 0o555 } else { 0o444 }, ) Symlink(target~) => @fs.symlink(target~, path)