From 988c942952ef7504538f041ae083db795d0c747c Mon Sep 17 00:00:00 2001 From: Sprite Date: Tue, 24 Nov 2026 21:49:20 +0000 Subject: [PATCH] WIP: store, narinfo, sign, nar, cache, closure packages --- .gitignore | 4 + moon.mod | 25 ++++ src/cache/cache.mbt | 163 ++++++++++++++++++++++ src/cache/moon.pkg | 10 ++ src/cache/pkg.generated.mbti | 32 +++++ src/closure/closure.mbt | 46 ++++++ src/closure/closure_wbtest.mbt | 69 +++++++++ src/closure/moon.pkg | 8 ++ 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 | 99 +++++++++++++ src/narinfo/narinfo_wbtest.mbt | 38 +++++ src/narinfo/pkg.generated.mbti | 32 +++++ 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 ++++++++++ 28 files changed, 1432 insertions(+) create mode 100644 .gitignore create mode 100644 moon.mod create mode 100644 src/cache/cache.mbt create mode 100644 src/cache/moon.pkg create mode 100644 src/cache/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/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/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/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..ba02754 --- /dev/null +++ b/src/cache/cache.mbt @@ -0,0 +1,163 @@ +///| +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(fn(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, +) -> Bytes? raise @store.NixError { + let mut cur = url + for _ in 0..<8 { + let (resp, body) = @http.get(cur) 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/moon.pkg b/src/cache/moon.pkg new file mode 100644 index 0000000..faf0613 --- /dev/null +++ b/src/cache/moon.pkg @@ -0,0 +1,10 @@ +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", +} diff --git a/src/cache/pkg.generated.mbti b/src/cache/pkg.generated.mbti new file mode 100644 index 0000000..31493bf --- /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) -> 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/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/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..cbb4bcd --- /dev/null +++ b/src/narinfo/narinfo.mbt @@ -0,0 +1,99 @@ +///| +/// 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. `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 + } + guard line.find(": ") is Some(i) else { + raise Parse("narinfo: malformed line (no ': '): \{line}") + } + let key = line[0:i].to_owned() + let value = line[i + 2:].to_owned() + 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() + None => raise Parse("narinfo: missing required key References") + } + 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..95d4b70 --- /dev/null +++ b/src/narinfo/narinfo_wbtest.mbt @@ -0,0 +1,38 @@ +///| +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"))) +} 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/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"))) +}