From fa7016433651271044db0dde8133db6fad4933d5 Mon Sep 17 00:00:00 2001 From: V G Date: Tue, 24 Nov 2026 22:12:02 +0000 Subject: [PATCH] mnix: Nix binary-cache client PoC in MoonBit (install hello from cache.nixos.org) (#1) --- .gitignore | 4 + README.md | 273 ++++++++++++++++++++++++++++- moon.mod | 25 +++ src/cache/cache.mbt | 168 ++++++++++++++++++ src/cache/cache_wbtest.mbt | 101 +++++++++++ src/cache/moon.pkg | 16 ++ src/cache/pkg.generated.mbti | 32 ++++ src/cli/commands.mbt | 259 +++++++++++++++++++++++++++ src/cli/config.mbt | 72 ++++++++ src/cli/main.mbt | 197 +++++++++++++++++++++ src/cli/moon.pkg | 20 +++ src/cli/pkg.generated.mbti | 12 ++ src/closure/closure.mbt | 46 +++++ src/closure/closure_wbtest.mbt | 69 ++++++++ src/closure/moon.pkg | 8 + src/closure/pkg.generated.mbti | 18 ++ src/installer/installer.mbt | 77 ++++++++ src/installer/installer_wbtest.mbt | 42 +++++ src/installer/moon.pkg | 9 + src/installer/pkg.generated.mbti | 22 +++ src/nar/moon.pkg | 5 + src/nar/nar.mbt | 246 ++++++++++++++++++++++++++ src/nar/nar_wbtest.mbt | 72 ++++++++ src/nar/pkg.generated.mbti | 26 +++ src/narinfo/moon.pkg | 4 + src/narinfo/narinfo.mbt | 103 +++++++++++ src/narinfo/narinfo_wbtest.mbt | 58 ++++++ src/narinfo/pkg.generated.mbti | 32 ++++ src/profile/moon.pkg | 10 ++ src/profile/pkg.generated.mbti | 35 ++++ src/profile/profile.mbt | 175 ++++++++++++++++++ src/profile/profile_wbtest.mbt | 50 ++++++ src/resolve/moon.pkg | 4 + src/resolve/pkg.generated.mbti | 32 ++++ src/resolve/resolve.mbt | 183 +++++++++++++++++++ src/resolve/resolve_wbtest.mbt | 56 ++++++ src/sign/moon.pkg | 7 + src/sign/pkg.generated.mbti | 27 +++ src/sign/sign.mbt | 88 ++++++++++ src/sign/sign_wbtest.mbt | 57 ++++++ src/store/error.mbt | 32 ++++ src/store/hash.mbt | 36 ++++ src/store/moon.pkg | 3 + src/store/nixbase32.mbt | 74 ++++++++ src/store/path.mbt | 100 +++++++++++ src/store/pkg.generated.mbti | 55 ++++++ src/store/store.mbt | 4 + src/store/store_wbtest.mbt | 70 ++++++++ 48 files changed, 3112 insertions(+), 2 deletions(-) create mode 100644 .gitignore create mode 100644 moon.mod create mode 100644 src/cache/cache.mbt create mode 100644 src/cache/cache_wbtest.mbt create mode 100644 src/cache/moon.pkg create mode 100644 src/cache/pkg.generated.mbti create mode 100644 src/cli/commands.mbt create mode 100644 src/cli/config.mbt create mode 100644 src/cli/main.mbt create mode 100644 src/cli/moon.pkg create mode 100644 src/cli/pkg.generated.mbti create mode 100644 src/closure/closure.mbt create mode 100644 src/closure/closure_wbtest.mbt create mode 100644 src/closure/moon.pkg create mode 100644 src/closure/pkg.generated.mbti create mode 100644 src/installer/installer.mbt create mode 100644 src/installer/installer_wbtest.mbt create mode 100644 src/installer/moon.pkg create mode 100644 src/installer/pkg.generated.mbti create mode 100644 src/nar/moon.pkg create mode 100644 src/nar/nar.mbt create mode 100644 src/nar/nar_wbtest.mbt create mode 100644 src/nar/pkg.generated.mbti create mode 100644 src/narinfo/moon.pkg create mode 100644 src/narinfo/narinfo.mbt create mode 100644 src/narinfo/narinfo_wbtest.mbt create mode 100644 src/narinfo/pkg.generated.mbti create mode 100644 src/profile/moon.pkg create mode 100644 src/profile/pkg.generated.mbti create mode 100644 src/profile/profile.mbt create mode 100644 src/profile/profile_wbtest.mbt create mode 100644 src/resolve/moon.pkg create mode 100644 src/resolve/pkg.generated.mbti create mode 100644 src/resolve/resolve.mbt create mode 100644 src/resolve/resolve_wbtest.mbt create mode 100644 src/sign/moon.pkg create mode 100644 src/sign/pkg.generated.mbti create mode 100644 src/sign/sign.mbt create mode 100644 src/sign/sign_wbtest.mbt create mode 100644 src/store/error.mbt create mode 100644 src/store/hash.mbt create mode 100644 src/store/moon.pkg create mode 100644 src/store/nixbase32.mbt create mode 100644 src/store/path.mbt create mode 100644 src/store/pkg.generated.mbti create mode 100644 src/store/store.mbt create mode 100644 src/store/store_wbtest.mbt diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..756aea3 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +_build/ +.context/ +target/ +.mooncakes/ diff --git a/README.md b/README.md index ebd1e9e..7f9aa32 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,272 @@ -# 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). + +## Inspiration: snix (and licensing) + +The layout is inspired by [snix](https://snix.dev/) ([source](https://git.snix.dev/snix/snix)), +the Rust re-implementation of Nix, in particular its `nix-compat` crate, +which splits Nix's wire/on-disk formats into small independent modules +(`nixbase32`, `store_path`, `narinfo`, `nar`, `nixhash`, `derivation`, …) +separate from the services that use them. Borrowed *ideas*: + +* format handling as pure, individually tested modules (our `store`, + `narinfo`, `nar`, `sign`) kept apart from I/O (`cache`, `installer`, + `profile`, `cli`); +* the store / content-addressed-store split: snix's `castore` stores + NAR *contents* (blobs/directories) separately from Nix's store-path + metadata. `mnix` only has the first, simplest half of that idea: the NAR + is parsed into an in-memory tree (`nar.Node`, comparable to castore's + directory/file/symlink nodes) which the `installer` materialises into a + store dir, so a content-addressed or chunked backend could replace + `installer` without touching the NAR/narinfo/signature code; +* "Nix-compatible surface, different internals" as the goal for a future + evaluator (see below). + +**Licence:** snix's crates are licensed GPL-3.0 (only its protobuf service +definitions are MIT). `mnix` is Apache-2.0, so **no snix code was copied or +translated**; everything here was written from the public Nix formats +(nixbase32, narinfo fingerprints, NAR) and from observing real +cache.nixos.org/Hydra responses. If snix code were ever reused, the +affected packages would have to be relicensed under GPL-3.0. + +## Stretch goal: Nix expression evaluator + +Not implemented (the binary-cache path was prioritised). Design notes for a +future `nixexpr` package, informed by snix's `eval` crate (parser → AST → +bytecode compiler → VM with thunks/upvalues, builtins as a separate +module, an I/O abstraction so evaluation is embeddable and testable): +a lexer/parser for literals, attrsets, lists, `let`, lambdas, string +interpolation; a *lazy* evaluator (thunks, since Nix is lazy and nixpkgs +depends on it); a small `builtins` set behind an I/O trait; tests per +language feature. A tree-walking lazy evaluator would be the realistic +first step; a bytecode VM like snix's is the performance route. + +## License + +Apache-2.0. Third-party mooncakes keep their own licenses. diff --git a/moon.mod b/moon.mod new file mode 100644 index 0000000..4cd1e16 --- /dev/null +++ b/moon.mod @@ -0,0 +1,25 @@ +name = "experiments/moon-nix" + +version = "0.1.0" + +readme = "README.md" + +repository = "https://git.site.latha.org/experiments/moon-nix" + +license = "Apache-2.0" + +keywords = [ "nix", "nixpkgs", "binary-cache" ] + +description = "mnix: a proof-of-concept Nix binary-cache client in MoonBit" + +preferred_target = "native" + +source = "src" + +import { + "moonbitlang/async@0.22.10", + "moonbitlang/x@0.5.9", + "lin2077-zeming/moonxz@0.4.6", + "gaato/zstd@0.6.1", + "hustcer/ed25519@0.6.2", +} diff --git a/src/cache/cache.mbt b/src/cache/cache.mbt new file mode 100644 index 0000000..214e04e --- /dev/null +++ b/src/cache/cache.mbt @@ -0,0 +1,168 @@ +///| +pub let default_cache_url : String = "https://cache.nixos.org" + +///| +/// Binary cache client configuration. +pub(all) struct Cache { + url : String + trusted_keys : Array[@sign.PublicKey] +} + +///| +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(k => @sign.PublicKey::parse(k)) + let url = url.trim_end(chars="/").to_owned() + { url, trusted_keys, } +} + +///| +/// GET a URL, following up to 8 redirects manually. Anything other than a +/// final 200 is an error, except that `allow_404` turns a 404 into `None`. +pub async fn http_get( + url : String, + allow_404~ : Bool = false, + accept_json~ : Bool = false, +) -> Bytes? raise @store.NixError { + let headers : Map[@http.CaseInsensitiveString, String] = Map([]) + if accept_json { + headers["Accept"] = "application/json" + } + let mut cur = url + for _ in 0..<8 { + let (resp, body) = @http.get(cur, headers~) catch { + e => raise Network("GET \{cur} failed: \{e}") + } + let code = resp.code.to_int() + if code == 200 { + return Some(body.binary()) + } + if code == 404 && allow_404 { + return None + } + if code == 301 || code == 302 || code == 303 || code == 307 || code == 308 { + match resp.headers.get("location") { + Some(loc) => { + cur = resolve_location(cur, loc) + continue + } + None => raise Network("GET \{cur}: redirect \{code} without Location") + } + } + raise Network("GET \{cur}: unexpected HTTP status \{code} \{resp.reason}") + } + raise Network("GET \{url}: too many redirects") +} + +///| +fn resolve_location(base : String, loc : String) -> String { + if loc.has_prefix("http://") || loc.has_prefix("https://") { + return loc + } + // absolute-path reference: keep scheme://host from base + let scheme_end = base.find("://").unwrap() + 3 + let rest = base[scheme_end:] + let host_end = match rest.find("/") { + Some(i) => scheme_end + i + None => base.length() + } + base[0:host_end].to_owned() + loc +} + +///| +/// Fetch and parse `.narinfo`. Returns None when the cache does not +/// have the path (HTTP 404). The signature is verified before returning. +pub async fn Cache::fetch_narinfo( + self : Cache, + hash : String, +) -> @narinfo.NarInfo? raise @store.NixError { + match http_get("\{self.url}/\{hash}.narinfo", allow_404=true) { + None => None + Some(b) => { + let text = @utf8.decode(b) catch { + _ => raise Parse("narinfo for \{hash} is not valid UTF-8") + } + let ni = @narinfo.NarInfo::parse(text) + let sp = @store.StorePath::parse(ni.store_path) + if sp.hash != hash { + raise Verify( + "narinfo for \{hash} describes a different path: \{ni.store_path}", + ) + } + ignore(@sign.verify_narinfo(ni, self.trusted_keys)) + Some(ni) + } + } +} + +///| +/// Decompress according to the narinfo `Compression` field. No fallback: +/// unknown compressions are an error. +pub fn decompress( + compression : String, + data : Bytes, +) -> Bytes raise @store.NixError { + match compression { + "none" => data + "xz" => + @xz.decompress(data) catch { + e => raise Verify("xz decompression failed: \{@debug.to_string(e)}") + } + "zstd" => + @zstd.decompress(data, max_output=0x7fffffff) catch { + e => raise Verify("zstd decompression failed: \{@debug.to_string(e)}") + } + c => raise Unsupported("compression '\{c}' (supported: none, xz, zstd)") + } +} + +///| +/// Download, verify and decompress the NAR for a (verified) narinfo. +/// Checks: FileHash/FileSize of the compressed download (when present), +/// then NarHash/NarSize of the decompressed archive. +pub async fn Cache::fetch_nar( + self : Cache, + ni : @narinfo.NarInfo, +) -> Bytes raise @store.NixError { + let raw = match http_get("\{self.url}/\{ni.url}") { + Some(b) => b + None => raise Network("unreachable") + } + verify_nar_download(ni, raw) +} + +///| +/// Pure verification half of `fetch_nar`, separated for testing. +pub fn verify_nar_download( + ni : @narinfo.NarInfo, + raw : Bytes, +) -> Bytes raise @store.NixError { + if ni.file_hash != "" { + let got = @store.sha256_nix32(raw) + if got != ni.file_hash { + raise Verify( + "\{ni.url}: FileHash mismatch: expected \{ni.file_hash}, got \{got}", + ) + } + } + if ni.file_size != 0L && ni.file_size != raw.length().to_int64() { + raise Verify( + "\{ni.url}: FileSize mismatch: expected \{ni.file_size}, got \{raw.length()}", + ) + } + let nar = decompress(ni.compression, raw) + if nar.length().to_int64() != ni.nar_size { + raise Verify( + "\{ni.url}: NarSize mismatch: expected \{ni.nar_size}, got \{nar.length()}", + ) + } + let got = @store.sha256_nix32(nar) + if got != ni.nar_hash { + raise Verify( + "\{ni.url}: NarHash mismatch: expected \{ni.nar_hash}, got \{got}", + ) + } + nar +} 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 new file mode 100644 index 0000000..5ff86ac --- /dev/null +++ b/src/cache/moon.pkg @@ -0,0 +1,16 @@ +import { + "experiments/moon-nix/store", + "experiments/moon-nix/narinfo", + "experiments/moon-nix/sign", + "moonbitlang/async/http", + "moonbitlang/core/debug", + "moonbitlang/core/encoding/utf8", + "lin2077-zeming/moonxz/lib" @xz, + "gaato/zstd", +} + +import { + "experiments/moon-nix/narinfo", +} for "wbtest" + +supported_targets = "+native" diff --git a/src/cache/pkg.generated.mbti b/src/cache/pkg.generated.mbti new file mode 100644 index 0000000..6ec3d77 --- /dev/null +++ b/src/cache/pkg.generated.mbti @@ -0,0 +1,32 @@ +// Generated using `moon info`, DON'T EDIT IT +package "experiments/moon-nix/cache" + +import { + "experiments/moon-nix/narinfo", + "experiments/moon-nix/sign", + "experiments/moon-nix/store", +} + +// Values +pub fn decompress(String, Bytes) -> Bytes raise @store.NixError + +pub let default_cache_url : String + +pub async fn http_get(String, allow_404? : Bool, accept_json? : Bool) -> Bytes? raise @store.NixError + +pub fn verify_nar_download(@narinfo.NarInfo, Bytes) -> Bytes raise @store.NixError + +// Errors + +// Types and methods +pub(all) struct Cache { + url : String + trusted_keys : Array[@sign.PublicKey] +} +pub async fn Cache::fetch_nar(Self, @narinfo.NarInfo) -> Bytes raise @store.NixError +pub async fn Cache::fetch_narinfo(Self, String) -> @narinfo.NarInfo? raise @store.NixError +pub fn Cache::new(url? : String, keys? : Array[String]) -> Self raise @store.NixError + +// Type aliases + +// Traits diff --git a/src/cli/commands.mbt b/src/cli/commands.mbt new file mode 100644 index 0000000..c20e976 --- /dev/null +++ b/src/cli/commands.mbt @@ -0,0 +1,259 @@ +///| +/// pname from a store-path name: everything before the first "-". +fn pname_of(name : String) -> String { + let chars = name.to_array() + for i in 0..= '0' && n <= '9' { + return name[0:i].to_owned() + } + } + } + name +} + +///| +async fn resolve_target( + cfg : Config, + target : String, +) -> (@store.StorePath, String) raise @store.NixError { + if target.has_prefix("/") { + let sp = @store.StorePath::parse(target) + return (sp, pname_of(sp.name)) + } + // "-" base name given directly? + if target.length() > 33 && target[32:33].to_owned() == "-" { + let sp = @store.StorePath::parse_base(target) + return (sp, pname_of(sp.name)) + } + let url = cfg.channel.job_url(target, cfg.system) + eprintln("resolving '\{target}' via \{url}") + let body = match @cache.http_get(url, allow_404=true, accept_json=true) { + Some(b) => b + None => + raise Network( + "attribute '\{target}' has no successful \{cfg.system} build in \{cfg.channel.name} (Hydra \{cfg.channel.project}/\{cfg.channel.jobset})", + ) + } + let text = @utf8.decode(body) catch { + _ => raise Parse("Hydra response is not UTF-8") + } + let (path, _) = @resolve.parse_hydra_build(text) + (@store.StorePath::parse(path), target) +} + +///| +async fn cmd_resolve( + cfg : Config, + target : String, +) -> Unit raise @store.NixError { + let (sp, _) = resolve_target(cfg, target) + println(sp.logical()) +} + +///| +async fn fetch_closure( + cfg : Config, + sp : @store.StorePath, +) -> Array[@narinfo.NarInfo] raise @store.NixError { + @closure.compute([sp.base_name()], async fn( + h, + ) -> @narinfo.NarInfo? raise @store.NixError { + cfg.cache.fetch_narinfo(h) + }) +} + +///| +async fn cmd_closure( + cfg : Config, + target : String, +) -> Unit raise @store.NixError { + let (sp, _) = resolve_target(cfg, target) + let c = fetch_closure(cfg, sp) + let mut total = 0L + for ni in c { + total += ni.nar_size + println("\{ni.store_path} \{ni.nar_size} bytes") + } + println("\{c.length()} paths, \{total} bytes (unpacked NAR size)") +} + +///| +async fn install_one( + cfg : Config, + ni : @narinfo.NarInfo, +) -> Bool raise @store.NixError { + let sp = @store.StorePath::parse(ni.store_path) + if @installer.lexists("\{cfg.store_dir}/\{sp.base_name()}") { + return false + } + eprintln( + "fetching \{sp.base_name()} (\{ni.file_size} bytes, \{ni.compression})", + ) + let raw = cfg.cache.fetch_nar(ni) + let node = @nar.parse(raw) + @installer.install_node(cfg.store_dir, sp.base_name(), node) +} + +///| +async fn cmd_install( + cfg : Config, + target : String, + no_profile : Bool, + dry_run : Bool, +) -> Unit raise @store.NixError { + let (sp, name) = resolve_target(cfg, target) + eprintln("target: \{sp.logical()}") + let c = fetch_closure(cfg, sp) + eprintln("closure: \{c.length()} paths (all signatures verified)") + if dry_run { + for ni in c { + println(ni.store_path) + } + return + } + if cfg.store_dir != @store.default_store_dir { + eprintln( + "note: installing into \{cfg.store_dir}; binaries hardcode /nix/store, use `mnix run` (see README)", + ) + } + let mut fresh = 0 + for ni in c { + if install_one(cfg, ni) { + fresh += 1 + } + } + eprintln( + "installed \{fresh} new paths, \{c.length() - fresh} already present", + ) + if !no_profile { + let installed = "\{cfg.store_dir}/\{sp.base_name()}" + let e = cfg.profile.add(name, installed) + println("\{e.name}: \{e.path}") + let bl = e.bins.join(", ") + println("linked: \{bl} -> \{cfg.profile.dir}/bin") + } else { + println("\{cfg.store_dir}/\{sp.base_name()}") + } +} + +///| +async fn cmd_list(cfg : Config) -> Unit raise @store.NixError { + let es = cfg.profile.list() + if es.length() == 0 { + println("(profile \{cfg.profile.dir} is empty)") + } + for e in es { + let bl = e.bins.join(", ") + println("\{e.name}\t\{e.path}\t[\{bl}]") + } +} + +///| +async fn cmd_remove(cfg : Config, name : String) -> Unit raise @store.NixError { + let e = cfg.profile.remove(name) + println( + "removed \{e.name} (store path \{e.path} kept; no garbage collector yet)", + ) +} + +///| +fn cmd_env(cfg : Config) -> Unit { + println("export PATH=\"\{cfg.profile.dir}/bin:$PATH\"") +} + +///| +async fn cmd_search(cfg : Config, term : String) -> Unit { + let cache_dir = "\{cfg.root}/cache" + let cache_file = "\{cache_dir}/\{cfg.channel.name}-store-paths.txt" + let text = if @installer.lexists(cache_file) { + eprintln("using cached \{cache_file} (delete it to refresh)") + @utf8.decode(@fs.read_file(cache_file).binary()) + } else { + let url = "\{cfg.channel.releases_url}/store-paths.xz" + eprintln("downloading \{url}") + let raw = match @cache.http_get(url) { + Some(b) => b + None => raise @store.Network("unreachable") + } + eprintln("decompressing \{raw.length()} bytes of xz") + let data = @xz.decompress(raw) catch { + _ => raise @store.Verify("store-paths.xz failed to decompress") + } + let text = @utf8.decode(data) + @fs.mkdir(cache_dir, recursive=true, allow_exist=true) + @fs.write_file(cache_file, text, create_mode=CreateOrTruncate) + text + } + let paths = @resolve.parse_store_paths(text) + let res = @resolve.search(paths, term) + let mut n = 0 + for r in res { + if n >= 50 { + println("... (\{res.length() - 50} more)") + break + } + println("\{r.0}\t(\{r.1} path(s) across platforms)") + n += 1 + } + if res.length() == 0 { + println("no store path names contain '\{term}'") + } +} + +///| +/// Shell used to make `` appear at /nix/store inside a private +/// user+mount namespace (no root needed): build a tmpfs root that mirrors +/// the real root via recursive bind mounts, bind the store at /nix/store, +/// chroot into it. +let run_script : String = + #|set -e + #|STORE="$1"; shift + #|R=$(mktemp -d "${TMPDIR:-/tmp}/mnix-root.XXXXXX") + #|mount -t tmpfs none "$R" + #|for d in /*; do + #| n=${d#/} + #| [ "$n" = nix ] && continue + #| if [ -L "$d" ]; then ln -s "$(readlink "$d")" "$R/$n"; continue; fi + #| [ -d "$d" ] || continue + #| mkdir "$R/$n" + #| mount --rbind "$d" "$R/$n" + #|done + #|mkdir -p "$R/nix/store" + #|mount --bind "$STORE" "$R/nix/store" + #|exec chroot "$R" /bin/sh -c 'cd "$0" && exec "$@"' "$PWD" "$@" + +///| +async fn cmd_run( + cfg : Config, + argv : Array[String], +) -> Int32 raise @store.NixError { + if argv.length() == 0 { + raise Parse("run: no command given") + } + let path = match @env.get_env_var("PATH") { + Some(p) => p + 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) + } else { + let args = ["-rm", "sh", "-c", run_script, "mnix-run", cfg.store_dir] + for a in argv { + args.push(a) + } + @process.run("unshare", args, extra_env=extra) + } + } catch { + e => raise Io("running \{argv[0]}: \{e}") + } +} diff --git a/src/cli/config.mbt b/src/cli/config.mbt new file mode 100644 index 0000000..f04ca79 --- /dev/null +++ b/src/cli/config.mbt @@ -0,0 +1,72 @@ +///| +/// Resolved global configuration for one invocation. +priv struct Config { + root : String // state dir: /store, /profile, /cache + store_dir : String + profile : @profile.Profile + channel : @resolve.Channel + system : String + cache : @cache.Cache +} + +///| +fn opt(m : @argparse.Matches, key : String) -> String? { + match m.values.get(key) { + Some([v, ..]) => Some(v) + _ => None + } +} + +///| +async fn detect_system() -> String raise @store.NixError { + let (code, out, _) = @process.collect_output("uname", ["-m"]) catch { + e => raise Io("running uname: \{e}") + } + if code != 0 { + raise Io("uname -m exited with \{code}") + } + let arch = out.text().trim().to_owned() catch { + e => raise Io("decoding uname output: \{e}") + } + match arch { + "x86_64" => "x86_64-linux" + "aarch64" => "aarch64-linux" + a => + raise Unsupported( + "unsupported machine architecture '\{a}' (use --system)", + ) + } +} + +///| +async fn load_config(m : @argparse.Matches) -> Config raise @store.NixError { + let root = match opt(m, "root") { + Some(r) => r + None => + match @env.get_env_var("HOME") { + Some(h) => "\{h}/.mnix" + None => raise Io("HOME is not set; pass --root") + } + } + let store_dir = match opt(m, "store") { + Some(s) => s.trim_end(chars="/").to_owned() + None => "\{root}/store" + } + let channel = @resolve.Channel::parse(opt(m, "channel").unwrap()) + let system = match opt(m, "system") { + Some(s) => s + None => detect_system() + } + let cache = match opt(m, "cache") { + Some(u) => @cache.Cache::new(url=u) + None => @cache.Cache::new() + } + { + root, + store_dir, + profile: { dir: "\{root}/profile", }, + channel, + system, + cache, + } +} diff --git a/src/cli/main.mbt b/src/cli/main.mbt new file mode 100644 index 0000000..21a19a8 --- /dev/null +++ b/src/cli/main.mbt @@ -0,0 +1,197 @@ +///| +fn build_command() -> @argparse.Command { + let g : Array[@argparse.OptionArg] = [ + OptionArg( + "root", + long="root", + about="state directory (default: $HOME/.mnix)", + global=true, + ), + OptionArg( + "store", + long="store", + about="store directory (default: /store; /nix/store runs binaries natively)", + global=true, + ), + OptionArg( + "channel", + long="channel", + about="nixos-unstable | nixpkgs-unstable | nixos-YY.MM", + default_values=["nixos-unstable"], + global=true, + ), + OptionArg( + "system", + long="system", + about="platform, e.g. x86_64-linux (default: detected)", + global=true, + ), + OptionArg( + "cache", + long="cache", + about="binary cache URL (default: https://cache.nixos.org)", + global=true, + ), + ] + @argparse.Command( + "mnix", + about="Proof-of-concept Nix binary-cache client written in MoonBit", + options=g, + subcommand_required=true, + subcommands=[ + @argparse.Command( + "install", + about="install a package (attr like `hello`, or /nix/store/-name) with its closure", + flags=[ + FlagArg( + "no-profile", + long="no-profile", + about="do not link into the profile", + ), + FlagArg( + "dry-run", + long="dry-run", + about="only resolve + verify the closure; download nothing", + ), + ], + positionals=[ + PositionArg("target", num_args=@argparse.ValueRange::single()), + ], + ), + @argparse.Command( + "resolve", + about="print the store path of an attribute", + positionals=[ + PositionArg("target", num_args=@argparse.ValueRange::single()), + ], + ), + @argparse.Command( + "closure", + about="print the transitive closure (verified narinfos) of a package", + positionals=[ + PositionArg("target", num_args=@argparse.ValueRange::single()), + ], + ), + @argparse.Command( + "search", + about="search store-path names of the channel (store-paths.xz)", + positionals=[ + PositionArg("term", num_args=@argparse.ValueRange::single()), + ], + ), + @argparse.Command("list", about="list profile contents"), + @argparse.Command("remove", about="remove a package from the profile", positionals=[ + PositionArg("name", num_args=@argparse.ValueRange::single()), + ]), + @argparse.Command( + "env", + about="print a shell snippet that puts the profile on PATH", + ), + @argparse.Command( + "run", + about="run a command with the profile on PATH (inside a /nix/store namespace if needed)", + positionals=[ + PositionArg( + "command", + num_args=@argparse.ValueRange(lower=1), + allow_hyphen_values=true, + ), + ], + ), + ], + ) +} + +///| +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_owned() + let mut run_tail : Array[String]? = None + let mut head = args + for i in 0.. cmd.parse(argv=head + ["--"] + ["_"]) + None => cmd.parse(argv=head) + } + guard m.subcommand is Some((name, sub)) else { + raise Failure("no subcommand") + } + let cfg = load_config(m) + fn arg(k : String) -> String { + opt(sub, k).unwrap() + } + + match name { + "install" => { + cmd_install( + cfg, + arg("target"), + sub.flags.get("no-profile").unwrap_or(false), + sub.flags.get("dry-run").unwrap_or(false), + ) + 0 + } + "resolve" => { + cmd_resolve(cfg, arg("target")) + 0 + } + "closure" => { + cmd_closure(cfg, arg("target")) + 0 + } + "search" => { + cmd_search(cfg, arg("term")) + 0 + } + "list" => { + cmd_list(cfg) + 0 + } + "remove" => { + cmd_remove(cfg, arg("name")) + 0 + } + "env" => { + cmd_env(cfg) + 0 + } + "run" => cmd_run(cfg, run_tail.unwrap()) + _ => raise Failure("unknown command \{name}") + } +} + +///| +async fn main { + let code = run_cli() catch { + e => { + eprintln("mnix: error: \{e}") + 1 + } + } + if code != 0 { + @env.exit(code) + } +} diff --git a/src/cli/moon.pkg b/src/cli/moon.pkg new file mode 100644 index 0000000..5171aee --- /dev/null +++ b/src/cli/moon.pkg @@ -0,0 +1,20 @@ +import { + "experiments/moon-nix/store", + "experiments/moon-nix/narinfo", + "experiments/moon-nix/cache", + "experiments/moon-nix/closure", + "experiments/moon-nix/nar", + "experiments/moon-nix/installer", + "experiments/moon-nix/profile", + "experiments/moon-nix/resolve", + "moonbitlang/core/argparse", + "moonbitlang/core/env", + "moonbitlang/core/encoding/utf8", + "moonbitlang/async/fs", + "moonbitlang/async/process", + "lin2077-zeming/moonxz/lib" @xz, +} + +supported_targets = "+native" + +pkgtype(kind: "executable") diff --git a/src/cli/pkg.generated.mbti b/src/cli/pkg.generated.mbti new file mode 100644 index 0000000..a8c47de --- /dev/null +++ b/src/cli/pkg.generated.mbti @@ -0,0 +1,12 @@ +// Generated using `moon info`, DON'T EDIT IT +package "experiments/moon-nix/cli" + +// Values + +// Errors + +// Types and methods + +// Type aliases + +// Traits diff --git a/src/closure/closure.mbt b/src/closure/closure.mbt new file mode 100644 index 0000000..e3b7b57 --- /dev/null +++ b/src/closure/closure.mbt @@ -0,0 +1,46 @@ +///| +/// Compute the transitive closure of store paths over `References`. +/// +/// `roots` are `-` base names. `fetch` returns the narinfo for a +/// store hash (or None when the cache lacks it — which is an error here: a +/// closure with a missing member is not installable). Result is ordered +/// dependencies-first (post-order DFS), roots last, each path once. +pub async fn compute( + roots : Array[String], + fetch : async (String) -> @narinfo.NarInfo? raise @store.NixError, +) -> Array[@narinfo.NarInfo] raise @store.NixError { + let done : Map[String, Bool] = Map([]) + let order : Array[@narinfo.NarInfo] = [] + for r in roots { + visit(r, fetch, done, order, 0) + } + order +} + +///| +async fn visit( + base : String, + fetch : async (String) -> @narinfo.NarInfo? raise @store.NixError, + done : Map[String, Bool], + order : Array[@narinfo.NarInfo], + depth : Int32, +) -> Unit raise @store.NixError { + if done.contains(base) { + return + } + done[base] = true // mark first: references may be cyclic only via self + if depth > 10000 { + raise Parse("closure recursion too deep at \{base}") + } + let sp = @store.StorePath::parse_base(base) + let ni = match fetch(sp.hash) { + Some(n) => n + None => raise Network("path \{base} not found in binary cache") + } + for r in ni.references { + if r != base { + visit(r, fetch, done, order, depth + 1) + } + } + order.push(ni) +} diff --git a/src/closure/closure_wbtest.mbt b/src/closure/closure_wbtest.mbt new file mode 100644 index 0000000..ab20763 --- /dev/null +++ b/src/closure/closure_wbtest.mbt @@ -0,0 +1,69 @@ +///| +fn mk(base : String, refs : Array[String]) -> @narinfo.NarInfo { + { + store_path: "/nix/store/\{base}", + url: "nar/x.nar.xz", + compression: "xz", + file_hash: "", + file_size: 0L, + nar_hash: "sha256:x", + nar_size: 1L, + references: refs, + deriver: None, + sigs: [], + ca: None, + } +} + +///| +let a : String = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa-a-1" + +///| +let b : String = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb-b-1" + +///| +let c : String = "cccccccccccccccccccccccccccccccc-c-1" + +///| +let d : String = "dddddddddddddddddddddddddddddddd-d-1" + +///| +fn graph() -> Map[String, @narinfo.NarInfo] { + // a -> b, c ; b -> c, self ; c -> (none) + { + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa": mk(a, [b, c]), + "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb": mk(b, [c, b]), + "cccccccccccccccccccccccccccccccc": mk(c, []), + "dddddddddddddddddddddddddddddddd": mk(d, [ + "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee-e-1", + ]), + } +} + +///| +async test "closure is dependency-ordered and deduplicated" { + let g = graph() + let calls = Ref(0) + let r = compute([a], fn(h) { + calls.val += 1 + g.get(h) + }) + assert_eq(r.map(fn(n) { n.store_path }), [ + "/nix/store/\{c}", + "/nix/store/\{b}", + "/nix/store/\{a}", + ]) + assert_eq(calls.val, 3) +} + +///| +async test "missing dependency fails loudly" { + let g = graph() + let mut failed = false + try compute([d], fn(h) { g.get(h) }) catch { + _ => failed = true + } noraise { + _ => () + } + assert_true(failed) +} diff --git a/src/closure/moon.pkg b/src/closure/moon.pkg new file mode 100644 index 0000000..b3fd5f1 --- /dev/null +++ b/src/closure/moon.pkg @@ -0,0 +1,8 @@ +import { + "experiments/moon-nix/store", + "experiments/moon-nix/narinfo", +} + +import { + "moonbitlang/async", +} for "wbtest" diff --git a/src/closure/pkg.generated.mbti b/src/closure/pkg.generated.mbti new file mode 100644 index 0000000..c426b9e --- /dev/null +++ b/src/closure/pkg.generated.mbti @@ -0,0 +1,18 @@ +// Generated using `moon info`, DON'T EDIT IT +package "experiments/moon-nix/closure" + +import { + "experiments/moon-nix/narinfo", + "experiments/moon-nix/store", +} + +// Values +pub async fn compute(Array[String], async (String) -> @narinfo.NarInfo? raise @store.NixError) -> Array[@narinfo.NarInfo] raise @store.NixError + +// Errors + +// Types and methods + +// Type aliases + +// Traits diff --git a/src/installer/installer.mbt b/src/installer/installer.mbt new file mode 100644 index 0000000..d315109 --- /dev/null +++ b/src/installer/installer.mbt @@ -0,0 +1,77 @@ +///| +/// True if something (even a dangling symlink) exists at `path`. +pub async fn lexists(path : String) -> Bool noraise { + try { + ignore(@fs.kind(path, follow_symlink=false)) + true + } catch { + _ => false + } +} + +///| +async fn write_node(path : String, node : @nar.Node) -> Unit { + match node { + File(executable~, contents~) => + @fs.write_file( + path, + contents, + create_mode=CreateNew, + sync=NoSync, + permission=if executable { 0o555 } else { 0o444 }, + ) + Symlink(target~) => @fs.symlink(target~, path) + Directory(entries~) => { + @fs.mkdir(path, permission=0o755) + for e in entries { + let (name, child) = e + write_node("\{path}/\{name}", child) + } + } + } +} + +///| +/// Unpack a parsed NAR as `/` atomically: everything is +/// written to a private temp directory inside the store dir (same +/// filesystem) and then `rename(2)`d into place. Returns true if the path +/// was newly installed, false if it was already present (left untouched). +pub async fn install_node( + store_dir : String, + base : String, + node : @nar.Node, +) -> Bool raise @store.NixError { + // Validate the base name so we never write outside the store dir. + ignore(@store.StorePath::parse_base(base, store_dir~)) + let target = "\{store_dir}/\{base}" + if lexists(target) { + return false + } + try { + @fs.mkdir(store_dir, permission=0o755, recursive=true, allow_exist=true) + let tmp = "\{store_dir}/.tmp-install-\{base}" + if lexists(tmp) { + remove_tree(tmp) + } + write_node(tmp, node) + @fs.rename(tmp, target) + true + } catch { + e => raise Io("installing \{target}: \{e}") + } +} + +///| +/// Remove a tree, fixing permissions first (store files are read-only). +pub async fn remove_tree(path : String) -> Unit { + match @fs.kind(path, follow_symlink=false) { + Directory => { + @fs.chmod(path, 0o755) + for name in @fs.readdir(path, include_hidden=true) { + remove_tree("\{path}/\{name}") + } + @fs.rmdir(path) + } + _ => @fs.remove(path) + } +} diff --git a/src/installer/installer_wbtest.mbt b/src/installer/installer_wbtest.mbt new file mode 100644 index 0000000..70ecf7e --- /dev/null +++ b/src/installer/installer_wbtest.mbt @@ -0,0 +1,42 @@ +///| +async test "unpack NAR tree: contents, exec bits, symlinks, atomic rename" { + let root = @fs.tmpdir(prefix="mnix-test-") + let node : @nar.Node = Directory(entries=[ + ( + "bin", + Directory(entries=[ + ("run", File(executable=true, contents=b"#!/bin/sh\necho ok\n")), + ("run-link", Symlink(target="run")), + ]), + ), + ("data", File(executable=false, contents=b"hello")), + ]) + let base = "8padfyi6z9ipfq35j86krpvpvx3j3r3v-demo-1.0" + let store = "\{root}/store" + assert_true(install_node(store, base, node)) + let p = "\{store}/\{base}" + assert_true(@fs.can_execute("\{p}/bin/run")) + assert_true(!@fs.can_execute("\{p}/data")) + assert_eq(@fs.read_file("\{p}/data").text(), "hello") + assert_true(@fs.kind("\{p}/bin/run-link", follow_symlink=false) is SymLink) + assert_eq(@fs.read_file("\{p}/bin/run-link").text(), "#!/bin/sh\necho ok\n") + // second install is a no-op + assert_true(!install_node(store, base, node)) + // no temp leftovers + assert_eq(@fs.readdir(store, include_hidden=true), [base]) + remove_tree(root) +} + +///| +async test "invalid base names are rejected before touching disk" { + let root = @fs.tmpdir(prefix="mnix-test-") + let mut failed = false + try install_node("\{root}/store", "../evil", Directory(entries=[])) catch { + _ => failed = true + } noraise { + _ => () + } + assert_true(failed) + assert_true(!lexists("\{root}/store")) + remove_tree(root) +} diff --git a/src/installer/moon.pkg b/src/installer/moon.pkg new file mode 100644 index 0000000..50f72df --- /dev/null +++ b/src/installer/moon.pkg @@ -0,0 +1,9 @@ +import { + "experiments/moon-nix/store", + "experiments/moon-nix/nar", + "moonbitlang/async/fs", +} + +import { + "moonbitlang/async", +} for "wbtest" diff --git a/src/installer/pkg.generated.mbti b/src/installer/pkg.generated.mbti new file mode 100644 index 0000000..55da589 --- /dev/null +++ b/src/installer/pkg.generated.mbti @@ -0,0 +1,22 @@ +// Generated using `moon info`, DON'T EDIT IT +package "experiments/moon-nix/installer" + +import { + "experiments/moon-nix/nar", + "experiments/moon-nix/store", +} + +// Values +pub async fn install_node(String, String, @nar.Node) -> Bool raise @store.NixError + +pub async fn lexists(String) -> Bool noraise + +pub async fn remove_tree(String) -> Unit + +// Errors + +// Types and methods + +// Type aliases + +// Traits diff --git a/src/nar/moon.pkg b/src/nar/moon.pkg new file mode 100644 index 0000000..c336f5a --- /dev/null +++ b/src/nar/moon.pkg @@ -0,0 +1,5 @@ +import { + "experiments/moon-nix/store", + "moonbitlang/core/encoding/utf8", + "moonbitlang/core/buffer", +} diff --git a/src/nar/nar.mbt b/src/nar/nar.mbt new file mode 100644 index 0000000..c18090c --- /dev/null +++ b/src/nar/nar.mbt @@ -0,0 +1,246 @@ +///| +/// In-memory tree of a NAR (Nix ARchive). Directory entries are kept in the +/// strictly ascending byte order that the NAR format mandates. +#derive(Eq, Debug) +pub(all) enum Node { + File(executable~ : Bool, contents~ : Bytes) + Symlink(target~ : String) + Directory(entries~ : Array[(String, Node)]) +} + +///| +const MAGIC : String = "nix-archive-1" + +///| +// ---------------------------------------------------------------- reader + +///| +priv struct Reader { + data : Bytes + mut pos : Int32 +} + +///| +fn[T] Reader::fail(self : Reader, msg : String) -> T raise @store.NixError { + raise Parse("NAR: \{msg} (at offset \{self.pos})") +} + +///| +fn Reader::read_u64(self : Reader) -> Int32 raise @store.NixError { + if self.pos + 8 > self.data.length() { + self.fail("unexpected end of data reading length") + } + let mut v = 0L + for i in 0..<8 { + v = v | (self.data[self.pos + i].to_int64() << (8 * i)) + } + if v < 0L || v > 0x7fffffffL { + self.fail("length \{v} too large for this implementation (max 2 GiB)") + } + self.pos += 8 + v.to_int() +} + +///| +/// Read a length-prefixed, 8-byte-padded byte string. +fn Reader::read_bytes(self : Reader) -> Bytes raise @store.NixError { + let len = self.read_u64() + let padded = (len + 7) / 8 * 8 + if self.pos + padded > self.data.length() { + self.fail("string of length \{len} runs past end of data") + } + let out = self.data[self.pos:self.pos + len].to_owned() + for i in len.. String raise @store.NixError { + let b = self.read_bytes() + @utf8.decode(b) catch { + _ => self.fail("invalid UTF-8 in name/target") + } +} + +///| +fn Reader::expect(self : Reader, s : String) -> Unit raise @store.NixError { + let got = self.read_str() + if got != s { + self.fail("expected '\{s}', got '\{got}'") + } +} + +///| +/// Byte-wise lexicographic comparison (the order Nix sorts directory entries by). +fn bytes_compare(a : Bytes, b : Bytes) -> Int32 { + let n = if a.length() < b.length() { a.length() } else { b.length() } + for i in 0.. Bool { + n.length() > 0 && + n != "." && + n != ".." && + !n.contains("/") && + !n.contains("\u{0}") +} + +///| +fn Reader::read_node( + self : Reader, + depth : Int32, +) -> Node raise @store.NixError { + if depth > 512 { + self.fail("directory nesting too deep") + } + self.expect("(") + self.expect("type") + let ty = self.read_str() + match ty { + "regular" => { + let mut executable = false + let mut tag = self.read_str() + if tag == "executable" { + executable = true + self.expect("") + tag = self.read_str() + } + if tag != "contents" { + self.fail("expected 'contents', got '\{tag}'") + } + let contents = self.read_bytes() + self.expect(")") + File(executable~, contents~) + } + "symlink" => { + self.expect("target") + let target = self.read_str() + self.expect(")") + Symlink(target~) + } + "directory" => { + let entries : Array[(String, Node)] = [] + let mut prev : String? = None + while true { + let tag = self.read_str() + if tag == ")" { + break + } + if tag != "entry" { + self.fail("expected 'entry' or ')', got '\{tag}'") + } + self.expect("(") + self.expect("name") + let name = self.read_str() + if !valid_entry_name(name) { + self.fail("invalid directory entry name '\{name}'") + } + if prev is Some(p) && + bytes_compare(@utf8.encode(p), @utf8.encode(name)) >= 0 { + self.fail("entries not strictly sorted: '\{p}' before '\{name}'") + } + prev = Some(name) + self.expect("node") + let node = self.read_node(depth + 1) + self.expect(")") + entries.push((name, node)) + } + Directory(entries~) + } + _ => self.fail("unknown node type '\{ty}'") + } +} + +///| +/// Parse a complete NAR. Fails on any malformation, including trailing bytes. +pub fn parse(data : Bytes) -> Node raise @store.NixError { + let r = { data, pos: 0, } + r.expect(MAGIC) + let node = r.read_node(0) + if r.pos != data.length() { + r.fail("trailing garbage after archive") + } + node +} + +///| +// ---------------------------------------------------------------- writer + +///| +fn put_u64(buf : @buffer.Buffer, n : Int32) -> Unit { + let v = n.to_int64() + for i in 0..<8 { + buf.write_byte(((v >> (8 * i)) & 0xffL).to_int().to_byte()) + } +} + +///| +fn put_bytes(buf : @buffer.Buffer, b : BytesView) -> Unit { + put_u64(buf, b.length()) + buf.write_bytesview(b) + let pad = (8 - b.length() % 8) % 8 + for _ in 0.. Unit { + put_bytes(buf, @utf8.encode(s)) +} + +///| +fn put_node(buf : @buffer.Buffer, n : Node) -> Unit { + put_str(buf, "(") + put_str(buf, "type") + match n { + File(executable~, contents~) => { + put_str(buf, "regular") + if executable { + put_str(buf, "executable") + put_str(buf, "") + } + put_str(buf, "contents") + put_bytes(buf, contents) + } + Symlink(target~) => { + put_str(buf, "symlink") + put_str(buf, "target") + put_str(buf, target) + } + Directory(entries~) => { + put_str(buf, "directory") + for e in entries { + let (name, child) = e + put_str(buf, "entry") + put_str(buf, "(") + put_str(buf, "name") + put_str(buf, name) + put_str(buf, "node") + put_node(buf, child) + put_str(buf, ")") + } + } + } + put_str(buf, ")") +} + +///| +/// Serialize a node tree into canonical NAR bytes. +pub fn serialize(n : Node) -> Bytes { + let buf = @buffer.Buffer() + put_str(buf, MAGIC) + put_node(buf, n) + buf.to_bytes() +} diff --git a/src/nar/nar_wbtest.mbt b/src/nar/nar_wbtest.mbt new file mode 100644 index 0000000..fde39f1 --- /dev/null +++ b/src/nar/nar_wbtest.mbt @@ -0,0 +1,72 @@ +///| +fn sample() -> Node { + Directory(entries=[ + ( + "bin", + Directory(entries=[ + ("hello", File(executable=true, contents=b"#!/bin/sh\necho hi\n")), + ("link", Symlink(target="hello")), + ]), + ), + ("empty", File(executable=false, contents=b"")), + ("readme", File(executable=false, contents=b"0123456789")), + ]) +} + +///| +test "roundtrip" { + let n = sample() + let bytes = serialize(n) + assert_eq(bytes.length() % 8, 0) + assert_eq(parse(bytes), n) + assert_eq(serialize(parse(bytes)), bytes) +} + +///| +test "single file roundtrip" { + let n = File(executable=false, contents=b"abc") + assert_eq(parse(serialize(n)), n) +} + +///| +test "known encoding of a regular file" { + // Matches `nix-store --dump` for a 3-byte file "abc" (hand-checked layout). + let b = serialize(File(executable=false, contents=b"abc")) + // magic(8+16) "(" (16) "type"(16) "regular"(16) "contents"(16) data(16) ")"(16) + assert_eq(b.length(), 24 + 16 + 16 + 16 + 16 + 16 + 16) + assert_eq(b[0], b'\x0d') + assert_eq(b[8], b'n') +} + +///| +test "rejects malformations" { + let good = serialize(sample()) + // truncated + assert_true(@store.raises(() => parse(good[0:good.length() - 8].to_owned()))) + // trailing garbage + let trailing = @buffer.Buffer() + trailing.write_bytes(good) + trailing.write_bytes(b"\x00\x00\x00\x00\x00\x00\x00\x00") + assert_true(@store.raises(() => parse(trailing.to_bytes()))) + // bad magic + assert_true(@store.raises(() => parse(b"hello"))) + // unsorted entries + let bad = Directory(entries=[ + ("b", File(executable=false, contents=b"")), + ("a", File(executable=false, contents=b"")), + ]) + assert_true(@store.raises(() => parse(serialize(bad)))) + // path traversal name + let evil = Directory(entries=[("..", File(executable=false, contents=b""))]) + assert_true(@store.raises(() => parse(serialize(evil)))) + let evil2 = Directory(entries=[("a/b", File(executable=false, contents=b""))]) + assert_true(@store.raises(() => parse(serialize(evil2)))) +} + +///| +test "bytewise ordering is lexicographic, not length-first" { + assert_true(bytes_compare(b"hello", b"link") < 0) + assert_true(bytes_compare(b"a", b"ab") < 0) + assert_true(bytes_compare(b"b", b"a") > 0) + assert_eq(bytes_compare(b"x", b"x"), 0) +} diff --git a/src/nar/pkg.generated.mbti b/src/nar/pkg.generated.mbti new file mode 100644 index 0000000..d7a67af --- /dev/null +++ b/src/nar/pkg.generated.mbti @@ -0,0 +1,26 @@ +// Generated using `moon info`, DON'T EDIT IT +package "experiments/moon-nix/nar" + +import { + "experiments/moon-nix/store", + "moonbitlang/core/debug", +} + +// Values +pub fn parse(Bytes) -> Node raise @store.NixError + +pub fn serialize(Node) -> Bytes + +// Errors + +// Types and methods +#derive(Eq, @debug.Debug) +pub(all) enum Node { + File(executable~ : Bool, contents~ : Bytes) + Symlink(target~ : String) + Directory(entries~ : Array[(String, Node)]) +} + +// Type aliases + +// Traits diff --git a/src/narinfo/moon.pkg b/src/narinfo/moon.pkg new file mode 100644 index 0000000..297f88f --- /dev/null +++ b/src/narinfo/moon.pkg @@ -0,0 +1,4 @@ +import { + "experiments/moon-nix/store", + "moonbitlang/core/string", +} diff --git a/src/narinfo/narinfo.mbt b/src/narinfo/narinfo.mbt new file mode 100644 index 0000000..d7c1d9a --- /dev/null +++ b/src/narinfo/narinfo.mbt @@ -0,0 +1,103 @@ +///| +/// A parsed `.narinfo` file as served by a Nix binary cache. +#derive(Eq, Debug) +pub(all) struct NarInfo { + store_path : String // full path, e.g. /nix/store/-hello-2.8.4 + url : String // relative to the cache, e.g. nar/.nar.xz + compression : String // none | xz | zstd | bzip2 ... + file_hash : String // sha256: of the compressed file + file_size : Int64 + nar_hash : String // sha256: of the uncompressed NAR + nar_size : Int64 + references : Array[String] // base names (-), may include self + deriver : String? // base name of the .drv + sigs : Array[String] // name:base64 + ca : String? +} + +///| +fn parse_i64(key : String, v : String) -> Int64 raise @store.NixError { + @string.parse_int64(v) catch { + _ => raise Parse("narinfo: bad integer for \{key}: '\{v}'") + } +} + +///| +/// Parse the text of a narinfo file. Required keys: StorePath, URL, +/// NarHash, NarSize. `References` is optional (omitted when empty). `Compression` defaults to "bzip2" when +/// absent (per the Nix spec); unsupported values fail at decompression time. +/// Duplicate keys (except `Sig`, which may repeat) and malformed lines are +/// errors. +pub fn NarInfo::parse(text : String) -> NarInfo raise @store.NixError { + let seen : Map[String, String] = Map([]) + let sigs : Array[String] = [] + for line in text.split("\n") { + let line = line.trim_end(chars="\r").to_owned() + if line.length() == 0 { + continue + } + // "Key: value", or "Key:" alone when the value is empty (e.g. no references) + let (key, value) = if line.find(": ") is Some(i) { + (line[0:i].to_owned(), line[i + 2:].to_owned()) + } else if line.has_suffix(":") { + (line[0:line.length() - 1].to_owned(), "") + } else { + raise Parse("narinfo: malformed line (no ': '): \{line}") + } + if key == "Sig" { + sigs.push(value) + continue + } + if seen.contains(key) { + raise Parse("narinfo: duplicate key \{key}") + } + seen[key] = value + } + fn req(k : String) -> String raise @store.NixError { + match seen.get(k) { + Some(v) => v + None => raise Parse("narinfo: missing required key \{k}") + } + } + + let store_path = req("StorePath") + // Validate the path shape loudly. + ignore(@store.StorePath::parse(store_path)) + let file_hash = match seen.get("FileHash") { + Some(v) => v + None => "" + } + let file_size = match seen.get("FileSize") { + Some(v) => parse_i64("FileSize", v) + None => 0L + } + let references = match seen.get("References") { + Some(v) => + v + .split(" ") + .filter(fn(s) { s.length() > 0 }) + .map(fn(s) { s.to_owned() }) + .collect() + // cache.nixos.org omits the line entirely when there are no references + None => [] + } + for r in references { + ignore(@store.StorePath::parse_base(r)) + } + { + store_path, + url: req("URL"), + compression: match seen.get("Compression") { + Some(c) => c + None => "bzip2" + }, + file_hash, + file_size, + nar_hash: req("NarHash"), + nar_size: parse_i64("NarSize", req("NarSize")), + references, + deriver: seen.get("Deriver"), + sigs, + ca: seen.get("CA"), + } +} diff --git a/src/narinfo/narinfo_wbtest.mbt b/src/narinfo/narinfo_wbtest.mbt new file mode 100644 index 0000000..a220758 --- /dev/null +++ b/src/narinfo/narinfo_wbtest.mbt @@ -0,0 +1,58 @@ +///| +let hello_narinfo : String = + #|StorePath: /nix/store/8padfyi6z9ipfq35j86krpvpvx3j3r3v-hello-2.8.4 + #|URL: nar/0rn6mlcldbs3x4jwd7j8x2j1xf3v8ydn08icm4by312cw7db8z33.nar.zst + #|Compression: zstd + #|FileHash: sha256:0rvh1h413bl7rl9hbifzvjwjyzfbqy4q969xpg42ns43fajggazs + #|FileSize: 10561 + #|NarHash: sha256:0rn6mlcldbs3x4jwd7j8x2j1xf3v8ydn08icm4by312cw7db8z33 + #|NarSize: 101224 + #|References: 1q857rs68rs3gijls9wdnsjqnwnv5zd8-glibc-2.44-57 w79cl5jdx1hggkmy4miwhb1j9w1pb7qg-gcc-16.2.0-lib + #|Deriver: fwcmbj1s9g7w3ss4nn774dvvq4was180-hello-2.8.4.drv + #|Sig: cache.nixos.org-1:LPtBVTcqdkiUD6vGPmFjn0LEIkg0N5cg7xwbIPa9z9g81p9gUxGJQElBPNDhI6MD0Jt3AyCK5rb1Buy609kXCQ== + #| + +///| +test "parse real hello narinfo" { + let ni = NarInfo::parse(hello_narinfo) + inspect( + ni.store_path, + content="/nix/store/8padfyi6z9ipfq35j86krpvpvx3j3r3v-hello-2.8.4", + ) + inspect(ni.compression, content="zstd") + inspect(ni.file_size, content="10561") + inspect(ni.nar_size, content="101224") + assert_eq(ni.references.length(), 2) + assert_eq(ni.sigs.length(), 1) + assert_eq( + ni.deriver, + Some("fwcmbj1s9g7w3ss4nn774dvvq4was180-hello-2.8.4.drv"), + ) +} + +///| +test "reject malformed narinfo" { + assert_true(@store.raises(() => NarInfo::parse("StorePath /nix/store/x"))) + assert_true(@store.raises(() => NarInfo::parse("URL: a\nURL: b\n"))) + assert_true(@store.raises(() => NarInfo::parse("URL: a\n"))) +} + +///| +test "empty References value" { + let ni = NarInfo::parse( + "StorePath: /nix/store/8padfyi6z9ipfq35j86krpvpvx3j3r3v-x-1\nURL: nar/a.nar.xz\nCompression: xz\nNarHash: sha256:00\nNarSize: 5\nReferences:\n", + ) + assert_eq(ni.references.length(), 0) + let ni2 = NarInfo::parse( + "StorePath: /nix/store/8padfyi6z9ipfq35j86krpvpvx3j3r3v-x-1\nURL: nar/a.nar.xz\nCompression: xz\nNarHash: sha256:00\nNarSize: 5\nReferences: \n", + ) + assert_eq(ni2.references.length(), 0) +} + +///| +test "absent References line means no references (as served by the real cache)" { + let ni = NarInfo::parse( + "StorePath: /nix/store/80v5n8kdscr9r2ls8h72s8ppwmccwrgm-xgcc-16.2.0-libgcc\nURL: nar/a.nar.zst\nCompression: zstd\nNarHash: sha256:00\nNarSize: 5\n", + ) + assert_eq(ni.references.length(), 0) +} diff --git a/src/narinfo/pkg.generated.mbti b/src/narinfo/pkg.generated.mbti new file mode 100644 index 0000000..6aaacb0 --- /dev/null +++ b/src/narinfo/pkg.generated.mbti @@ -0,0 +1,32 @@ +// Generated using `moon info`, DON'T EDIT IT +package "experiments/moon-nix/narinfo" + +import { + "experiments/moon-nix/store", + "moonbitlang/core/debug", +} + +// Values + +// Errors + +// Types and methods +#derive(Eq, @debug.Debug) +pub(all) struct NarInfo { + store_path : String + url : String + compression : String + file_hash : String + file_size : Int64 + nar_hash : String + nar_size : Int64 + references : Array[String] + deriver : String? + sigs : Array[String] + ca : String? +} +pub fn NarInfo::parse(String) -> Self raise @store.NixError + +// Type aliases + +// Traits diff --git a/src/profile/moon.pkg b/src/profile/moon.pkg new file mode 100644 index 0000000..5b0c6b0 --- /dev/null +++ b/src/profile/moon.pkg @@ -0,0 +1,10 @@ +import { + "experiments/moon-nix/store", + "experiments/moon-nix/installer", + "moonbitlang/async/fs", + "moonbitlang/core/encoding/utf8", +} + +import { + "moonbitlang/async", +} for "wbtest" diff --git a/src/profile/pkg.generated.mbti b/src/profile/pkg.generated.mbti new file mode 100644 index 0000000..fcc6e2b --- /dev/null +++ b/src/profile/pkg.generated.mbti @@ -0,0 +1,35 @@ +// Generated using `moon info`, DON'T EDIT IT +package "experiments/moon-nix/profile" + +import { + "experiments/moon-nix/store", + "moonbitlang/core/debug", +} + +// Values +pub fn find_conflict(Array[Entry], String, Array[String]) -> (String, String)? + +pub fn parse_manifest(String) -> Array[Entry] raise @store.NixError + +pub fn serialize_manifest(Array[Entry]) -> String + +// Errors + +// Types and methods +#derive(Eq, @debug.Debug) +pub(all) struct Entry { + name : String + path : String + bins : Array[String] +} + +pub(all) struct Profile { + dir : String +} +pub async fn Profile::add(Self, String, String) -> Entry raise @store.NixError +pub async fn Profile::list(Self) -> Array[Entry] raise @store.NixError +pub async fn Profile::remove(Self, String) -> Entry raise @store.NixError + +// Type aliases + +// Traits diff --git a/src/profile/profile.mbt b/src/profile/profile.mbt new file mode 100644 index 0000000..011d81b --- /dev/null +++ b/src/profile/profile.mbt @@ -0,0 +1,175 @@ +///| +/// One installed package in a profile. +#derive(Eq, Debug) +pub(all) struct Entry { + name : String // user-facing name (e.g. "hello") + path : String // full store path as installed (under the chosen store dir) + bins : Array[String] // executables linked into /bin +} + +///| +/// Manifest format: one line per entry, tab separated: +/// name \t store-path \t comma-separated-bin-names +pub fn parse_manifest(text : String) -> Array[Entry] raise @store.NixError { + let out : Array[Entry] = [] + for line in text.split("\n") { + if line.length() == 0 { + continue + } + let parts = line.split("\t").map(fn(s) { s.to_owned() }).collect() + if parts.length() != 3 { + raise Parse("profile manifest: malformed line '\{line}'") + } + let bins = if parts[2].length() == 0 { + [] + } else { + parts[2].split(",").map(fn(s) { s.to_owned() }).collect() + } + out.push({ name: parts[0], path: parts[1], bins, }) + } + out +} + +///| +pub fn serialize_manifest(entries : Array[Entry]) -> String { + let sb = StringBuilder() + for e in entries { + sb.write_string("\{e.name}\t\{e.path}\t\{e.bins.join(",")}\n") + } + sb.to_string() +} + +///| +/// Which other entry (if any) already owns one of `bins`? +pub fn find_conflict( + entries : Array[Entry], + name : String, + bins : Array[String], +) -> (String, String)? { + for e in entries { + if e.name == name { + continue + } + for b in bins { + if e.bins.contains(b) { + return Some((e.name, b)) + } + } + } + None +} + +///| +pub(all) struct Profile { + dir : String +} + +///| +async fn Profile::read(self : Profile) -> Array[Entry] raise @store.NixError { + let mf = "\{self.dir}/manifest" + if !@installer.lexists(mf) { + return [] + } + let text = @utf8.decode(@fs.read_file(mf).binary()) catch { + e => raise Io("reading \{mf}: \{e}") + } + parse_manifest(text) +} + +///| +pub async fn Profile::list( + self : Profile, +) -> Array[Entry] raise @store.NixError { + self.read() +} + +///| +async fn Profile::write( + self : Profile, + entries : Array[Entry], +) -> Unit raise @store.NixError { + try { + @fs.mkdir(self.dir, recursive=true, allow_exist=true) + @fs.write_file( + "\{self.dir}/manifest.tmp", + serialize_manifest(entries), + create_mode=CreateOrTruncate, + ) + @fs.rename("\{self.dir}/manifest.tmp", "\{self.dir}/manifest", replace=true) + } catch { + e => raise Io("writing profile manifest: \{e}") + } +} + +///| +/// Link `/bin/*` into `/bin`. Re-adding the same name +/// replaces its previous links; a clash with another package's binary fails. +pub async fn Profile::add( + self : Profile, + name : String, + path : String, +) -> Entry raise @store.NixError { + let bindir = "\{path}/bin" + if !@installer.lexists(bindir) { + raise Io("\{path} has no bin/ directory; nothing to link") + } + let bins = @fs.readdir(bindir, sort=true) catch { + e => raise Io("reading \{bindir}: \{e}") + } + if bins.length() == 0 { + raise Io("\{bindir} is empty; nothing to link") + } + let entries = self.read() + match find_conflict(entries, name, bins) { + Some((owner, b)) => + raise Io( + "binary '\{b}' is already provided by '\{owner}' in this profile", + ) + None => () + } + let entry : Entry = { name, path, bins, } + try { + @fs.mkdir("\{self.dir}/bin", recursive=true, allow_exist=true) + // drop old links of the same name that the new version no longer has + for e in entries { + if e.name == name { + for b in e.bins { + @fs.remove("\{self.dir}/bin/\{b}", allow_missing=true) + } + } + } + for b in bins { + @fs.symlink( + target="\{bindir}/\{b}", + "\{self.dir}/bin/\{b}", + force_symlink=true, + ) + } + } catch { + e => raise Io("linking binaries into \{self.dir}/bin: \{e}") + } + let rest = entries.filter(fn(e) { e.name != name }) + rest.push(entry) + self.write(rest) + entry +} + +///| +pub async fn Profile::remove( + self : Profile, + name : String, +) -> Entry raise @store.NixError { + let entries = self.read() + guard entries.iter().find_first(fn(e) { e.name == name }) is Some(entry) else { + raise Io("'\{name}' is not installed in this profile") + } + try { + for b in entry.bins { + @fs.remove("\{self.dir}/bin/\{b}", allow_missing=true) + } + } catch { + e => raise Io("removing links: \{e}") + } + self.write(entries.filter(fn(e) { e.name != name })) + entry +} diff --git a/src/profile/profile_wbtest.mbt b/src/profile/profile_wbtest.mbt new file mode 100644 index 0000000..3f428f4 --- /dev/null +++ b/src/profile/profile_wbtest.mbt @@ -0,0 +1,50 @@ +///| +test "manifest roundtrip" { + let es : Array[Entry] = [ + { name: "hello", path: "/s/aaa-hello-2.8", bins: ["hello"], }, + { name: "coreutils", path: "/s/bbb-coreutils-9", bins: ["ls", "cat"], }, + ] + assert_eq(parse_manifest(serialize_manifest(es)), es) + assert_true(@store.raises(() => parse_manifest("only\ttwo\n"))) +} + +///| +test "conflict detection" { + let es : Array[Entry] = [{ name: "a", path: "/p", bins: ["x", "y"], }] + assert_eq(find_conflict(es, "b", ["y"]), Some(("a", "y"))) + assert_eq(find_conflict(es, "a", ["y"]), None) // upgrade of same name is fine + assert_eq(find_conflict(es, "b", ["z"]), None) +} + +///| +async test "add / list / remove with real symlinks" { + let root = @fs.tmpdir(prefix="mnix-prof-") + let pkg = "\{root}/store/8padfyi6z9ipfq35j86krpvpvx3j3r3v-demo-1" + @fs.mkdir("\{pkg}/bin", recursive=true) + @fs.write_file("\{pkg}/bin/demo", "#!/bin/sh\n", permission=0o755) + let p : Profile = { dir: "\{root}/profile", } + let e = p.add("demo", pkg) + assert_eq(e.bins, ["demo"]) + assert_true( + @fs.kind("\{root}/profile/bin/demo", follow_symlink=false) is SymLink, + ) + assert_eq(p.list().length(), 1) + // re-add is idempotent + ignore(p.add("demo", pkg)) + assert_eq(p.list().length(), 1) + // conflicting package + let pkg2 = "\{root}/store/9padfyi6z9ipfq35j86krpvpvx3j3r3v-other-1" + @fs.mkdir("\{pkg2}/bin", recursive=true) + @fs.write_file("\{pkg2}/bin/demo", "x", permission=0o755) + let mut failed = false + try p.add("other", pkg2) catch { + _ => failed = true + } noraise { + _ => () + } + assert_true(failed) + ignore(p.remove("demo")) + assert_eq(p.list().length(), 0) + assert_true(!@installer.lexists("\{root}/profile/bin/demo")) + @installer.remove_tree(root) +} diff --git a/src/resolve/moon.pkg b/src/resolve/moon.pkg new file mode 100644 index 0000000..076d4c8 --- /dev/null +++ b/src/resolve/moon.pkg @@ -0,0 +1,4 @@ +import { + "experiments/moon-nix/store", + "moonbitlang/core/json", +} diff --git a/src/resolve/pkg.generated.mbti b/src/resolve/pkg.generated.mbti new file mode 100644 index 0000000..108e413 --- /dev/null +++ b/src/resolve/pkg.generated.mbti @@ -0,0 +1,32 @@ +// Generated using `moon info`, DON'T EDIT IT +package "experiments/moon-nix/resolve" + +import { + "experiments/moon-nix/store", + "moonbitlang/core/debug", +} + +// Values +pub fn parse_hydra_build(String) -> (String, String) raise @store.NixError + +pub fn parse_store_paths(String) -> Array[@store.StorePath] raise @store.NixError + +pub fn search(Array[@store.StorePath], String) -> Array[(String, Int32)] + +// Errors + +// Types and methods +#derive(Eq, @debug.Debug) +pub(all) struct Channel { + name : String + project : String + jobset : String + job_prefix : String + releases_url : String +} +pub fn Channel::job_url(Self, String, String) -> String raise @store.NixError +pub fn Channel::parse(String) -> Self raise @store.NixError + +// Type aliases + +// Traits diff --git a/src/resolve/resolve.mbt b/src/resolve/resolve.mbt new file mode 100644 index 0000000..ff211fc --- /dev/null +++ b/src/resolve/resolve.mbt @@ -0,0 +1,183 @@ +///| +/// Where to look up a package attribute on Hydra for a given channel. +#derive(Eq, Debug) +pub(all) struct Channel { + name : String + project : String + jobset : String + job_prefix : String // "" for nixpkgs/trunk, "nixpkgs." for nixos release jobsets + releases_url : String // channel base URL for store-paths.xz +} + +///| +/// Map a channel name to a Hydra jobset. +/// nixos-unstable / nixpkgs-unstable / unstable -> hydra nixpkgs/trunk +/// nixos-YY.MM -> hydra nixos/release-YY.MM +pub fn Channel::parse(name : String) -> Channel raise @store.NixError { + if name == "nixos-unstable" || + name == "nixpkgs-unstable" || + name == "unstable" { + return { + name, + project: "nixpkgs", + jobset: "trunk", + job_prefix: "", + releases_url: "https://channels.nixos.org/\{name}", + } + } + if name.has_prefix("nixos-") { + let ver = name[6:].to_owned() + let ok = ver.length() == 5 && + ver[2:3].to_owned() == "." && + ver.to_array().iter().all(fn(c) { c == '.' || (c >= '0' && c <= '9') }) + if ok { + return { + name, + project: "nixos", + jobset: "release-\{ver}", + job_prefix: "nixpkgs.", + releases_url: "https://channels.nixos.org/\{name}", + } + } + } + raise Parse( + "unknown channel '\{name}' (expected nixos-unstable, nixpkgs-unstable or nixos-YY.MM)", + ) +} + +///| +/// Hydra URL returning the JSON of the latest successful build of `attr`. +pub fn Channel::job_url( + self : Channel, + attr : String, + system : String, +) -> String raise @store.NixError { + if attr.length() == 0 { + raise Parse("empty package attribute") + } + for c in attr { + let ok = (c >= 'a' && c <= 'z') || + (c >= 'A' && c <= 'Z') || + (c >= '0' && c <= '9') || + c == '_' || + c == '-' || + c == '.' || + c == '+' + if !ok { + raise Parse("invalid character '\{c}' in package attribute '\{attr}'") + } + } + "https://hydra.nixos.org/job/\{self.project}/\{self.jobset}/\{self.job_prefix}\{attr}.\{system}/latest-finished" +} + +///| +/// Extract `(store path, nixname)` of the `out` output from Hydra's build JSON. +pub fn parse_hydra_build( + text : String, +) -> (String, String) raise @store.NixError { + let j = @json.parse(text) catch { + _ => raise Parse("Hydra response is not valid JSON") + } + guard j is Object(top) else { raise Parse("Hydra response: expected object") } + if top.get("error") is Some(e) { + raise Parse("Hydra error: \{e.stringify()}") + } + if top.get("finished") is Some(f) && f.stringify() != "1" { + raise Verify("Hydra build not finished") + } + if top.get("buildstatus") is Some(s) && s.stringify() != "0" { + raise Verify( + "Hydra build was not successful (buildstatus \{s.stringify()})", + ) + } + guard top.get("buildoutputs") is Some(Object(outs)) else { + raise Parse("Hydra response: missing buildoutputs") + } + guard outs.get("out") is Some(Object(out)) else { + raise Parse("Hydra response: no 'out' output") + } + guard out.get("path") is Some(String(path)) else { + raise Parse("Hydra response: no path for 'out'") + } + let name = match top.get("nixname") { + Some(String(n)) => n + _ => "" + } + ignore(@store.StorePath::parse(path)) + (path, name) +} + +///| +/// Parse the text of `store-paths.xz` (one store path per line). +pub fn parse_store_paths( + text : String, +) -> Array[@store.StorePath] raise @store.NixError { + let out : Array[@store.StorePath] = [] + for line in text.split("\n") { + if line.length() == 0 { + continue + } + out.push(@store.StorePath::parse(line.to_owned())) + } + out +} + +///| +/// Substring search over `name-version` strings of the channel's store paths. +/// Returns distinct names sorted by (exact match first, then length, then +/// alphabetical) with the number of distinct store paths for that name (the +/// same name appears several times because the channel covers all platforms). +pub fn search( + paths : Array[@store.StorePath], + query : String, +) -> Array[(String, Int32)] { + let q = query.to_lower() + let counts : Map[String, Int32] = Map([]) + for p in paths { + if p.name.to_lower().contains(q) { + counts[p.name] = counts.get_or_default(p.name, 0) + 1 + } + } + let res : Array[(String, Int32)] = [] + for k, v in counts { + res.push((k, v)) + } + res.sort_by(fn(a, b) { + let ka = rank(a.0, q) + let kb = rank(b.0, q) + if ka != kb { + ka - kb + } else if a.0.length() != b.0.length() { + a.0.length() - b.0.length() + } else { + a.0.compare(b.0) + } + }) + res +} + +///| +/// 0 = pname equals query, 1 = starts with query, 2 = elsewhere. +fn rank(name : String, q : String) -> Int32 { + let l = name.to_lower() + // pname = up to the first '-' followed by a digit + let chars = l.to_array() + let mut cut = chars.length() + for i in 0..= '0' && n <= '9' { + cut = i + break + } + } + } + let pname = l[0:cut].to_owned() + if pname == q { + 0 + } else if l.has_prefix(q) { + 1 + } else { + 2 + } +} diff --git a/src/resolve/resolve_wbtest.mbt b/src/resolve/resolve_wbtest.mbt new file mode 100644 index 0000000..981e1b0 --- /dev/null +++ b/src/resolve/resolve_wbtest.mbt @@ -0,0 +1,56 @@ +///| +test "channel mapping" { + let c = Channel::parse("nixos-unstable") + inspect( + c.job_url("hello", "x86_64-linux"), + content="https://hydra.nixos.org/job/nixpkgs/trunk/hello.x86_64-linux/latest-finished", + ) + let r = Channel::parse("nixos-25.05") + inspect( + r.job_url("hello", "x86_64-linux"), + content="https://hydra.nixos.org/job/nixos/release-25.05/nixpkgs.hello.x86_64-linux/latest-finished", + ) + assert_true(@store.raises(() => Channel::parse("bogus"))) + assert_true(@store.raises(() => c.job_url("a/b", "x86_64-linux"))) +} + +///| +test "parse hydra build json (real response shape)" { + let text = + #|{"system":"x86_64-linux","finished":1,"buildstatus":0,"nixname":"hello-2.12.3","buildoutputs":{"out":{"path":"/nix/store/dcg4mi1h810kl0q5skk995b8nb2idg1g-hello-2.12.3"}}} + let (p, n) = parse_hydra_build(text) + inspect(p, content="/nix/store/dcg4mi1h810kl0q5skk995b8nb2idg1g-hello-2.12.3") + inspect(n, content="hello-2.12.3") + assert_true( + @store.raises(() => { + parse_hydra_build("{\"error\":\"There is no successful build\"}") + }), + ) + assert_true(@store.raises(() => parse_hydra_build("not json"))) + assert_true( + @store.raises(() => { + parse_hydra_build( + "{\"finished\":1,\"buildstatus\":1,\"buildoutputs\":{}}", + ) + }), + ) +} + +///| +test "search ranks exact pname first" { + let paths = parse_store_paths( + ( + #|/nix/store/8padfyi6z9ipfq35j86krpvpvx3j3r3v-hello-2.8.4 + #|/nix/store/2w75rgswbbfgj1910mw7w5lz0cf6rxfr-hello-1.0.0.2 + #|/nix/store/2w75rgswbbfgj1910mw7w5lz0cf6rxfr-hello-1.0.0.2 + #|/nix/store/266xlfadj5g19isr0ygn0nz9jbgmvhrd-akku-retropikzel-hello-1.2.3 + #|/nix/store/76bbldfx3g88jxaqjakksgc5mvl1c3kb-ripgrep-15.2.0 + ), + ) + let r = search(paths, "hello") + assert_eq(r.length(), 3) + assert_eq(r[0].0.has_prefix("hello-"), true) + assert_eq(r[2].0, "akku-retropikzel-hello-1.2.3") + assert_eq(search(paths, "HELLO").length(), 3) + assert_eq(search(paths, "zzz").length(), 0) +} diff --git a/src/sign/moon.pkg b/src/sign/moon.pkg new file mode 100644 index 0000000..9d4ca83 --- /dev/null +++ b/src/sign/moon.pkg @@ -0,0 +1,7 @@ +import { + "experiments/moon-nix/store", + "experiments/moon-nix/narinfo", + "moonbitlang/core/encoding/base64", + "moonbitlang/core/encoding/utf8", + "hustcer/ed25519", +} diff --git a/src/sign/pkg.generated.mbti b/src/sign/pkg.generated.mbti new file mode 100644 index 0000000..b069af9 --- /dev/null +++ b/src/sign/pkg.generated.mbti @@ -0,0 +1,27 @@ +// Generated using `moon info`, DON'T EDIT IT +package "experiments/moon-nix/sign" + +import { + "experiments/moon-nix/narinfo", + "experiments/moon-nix/store", +} + +// Values +pub let cache_nixos_org_key : String + +pub fn fingerprint(@narinfo.NarInfo) -> String raise @store.NixError + +pub fn verify_narinfo(@narinfo.NarInfo, Array[PublicKey]) -> String raise @store.NixError + +// Errors + +// Types and methods +pub(all) struct PublicKey { + name : String + key : Bytes +} +pub fn PublicKey::parse(String) -> Self raise @store.NixError + +// Type aliases + +// Traits diff --git a/src/sign/sign.mbt b/src/sign/sign.mbt new file mode 100644 index 0000000..6e4eeb7 --- /dev/null +++ b/src/sign/sign.mbt @@ -0,0 +1,88 @@ +///| +pub let cache_nixos_org_key : String = "cache.nixos.org-1:6NCHdD59X431o0gWypbMrAURkbJ16ZPMQFGspcDShjY=" + +///| +/// A trusted public key in Nix's `name:base64(ed25519 pubkey)` format. +pub(all) struct PublicKey { + name : String + key : Bytes +} + +///| +pub fn PublicKey::parse(s : String) -> PublicKey raise @store.NixError { + guard s.find(":") is Some(i) else { + raise Parse("public key must be name:base64, got '\{s}'") + } + let name = s[0:i].to_owned() + let key = decode_b64(s[i + 1:].to_owned(), "public key") + if key.length() != 32 { + raise Parse("public key '\{name}' must be 32 bytes, got \{key.length()}") + } + { name, key, } +} + +///| +fn decode_b64(s : String, what : String) -> Bytes raise @store.NixError { + @base64.decode(s) catch { + _ => raise Parse("invalid base64 in \{what}: '\{s}'") + } +} + +///| +/// The string that Nix signs for a path: +/// `1;;;;` with references as +/// full paths. The store dir used is the logical one embedded in the +/// narinfo's StorePath (what the cache signed), never our install location. +pub fn fingerprint(ni : @narinfo.NarInfo) -> String raise @store.NixError { + let sp = @store.StorePath::parse(ni.store_path) + let refs = ni.references.map(fn(r) { "\{sp.store_dir}/\{r}" }) + "1;\{ni.store_path};\{ni.nar_hash};\{ni.nar_size};\{refs.join(",")}" +} + +///| +/// Verify that at least one signature in the narinfo is valid under one of +/// the trusted keys. Raises Verify with a precise reason otherwise. +pub fn verify_narinfo( + ni : @narinfo.NarInfo, + trusted : Array[PublicKey], +) -> String raise @store.NixError { + if ni.sigs.length() == 0 { + raise Verify("\{ni.store_path}: narinfo carries no signature") + } + let fp = fingerprint(ni) + let msg = @utf8.encode(fp) + let mut matched_name = false + for s in ni.sigs { + guard s.find(":") is Some(i) else { + raise Parse("malformed signature '\{s}'") + } + let name = s[0:i].to_owned() + let sig = decode_b64(s[i + 1:].to_owned(), "signature") + for k in trusted { + if k.name == name { + matched_name = true + if sig.length() != 64 { + raise Verify("signature by \{name} has wrong length \{sig.length()}") + } + if @ed25519.verify(k.key, msg, sig) { + return name + } + } + } + } + if matched_name { + raise Verify( + "\{ni.store_path}: signature does not match fingerprint '\{fp}'", + ) + } else { + let signers = ni.sigs.map(fn(s) { + match s.find(":") { + Some(i) => s[0:i].to_owned() + None => s + } + }) + raise Verify( + "\{ni.store_path}: no signature from a trusted key (signed by: \{signers.join(", ")})", + ) + } +} diff --git a/src/sign/sign_wbtest.mbt b/src/sign/sign_wbtest.mbt new file mode 100644 index 0000000..39aba75 --- /dev/null +++ b/src/sign/sign_wbtest.mbt @@ -0,0 +1,57 @@ +///| +let fixture : String = + #|StorePath: /nix/store/8padfyi6z9ipfq35j86krpvpvx3j3r3v-hello-2.8.4 + #|URL: nar/0rn6mlcldbs3x4jwd7j8x2j1xf3v8ydn08icm4by312cw7db8z33.nar.zst + #|Compression: zstd + #|FileHash: sha256:0rvh1h413bl7rl9hbifzvjwjyzfbqy4q969xpg42ns43fajggazs + #|FileSize: 10561 + #|NarHash: sha256:0rn6mlcldbs3x4jwd7j8x2j1xf3v8ydn08icm4by312cw7db8z33 + #|NarSize: 101224 + #|References: 1q857rs68rs3gijls9wdnsjqnwnv5zd8-glibc-2.44-57 w79cl5jdx1hggkmy4miwhb1j9w1pb7qg-gcc-16.2.0-lib + #|Deriver: fwcmbj1s9g7w3ss4nn774dvvq4was180-hello-2.8.4.drv + #|Sig: cache.nixos.org-1:LPtBVTcqdkiUD6vGPmFjn0LEIkg0N5cg7xwbIPa9z9g81p9gUxGJQElBPNDhI6MD0Jt3AyCK5rb1Buy609kXCQ== + +///| +test "fingerprint format" { + let ni = @narinfo.NarInfo::parse(fixture) + inspect( + fingerprint(ni), + content="1;/nix/store/8padfyi6z9ipfq35j86krpvpvx3j3r3v-hello-2.8.4;sha256:0rn6mlcldbs3x4jwd7j8x2j1xf3v8ydn08icm4by312cw7db8z33;101224;/nix/store/1q857rs68rs3gijls9wdnsjqnwnv5zd8-glibc-2.44-57,/nix/store/w79cl5jdx1hggkmy4miwhb1j9w1pb7qg-gcc-16.2.0-lib", + ) +} + +///| +test "real cache.nixos.org signature verifies" { + let ni = @narinfo.NarInfo::parse(fixture) + let key = PublicKey::parse(cache_nixos_org_key) + inspect(verify_narinfo(ni, [key]), content="cache.nixos.org-1") +} + +///| +test "tampered narinfo is rejected" { + let key = PublicKey::parse(cache_nixos_org_key) + let ni = @narinfo.NarInfo::parse(fixture) + // wrong size + assert_true( + @store.raises(() => verify_narinfo({ ..ni, nar_size: 101225L, }, [key])), + ) + // dropped reference + assert_true( + @store.raises(() => { + verify_narinfo({ ..ni, references: [ni.references[0]], }, [key]) + }), + ) + // no signatures + assert_true(@store.raises(() => verify_narinfo({ ..ni, sigs: [], }, [key]))) + // untrusted key + let other = PublicKey::parse( + "other-1:6NCHdD59X431o0gWypbMrAURkbJ16ZPMQFGspcDShjY=", + ) + assert_true(@store.raises(() => verify_narinfo(ni, [other]))) +} + +///| +test "bad public key rejected" { + assert_true(@store.raises(() => PublicKey::parse("nocolon"))) + assert_true(@store.raises(() => PublicKey::parse("k:AAAA"))) +} diff --git a/src/store/error.mbt b/src/store/error.mbt new file mode 100644 index 0000000..aa5ad42 --- /dev/null +++ b/src/store/error.mbt @@ -0,0 +1,32 @@ +///| +/// Single error type shared by all mnix packages. Every failure is loud: +/// there are no silent fallbacks anywhere in the code base. +pub(all) suberror NixError { + Parse(String) + Verify(String) + Network(String) + Io(String) + Unsupported(String) +} + +///| +pub impl Show for NixError with fn output(self, logger) { + match self { + Parse(m) => logger.write_string("parse error: \{m}") + Verify(m) => logger.write_string("verification failed: \{m}") + Network(m) => logger.write_string("network error: \{m}") + Io(m) => logger.write_string("I/O error: \{m}") + Unsupported(m) => logger.write_string("unsupported: \{m}") + } +} + +///| +/// Test helper: true if `f` raises. +pub fn[T] raises(f : () -> T raise) -> Bool { + try { + ignore(f()) + false + } catch { + _ => true + } +} diff --git a/src/store/hash.mbt b/src/store/hash.mbt new file mode 100644 index 0000000..c5e5de7 --- /dev/null +++ b/src/store/hash.mbt @@ -0,0 +1,36 @@ +///| +/// Raw SHA-256 digest (32 bytes). +pub fn sha256(data : BytesView) -> Bytes { + let d = @crypto.sha256(data) + Bytes::from_array(d) +} + +///| +/// `sha256:` rendering used by narinfo files. +pub fn sha256_nix32(data : BytesView) -> String { + "sha256:" + nixbase32_encode(sha256(data)) +} + +///| +pub fn to_hex(data : BytesView) -> String { + let hex = "0123456789abcdef" + let sb = StringBuilder() + for b in data { + sb.write_char(hex.get_char(b.to_int() >> 4).unwrap()) + sb.write_char(hex.get_char(b.to_int() & 15).unwrap()) + } + sb.to_string() +} + +///| +/// Parse `sha256:` into raw 32 bytes. +pub fn parse_sha256(s : String) -> Bytes raise { + guard s.strip_prefix("sha256:") is Some(rest) else { + raise Parse("unsupported hash (expected sha256:...): \{s}") + } + if rest.length() == 52 { + nixbase32_decode(rest, 32) + } else { + raise Parse("unsupported sha256 encoding length \{rest.length()}: \{s}") + } +} diff --git a/src/store/moon.pkg b/src/store/moon.pkg new file mode 100644 index 0000000..0b206ac --- /dev/null +++ b/src/store/moon.pkg @@ -0,0 +1,3 @@ +import { + "moonbitlang/x/crypto", +} diff --git a/src/store/nixbase32.mbt b/src/store/nixbase32.mbt new file mode 100644 index 0000000..9b370f0 --- /dev/null +++ b/src/store/nixbase32.mbt @@ -0,0 +1,74 @@ +///| +/// Nix's base-32 alphabet: digits and lowercase letters without e, o, u, t. +let alphabet : String = "0123456789abcdfghijklmnpqrsvwxyz" + +///| +/// Encoded length for `n` input bytes. +pub fn base32_len(n : Int32) -> Int32 { + if n == 0 { + 0 + } else { + (n * 8 - 1) / 5 + 1 + } +} + +///| +/// Encode bytes the way Nix does (least-significant 5-bit group last, +/// i.e. the string is written "backwards" relative to RFC 4648). +pub fn nixbase32_encode(data : BytesView) -> String { + let n = data.length() + let len = base32_len(n) + let sb = StringBuilder() + for k = len - 1; k >= 0; k = k - 1 { + let b = k * 5 + let i = b / 8 + let j = b % 8 + let lo = data[i].to_int() >> j + let hi = if i + 1 < n { data[i + 1].to_int() << (8 - j) } else { 0 } + let c = (lo | hi) & 0x1f + sb.write_char(alphabet.get_char(c).unwrap()) + } + sb.to_string() +} + +///| +fn digit_of(c : Char) -> Int32? { + for i in 0..<32 { + if alphabet.get_char(i).unwrap() == c { + return Some(i) + } + } + None +} + +///| +/// Decode a nixbase32 string into exactly `size` bytes. Fails loudly on +/// wrong length, invalid characters, or non-zero padding bits. +pub fn nixbase32_decode(s : StringView, size : Int32) -> Bytes raise NixError { + let chars = s.to_owned().to_array() + let len = chars.length() + if len != base32_len(size) { + raise Parse( + "expected \{base32_len(size)} characters for \{size} bytes, got \{len}", + ) + } + let out : Array[Int32] = Array::make(size, 0) + for n in 0.. d + None => raise Parse("invalid character '\{c}'") + } + let b = n * 5 + let i = b / 8 + let j = b % 8 + out[i] = out[i] | ((d << j) & 0xff) + let carry = d >> (8 - j) + if i + 1 < size { + out[i + 1] = out[i + 1] | carry + } else if carry != 0 { + raise Parse("non-zero trailing bits") + } + } + Bytes::from_array(FixedArray::makei(size, fn(i) { out[i].to_byte() })) +} diff --git a/src/store/path.mbt b/src/store/path.mbt new file mode 100644 index 0000000..c44174d --- /dev/null +++ b/src/store/path.mbt @@ -0,0 +1,100 @@ +///| +/// A parsed store path `/<32-char nixbase32 hash>-`. +#derive(Eq, Debug) +pub(all) struct StorePath { + store_dir : String + hash : String + name : String +} + +///| +pub let default_store_dir : String = "/nix/store" + +///| +fn valid_name_char(c : Char) -> Bool { + (c >= 'a' && c <= 'z') || + (c >= 'A' && c <= 'Z') || + (c >= '0' && c <= '9') || + c == '+' || + c == '-' || + c == '.' || + c == '_' || + c == '?' || + c == '=' +} + +///| +/// Validate the `-` part (the base name of a store path). +pub fn StorePath::parse_base( + base : String, + store_dir~ : String = default_store_dir, +) -> StorePath raise NixError { + if base.length() < 34 { + raise Parse("too short: \{base}") + } + let hash = base[0:32].to_owned() + if base[32:33].to_owned() != "-" { + raise Parse("missing '-' after hash: \{base}") + } + let name = base[33:].to_owned() + for c in hash { + if digit_of(c) is None { + raise Parse("invalid nixbase32 character '\{c}' in hash: \{base}") + } + } + // The 160-bit hash: 32 chars carry 160 bits exactly, but the top char only + // has 0..7 valid values (decoding validates trailing bits). + ignore(nixbase32_decode(hash, 20)) + if name.length() > 211 { + raise Parse("name too long") + } + if name.length() == 0 { + raise Parse("empty name") + } + if name == "." || name == ".." || name.has_prefix(".") { + raise Parse("name must not start with '.': \{name}") + } + for c in name { + if !valid_name_char(c) { + raise Parse("invalid character '\{c}' in name: \{name}") + } + } + { store_dir, hash, name, } +} + +///| +/// Parse a full path `/-`; the store dir is inferred +/// from the path (everything before the last '/'). +pub fn StorePath::parse(path : String) -> StorePath raise NixError { + guard path.rev_find("/") is Some(i) else { + raise Parse("not an absolute path: \{path}") + } + let dir = if i == 0 { "/" } else { path[0:i].to_owned() } + if !path.has_prefix("/") { + raise Parse("not an absolute path: \{path}") + } + StorePath::parse_base(path[i + 1:].to_owned(), store_dir=dir) +} + +///| +pub fn StorePath::base_name(self : StorePath) -> String { + "\{self.hash}-\{self.name}" +} + +///| +pub fn StorePath::to_string(self : StorePath) -> String { + "\{self.store_dir}/\{self.hash}-\{self.name}" +} + +///| +/// Same store path re-rooted in another store dir. +pub fn StorePath::with_store_dir(self : StorePath, dir : String) -> StorePath { + { ..self, store_dir: dir, } +} + +///| +/// Fingerprints in signatures always use the *logical* store dir of the +/// cache (/nix/store), regardless of where we install. +pub fn StorePath::logical(self : StorePath) -> String { + "\{default_store_dir}/\{self.hash}-\{self.name}" +} diff --git a/src/store/pkg.generated.mbti b/src/store/pkg.generated.mbti new file mode 100644 index 0000000..2c30bad --- /dev/null +++ b/src/store/pkg.generated.mbti @@ -0,0 +1,55 @@ +// Generated using `moon info`, DON'T EDIT IT +package "experiments/moon-nix/store" + +import { + "moonbitlang/core/debug", +} + +// Values +pub fn base32_len(Int32) -> Int32 + +pub let default_store_dir : String + +pub fn hello_probe() -> Int32 + +pub fn nixbase32_decode(StringView, Int32) -> Bytes raise NixError + +pub fn nixbase32_encode(BytesView) -> String + +pub fn parse_sha256(String) -> Bytes raise + +pub fn[T] raises(() -> T raise) -> Bool + +pub fn sha256(BytesView) -> Bytes + +pub fn sha256_nix32(BytesView) -> String + +pub fn to_hex(BytesView) -> String + +// Errors +pub(all) suberror NixError { + Parse(String) + Verify(String) + Network(String) + Io(String) + Unsupported(String) +} +pub impl Show for NixError + +// Types and methods +#derive(Eq, @debug.Debug) +pub(all) struct StorePath { + store_dir : String + hash : String + name : String +} +pub fn StorePath::base_name(Self) -> String +pub fn StorePath::logical(Self) -> String +pub fn StorePath::parse(String) -> Self raise NixError +pub fn StorePath::parse_base(String, store_dir? : String) -> Self raise NixError +pub fn StorePath::to_string(Self) -> String +pub fn StorePath::with_store_dir(Self, String) -> Self + +// Type aliases + +// Traits diff --git a/src/store/store.mbt b/src/store/store.mbt new file mode 100644 index 0000000..c5dd898 --- /dev/null +++ b/src/store/store.mbt @@ -0,0 +1,4 @@ +///| +pub fn hello_probe() -> Int32 { + 1 +} diff --git a/src/store/store_wbtest.mbt b/src/store/store_wbtest.mbt new file mode 100644 index 0000000..b0370e1 --- /dev/null +++ b/src/store/store_wbtest.mbt @@ -0,0 +1,70 @@ +///| +test "nixbase32 encode known vectors" { + // From the Nix test-suite: hash of "" etc. Use sha256("") = e3b0c442... + let h = sha256(b"") + inspect( + nixbase32_encode(h), + content="0mdqa9w1p6cmli6976v4wi0sw9r4p5prkj7lzfd1877wk11c9c73", + ) + inspect(nixbase32_encode(b"\x00\x01\x02"), content="04080") + inspect(nixbase32_encode(b""), content="") +} + +///| +test "nixbase32 roundtrip" { + for n in 1..<40 { + let arr = FixedArray::makei(n, fn(i) { ((i * 37 + n * 11) % 256).to_byte() }) + let b = Bytes::from_array(arr) + let s = nixbase32_encode(b) + assert_eq(nixbase32_decode(s, n), b) + } +} + +///| +test "nixbase32 decode errors" { + assert_true(raises(() => nixbase32_decode("0e0", 2))) // 'e' invalid + assert_true(raises(() => nixbase32_decode("00", 2))) // wrong length + assert_true(raises(() => nixbase32_decode("zzz", 2))) // trailing bits +} + +///| +test "sha256 vector" { + inspect( + to_hex(sha256(b"abc")), + content="ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad", + ) +} + +///| +test "store path parse" { + let p = StorePath::parse( + "/nix/store/8padfyi6z9ipfq35j86krpvpvx3j3r3v-hello-2.8.4", + ) + inspect(p.hash, content="8padfyi6z9ipfq35j86krpvpvx3j3r3v") + inspect(p.name, content="hello-2.8.4") + inspect(p.store_dir, content="/nix/store") + inspect( + p.to_string(), + content="/nix/store/8padfyi6z9ipfq35j86krpvpvx3j3r3v-hello-2.8.4", + ) +} + +///| +test "store path rejects invalid" { + // 'e' not in alphabet + assert_true( + raises(() => { + StorePath::parse("/nix/store/8padfyi6z9ipfq35j86krpvpvx3j3rev-hello") + }), + ) + // too short hash + assert_true(raises(() => StorePath::parse("/nix/store/abc-hello"))) + // bad char in name + assert_true( + raises(() => { + StorePath::parse("/nix/store/8padfyi6z9ipfq35j86krpvpvx3j3r3v-he llo") + }), + ) + // not absolute + assert_true(raises(() => StorePath::parse("hello"))) +}