diff --git a/CHANGELOG.adoc b/CHANGELOG.adoc index 7e7cf13e..a2838964 100644 --- a/CHANGELOG.adoc +++ b/CHANGELOG.adoc @@ -153,10 +153,38 @@ without the fix (127 tests, up from 123). not exist here, and so returned the fallback grade for the wrong reason. The same defect is in the upstream contractile copy. -Not fixed in this cycle, with reasons rather than silence: the deed's -`:parent-pin` / `:template-commit` names a commit that no longer exists in -`hyperpolymath/rsr-template-repo`, so `check-variant-drift.sh` cannot be run -at all (see `docs/reports/VERIFICATION.adoc`); base-image digest pinning and +Three findings from the review of the C ABI pull request +(`hyperpolymath/zig-dnssec`#5) were still open on `main`, and one more turned +up while checking them. Each new or tightened test fails against the code it +now guards: + +* The C ABI emptied the caller's text buffer only after its first argument + checks, so a NULL exchange function, NULL trace, NULL verdict pointer or + unparseable trace left a previous answer readable after a non-OK status, + although `zig_dnssec.h` says text is "set to the empty string first". Every + entry point now resets the verdict and the text before checking anything. +* `Abi.Foreign.validateTrace` handed its ABI-v1 verdict buffer to whatever + `libzig_dnssec` was loaded without comparing ABI versions; it now returns + `BrokenContract` on a mismatch before calling the library. +* `formatRr` wrote an empty NSEC3 salt as an empty field rather than `-` + (RFC 5155 §3.3), so an NSEC3 answer with the salt RFC 9276 recommends was + not parseable presentation format. +* NSEC and NSEC3 type bitmaps were enumerated into a 128-entry buffer, and + `TypeBitmap.fill` dropped every type past it without saying so: a bitmap + setting more types printed as valid but incomplete presentation format. + `fill` is replaced by `TypeBitmap.iterator`, which the formatter streams, + so no type can be lost. +* The user and maintainer quick starts, and `build/guix.scm`'s synopsis, + still described the template: recipes that do not exist (`stapeln-run`, + `stapeln-export`), unwired ones (`install`, `run`) and "Rsr Template Repo". + They now give only the wired commands. + +`check-variant-drift.sh` was recorded here as unrunnable because the deed's +parent pin is not in `rsr-template-repo`. The pin is this repository's own +root commit, whose tree is the deed's `:template-tree`; run against it, the +gate passes (`docs/reports/VERIFICATION.adoc`). + +Not fixed in this cycle, with reasons rather than silence: base-image digest pinning and the container build stages' user model are left to the estate-wide pinning decision because no registry or container engine is reachable from here to verify either; and the negative-cache-TTL bound above has no test, because no diff --git a/build/guix.scm b/build/guix.scm index 7dd3152e..d5cdaa6f 100755 --- a/build/guix.scm +++ b/build/guix.scm @@ -39,8 +39,8 @@ (native-inputs (map spec->input (list "git" "bash" "coreutils" "nss-certs" "just" "mise" "shellcheck" "chez-scheme" "gmp" "gcc-toolchain" "zig"))) (home-page "https://github.com/hyperpolymath/zig-dnssec") - (synopsis "Rhodium Standard Repository template") - (description "The estate's repository template: the RSR layout, an Idris2 ABI -seam with a Zig FFI, CI gates, and the provisioning set (launcher, Justfile, -mise, Guix, setup and AI-assisted installation guides).") + (synopsis "Experimental pure-Zig DNSSEC validator and DoH stub client") + (description "Experimental pure-Zig DNS wire-format codec and DNSSEC validator +with a DNS-over-HTTPS stub client: authenticates answers from an untrusted +upstream resolver to a configured trust anchor. Not independently reviewed.") (license license:mpl2.0)) diff --git a/docs/onboarding/QUICKSTART-MAINTAINER.adoc b/docs/onboarding/QUICKSTART-MAINTAINER.adoc index 88166c9c..a59bfd17 100644 --- a/docs/onboarding/QUICKSTART-MAINTAINER.adoc +++ b/docs/onboarding/QUICKSTART-MAINTAINER.adoc @@ -7,10 +7,12 @@ == Overview -This guide covers packaging, deploying, and maintaining zig-dnssec for -distribution on your platform. +This guide covers building and packaging zig-dnssec for distribution on your +platform. zig-dnssec is a library with one command-line tool, `dnssec-stub`, and a +C ABI (`libzig_dnssec` and `zig_dnssec.h`). It has no configuration file, and +`just install` and per-instance deployment are not wired. Only the paths below are. -== Runtime Dependencies +== Build Dependencies Zig 0.17.0, `just` (1.42 or later), and Idris2 0.7.0 for the ABI model checks that `just test` runs. @@ -23,7 +25,15 @@ cd zig-dnssec just build ---- -Output: `zig-out/` +Output, under `zig-out/`: + +* `bin/dnssec-stub`: the CLI (its exit status is the verdict: 0 secure, + 1 insecure, 2 bogus, 3 indeterminate, 4 usage or transport error) +* `lib/libzig_dnssec` (static and shared) and `include/zig_dnssec.h`, from + `zig build ffi` + +For a release build use `zig build -Doptimize=ReleaseSafe`; package those files +directly, since there is no install recipe. == Packaging @@ -34,57 +44,18 @@ Output: `zig-out/` guix build -f build/guix.scm ---- -=== Container (Stapeln) +This packages the source tree under `share/zig-dnssec/`. -[source,bash] ----- -just stapeln-export # Generates Containerfile -podman build -t zig-dnssec . ----- - -=== Manual Package +=== Container [source,bash] ---- -just install --prefix=/usr/local +just container-build ---- -Files installed: - -[cols="1,2"] -|=== -| Path | Contents - -| `$PREFIX/bin/` -| Executables - -| `$PREFIX/share/zig-dnssec/` -| Data files, assets - -| `$PREFIX/share/doc/zig-dnssec/` -| Documentation - -| `$PREFIX/share/applications/` -| .desktop file (Linux, if GUI) - -| `$PREFIX/share/man/man1/` -| Man pages -|=== - -== Configuration - -Default config location: `$XDG_CONFIG_HOME/zig-dnssec/config.toml` - -Fallback: `$HOME/.config/zig-dnssec/config.toml` - -== Health Checks - -[source,bash] ----- -just doctor # Full diagnostic -just run --version # Version check -just run --selftest # Built-in self-test ----- +This builds `build/container/Containerfile` and tags the image +`ghcr.io/hyperpolymath/zig-dnssec:latest`. `CT_REGISTRY` and `CT_TAG` override +the registry and tag. `just container-push` publishes the same reference. == Updating @@ -92,31 +63,16 @@ just run --selftest # Built-in self-test ---- git pull just build -just install --prefix=/usr/local +just test ---- -Or via OPSM: `opsm update zig-dnssec` - == Security Notes * License: MPL-2.0 (code) / CC-BY-SA-4.0 (docs) * All dependencies SHA-pinned -* `panic-attacker` scan results: link:INSTALL-SECURITY-REPORT.adoc[] * OpenSSF Scorecard: see badge in README - -== Multi-Instance Deployment - -For deploying multiple instances (e.g., different users or tenants): - -[source,bash] ----- -just install --prefix=/opt/zig-dnssec-instance1 --config=/etc/zig-dnssec/instance1.toml -just install --prefix=/opt/zig-dnssec-instance2 --config=/etc/zig-dnssec/instance2.toml ----- - -Each instance has isolated config, data, and logs. +* Experimental and not independently reviewed: see the warning in the README == Reporting Issues * Upstream: https://github.com/hyperpolymath/zig-dnssec/issues -* With diagnostic: `just help-me` (pre-fills context) diff --git a/docs/onboarding/QUICKSTART-USER.adoc b/docs/onboarding/QUICKSTART-USER.adoc index 163e7a0b..cceb3f37 100644 --- a/docs/onboarding/QUICKSTART-USER.adoc +++ b/docs/onboarding/QUICKSTART-USER.adoc @@ -1,125 +1,68 @@ // SPDX-License-Identifier: CC-BY-SA-4.0 // Copyright (c) Jonathan D.A. Jewell // Template: QUICKSTART-USER.adoc — 5-minute path to working software -// Replace zig-dnssec, Rsr Template Repo — See README.adoc for details., just run, Rsr Template Repo started successfully. with actuals = zig-dnssec — Quick Start for Users :toc: :toclevels: 2 == What is zig-dnssec? -Rsr Template Repo — See README.adoc for details. +Experimental pure-Zig DNS wire-format codec and DNSSEC validator with a +DNS-over-HTTPS stub client: it authenticates answers from an untrusted upstream +resolver to a configured trust anchor. -== Prerequisites - -Before you begin, ensure you have: - -* **just** — task runner (https://github.com/casey/just[install guide]) -* Platform-specific requirements listed below - -[cols="1,3"] -|=== -| Platform | Additional Requirements - -| Linux -| See README.adoc +It is a library with one command-line tool, `dnssec-stub`, which asks a +DNS-over-HTTPS resolver and validates the answer. There is no installer and no +configuration file, and `just install` is not wired. It is experimental and not +independently reviewed; read the warning in the link:../../README.adoc[README] +before relying on it. -| macOS -| See README.adoc - -| Windows -| See README.adoc -|=== +== Prerequisites -== Install +* Zig 0.17.0: enough for `zig build`, `zig build test` and the CLI +* Idris2 0.7.0 as well, for `just build` and `just test`, which also check the + Idris2 model of the C ABI +* *just*, the task runner (https://github.com/casey/just[install guide]) -=== Option 1: Standard Install (recommended) +== Build and test [source,bash] ---- -# Clone and set up git clone https://github.com/hyperpolymath/zig-dnssec.git cd zig-dnssec -just setup ----- - -The setup script will: - -* Detect your platform and shell -* Install missing dependencies (with your permission) -* Configure the application -* Offer install location choices -* Run a self-diagnostic to verify everything works - -=== Option 2: Container (via Stapeln) - -[source,bash] ----- -just stapeln-run ----- - -=== Option 3: Portable (no system changes) - -[source,bash] ----- -just install --portable --prefix=./zig-dnssec-portable ----- - -== First Run - -[source,bash] ----- -just run ----- - -Expected output: - -[source] ----- -Rsr Template Repo started successfully. +zig build # dnssec-stub, into zig-out/bin/ +zig build ffi # libzig_dnssec and zig_dnssec.h, into zig-out/lib and include +zig build test # Zig only +just test # Zig and the Idris2 model ---- -== Self-Diagnostic +To use the library from your own Zig project, follow "Using it" in the +link:../../README.adoc[README]. -If something isn't working: +== Run dnssec-stub [source,bash] ---- -just doctor +./zig-out/bin/dnssec-stub --doh https://cloudflare-dns.com/dns-query example.com. A +zig build run -- --doh https://cloudflare-dns.com/dns-query example.com. A # build and run ---- -This checks all dependencies, permissions, paths, and connectivity. -If it finds issues, it will suggest fixes. +It prints `verdict= reason= at= rcode=`, then the answer records +for a secure or insecure verdict. The exit status is the verdict: 0 secure, +1 insecure, 2 bogus, 3 indeterminate, 4 usage or transport error. Run it with no +arguments for the full option list. -To attempt automatic repair: +== Container [source,bash] ---- -just heal +just container-build ---- -== Get Help - -* **In-app**: `just run --help` -* **Guided tour**: `just tour` -* **Report a problem**: `just help-me` (pre-fills diagnostic context) -* **Wiki**: https://github.com/hyperpolymath/zig-dnssec/wiki - -== Uninstall - -[source,bash] ----- -just uninstall ----- - -You will be asked: - -1. Which uninstall tier (Bennett reversible, parameter-based, standard, or secure) -2. Whether to include or exclude your data -3. Whether to clear caches and LLM models +This builds `ghcr.io/hyperpolymath/zig-dnssec:latest` from +`build/container/Containerfile`. -== Next Steps +== Get help -* Read the link:README.adoc[README] for full feature overview -* Read the link:EXPLAINME.adoc[EXPLAINME] for architecture and design decisions -* Try `just tour` for a guided walkthrough +* Report a problem: https://github.com/hyperpolymath/zig-dnssec/issues +* Security issues: see link:../../.github/SECURITY.md[the security policy] diff --git a/docs/reports/VERIFICATION.adoc b/docs/reports/VERIFICATION.adoc index 6775962d..0934b8f2 100644 --- a/docs/reports/VERIFICATION.adoc +++ b/docs/reports/VERIFICATION.adoc @@ -250,23 +250,34 @@ response. == Findings outside this code -* *The repo deed's template pin cannot be fetched, so the variant-drift gate - cannot be run.* `(provenance :template-commit)` and `(variant :parent-pin)` - both name `3100d46b9cfee83317018f1e8244b2fafa9da660`, and - `:template-branch` names `init/repo-init`. Neither exists in - `hyperpolymath/rsr-template-repo`: the commit returns HTTP 422 from the - commits API and is reachable from no branch, and the branch is gone (the - parent carries only `main` and two work branches, `main` last pushed - 2026-10-27). `scripts/check-variant-drift.sh` takes a parent checkout at - that pin as its argument, so the gate is *unrunnable*, not failing. Run - against the parent's current `main` instead it reports 137 lines of drift, - which measures fourteen days of parent evolution since the 2026-10-13 mint - mixed with this repo's real divergence, and is not actionable either way. - Re-pointing the pin at today's parent tip and rewriting the path lists to - make the gate green would certify convergence that has not been - demonstrated, so it is left for the estate owner: either re-publish the pin - or re-derive the contract deliberately. `check-template-conformance.sh` T3 - asserts the same unfetchable commit and inherits the problem. +* *The repo deed's template pin is not in the template repository, but the + variant-drift gate can still be run, and passes (TESTED).* + `(provenance :template-commit)` and `(variant :parent-pin)` both name + `3100d46b9cfee83317018f1e8244b2fafa9da660`, and `:template-branch` names + `init/repo-init`. Neither exists in `hyperpolymath/rsr-template-repo`: the + commit returns HTTP 422 from its commits API and the branch is gone. The + commit is, however, this repository's own root commit ("Initial commit", + the GitHub template copy), and its tree is `2c01b6f0627133f0ed2544e1edd07ed49602e117`, + exactly the deed's `(provenance :template-tree)`. A checkout of it is + therefore the parent at the pin, identified by tree hash rather than by + where the commit is stored. It needs the root commit locally, so a shallow + clone (CI's default checkout) runs `git fetch --unshallow` first: ++ +---- +git fetch --unshallow # only in a shallow clone +git worktree add ../parent-pin 3100d46b9cfee83317018f1e8244b2fafa9da660 +bash scripts/check-variant-drift.sh ../parent-pin . +---- ++ + This passes ("spine convergent … modulo declared variant paths"), and a + control that edits one undeclared file is reported as drift. Run against + the parent's current `main` instead it reports drift that mixes the + parent's evolution since the 2026-10-13 mint with this repo's divergence, + which is a different question. Still for the estate owner: the deed names a + commit and branch the template repository no longer serves, so tools that + fetch the pin from the parent (and `check-template-conformance.sh` T3) see + it as missing; either the template republishes it or the mint records the + tree hash as the identity to check. * *Zig 0.17.0 `std.http.Client` + CONNECT proxy sends HTTPS requests in cleartext* (`docs/developer/ZIG-STD-SURVEY.adoc`). Worth an upstream report. * *RFC 8080 §6*: the example signatures carry Labels=3 for a two-label owner, which a diff --git a/src/interface/Abi/Foreign.idr b/src/interface/Abi/Foreign.idr index 52845ef2..b160123b 100644 --- a/src/interface/Abi/Foreign.idr +++ b/src/interface/Abi/Foreign.idr @@ -145,12 +145,21 @@ decodeVerdict v readText = do ||| zig_dnssec_validate_trace). `anchors` Nothing selects the built-in IANA root ||| anchors. `now` is seconds since the Unix epoch. The answer buffer starts at ||| 64 KiB and is retried once at the size the library reports. +||| +||| The linked library's ABI version is checked before anything is passed to +||| it: the verdict buffer below is sized and decoded for ABI `abiVersion`, so +||| an unversioned libzig_dnssec of another version found on the library path +||| could otherwise be handed a buffer of the wrong layout. export validateTrace : HasIO io => (trace : String) -> (anchors : Maybe String) -> (qname : String) -> (qtype : Bits16) -> (now : Int64) -> (policy : List PolicyFlag) -> io (Either CallError Outcome) -validateTrace trace anchors qname qtype now policy = attempt 65536 (S Z) +validateTrace trace anchors qname qtype now policy = do + linked <- linkedAbiVersion + if linked /= abiVersion + then pure (Left (BrokenContract ("linked library speaks ABI version " ++ show linked ++ ", this binding expects " ++ show abiVersion))) + else attempt 65536 (S Z) where call : Buffer -> Buffer -> Int -> io Int call out text cap = case anchors of diff --git a/src/interface/ffi/src/main.zig b/src/interface/ffi/src/main.zig index 1360c0f9..a97a8c4e 100644 --- a/src/interface/ffi/src/main.zig +++ b/src/interface/ffi/src/main.zig @@ -102,15 +102,23 @@ pub const Request = struct { text_cap: usize, }; +/// The header's first step for every call, before any argument is checked: +/// the verdict reads NONE and the text buffer is the empty string. Every +/// entry point runs it first, so an early rejection can never leave a +/// previous call's verdict or answer text in the caller's buffers. +fn reset(req: Request) void { + if (req.out) |o| o.* = std.mem.zeroes(Verdict); + if (req.text) |p| { + if (req.text_cap > 0) p[0] = 0; + } +} + /// Runs one validation over `t` and fills the verdict. Keeps the header's /// fail-closed rules: `security` stays NONE unless the result is OK, and /// answer text is produced only for SECURE and INSECURE. pub fn run(gpa: Allocator, t: transport.Transport, req: Request) Status { + reset(req); const out = req.out orelse return .invalid_argument; - out.* = std.mem.zeroes(Verdict); - if (req.text) |p| { - if (req.text_cap > 0) p[0] = 0; - } if (req.policy & ~policy_mask != 0) return .invalid_argument; const qname_z = req.qname orelse return .invalid_argument; const qtype = Type.fromInt(req.qtype); @@ -235,22 +243,17 @@ pub fn validateWith( ctx: ?*anyopaque, req: Request, ) Status { - if (exchange == null) { - if (req.out) |o| o.* = std.mem.zeroes(Verdict); - return .invalid_argument; - } + reset(req); + if (exchange == null) return .invalid_argument; var cb: CallbackTransport = .{ .exchange = exchange, .ctx = ctx }; return run(gpa, cb.asTransport(), req); } pub fn validateTraceWith(gpa: Allocator, trace: ?[*:0]const u8, req: Request) Status { - const tz = trace orelse { - if (req.out) |o| o.* = std.mem.zeroes(Verdict); - return .invalid_argument; - }; + reset(req); + const tz = trace orelse return .invalid_argument; if (req.out == null) return .invalid_argument; var tr = transport.Trace.parse(gpa, std.mem.span(tz)) catch |e| { - req.out.?.* = std.mem.zeroes(Verdict); return switch (e) { error.OutOfMemory => .out_of_memory, else => .bad_trace, diff --git a/src/interface/ffi/test/abi_test.zig b/src/interface/ffi/test/abi_test.zig index 2d690ff4..84d922f4 100644 --- a/src/interface/ffi/test/abi_test.zig +++ b/src/interface/ffi/test/abi_test.zig @@ -203,10 +203,25 @@ test "bad arguments fail closed: status set, security NONE" { try testing.expectEqual(c.expect, rc); try testing.expectEqual(@as(u8, h.ZIG_DNSSEC_SECURITY_NONE), v.security); try testing.expectEqual(@as(u32, 0), v.text_len); - try testing.expect(text[0] == 0 or text[0] == 'X'); + // The header empties text before any argument is checked, so an early + // rejection cannot leave a previous answer readable in the buffer. + try testing.expectEqual(@as(u8, 0), text[0]); + try testing.expectEqual(@as(u8, 'X'), text[1]); } - // A NULL verdict pointer is rejected without writing anything. + // A NULL verdict pointer is rejected; a supplied text buffer is still + // emptied first. + var text: [64]u8 = undefined; + @memset(&text, 'X'); + try testing.expectEqual(@as(c_int, h.ZIG_DNSSEC_ERR_INVALID_ARGUMENT), h.zig_dnssec_validate_trace(trace.ptr, anchors_z.ptr, "www.rsasha256.test.", qtype_a, now, 0, null, &text, text.len)); + try testing.expectEqual(@as(u8, 0), text[0]); try testing.expectEqual(@as(c_int, h.ZIG_DNSSEC_ERR_INVALID_ARGUMENT), h.zig_dnssec_validate_trace(trace.ptr, anchors_z.ptr, "www.rsasha256.test.", qtype_a, now, 0, null, null, 0)); + // The callback entry point: a NULL exchange function is rejected the same + // way, with the verdict NONE and the text emptied. + var v = poisoned(); + @memset(&text, 'X'); + try testing.expectEqual(@as(c_int, h.ZIG_DNSSEC_ERR_INVALID_ARGUMENT), h.zig_dnssec_validate(null, null, anchors_z.ptr, "www.rsasha256.test.", qtype_a, now, 0, &v, &text, text.len)); + try testing.expectEqual(@as(u8, h.ZIG_DNSSEC_SECURITY_NONE), v.security); + try testing.expectEqual(@as(u8, 0), text[0]); } test "NULL anchors select the IANA root, which does not sign the fixtures" { diff --git a/src/wire/rdata.zig b/src/wire/rdata.zig index a0b793a5..a5c2c1ab 100644 --- a/src/wire/rdata.zig +++ b/src/wire/rdata.zig @@ -414,29 +414,45 @@ pub const TypeBitmap = struct { return false; } - /// Fills `out` with every RR type the bitmap sets, in ascending order, and - /// returns the slice written; types past `out.len` are dropped. The - /// presentation writer has no allocator, and a real bitmap carries a - /// handful of types. - pub fn fill(self: TypeBitmap, out: []Type) []Type { - var n: usize = 0; - var p: usize = 0; - while (p + 2 <= self.raw.len) { - const window: u16 = self.raw[p]; - const len = self.raw[p + 1]; - for (self.raw[p + 2 ..][0..len], 0..) |octet, i| { - if (octet == 0) continue; - for (0..8) |bit| { - if ((octet & (@as(u8, 0x80) >> @intCast(bit))) == 0) continue; - if (n == out.len) return out[0..n]; - out[n] = Type.fromInt((window << 8) | (@as(u16, @intCast(i)) * 8 + @as(u16, @intCast(bit)))); - n += 1; + /// Every RR type the bitmap sets, in ascending order. An iterator rather + /// than a fill-a-buffer call so that no caller can lose types silently: + /// a bitmap may set all 65536 types, and the presentation writer has no + /// allocator to size a buffer with. + pub fn iterator(self: TypeBitmap) Iterator { + return .{ .raw = self.raw }; + } + + pub const Iterator = struct { + raw: []const u8, + /// Offset of the current window header. + p: usize = 0, + /// Octet index within the current window. + i: usize = 0, + /// Next bit to test within that octet, 0 (most significant) to 8. + bit: u8 = 0, + + pub fn next(it: *Iterator) ?Type { + while (it.p + 2 <= it.raw.len) { + const window: u16 = it.raw[it.p]; + const len = it.raw[it.p + 1]; + while (it.i < len) { + const octet = it.raw[it.p + 2 + it.i]; + while (it.bit < 8) { + const b = it.bit; + it.bit += 1; + if ((octet & (@as(u8, 0x80) >> @intCast(b))) != 0) { + return Type.fromInt((window << 8) | (@as(u16, @intCast(it.i)) * 8 + b)); + } + } + it.bit = 0; + it.i += 1; } + it.i = 0; + it.p += 2 + @as(usize, len); } - p += 2 + @as(usize, len); + return null; } - return out[0..n]; - } + }; pub fn isEmpty(self: TypeBitmap) bool { var p: usize = 0; @@ -683,3 +699,16 @@ test "canonicalize lowercases the SVCB and HTTPS TargetName" { var buf2: [rd.len]u8 = undefined; try testing.expectEqualSlices(u8, &rd, try expand(&rd, 0, rd.len, .https, &buf2)); } + +test "TypeBitmap.iterator yields every set type across windows, in order" { + // Window 0: A (1) and MX (15). Window 1: type 257. Window 255: type 65535. + var raw: [4 + 3 + 2 + 32]u8 = @splat(0); + @memcpy(raw[0..9], &[_]u8{ 0, 2, 0x40, 0x01, 1, 1, 0x40, 255, 32 }); + raw[raw.len - 1] = 0x01; + const bm = try TypeBitmap.parse(&raw); + var it = bm.iterator(); + const want = [_]u16{ 1, 15, 257, 65535 }; + for (want) |v| try std.testing.expectEqual(v, it.next().?.toInt()); + try std.testing.expectEqual(@as(?Type, null), it.next()); + for (want) |v| try std.testing.expect(bm.has(Type.fromInt(v))); +} diff --git a/src/wire/text.zig b/src/wire/text.zig index 523f9cb0..fa1e4a96 100644 --- a/src/wire/text.zig +++ b/src/wire/text.zig @@ -559,6 +559,14 @@ fn genericRdata(w: *std.Io.Writer, rd: []const u8) std.Io.Writer.Error!void { for (rd) |b| try w.print(" {x:0>2}", .{b}); } +fn writeTypes(w: *std.Io.Writer, bitmap: rdata_mod.TypeBitmap) std.Io.Writer.Error!void { + var it = bitmap.iterator(); + while (it.next()) |t| { + var mb: [16]u8 = undefined; + try w.print(" {s}", .{t.mnemonic(&mb)}); + } +} + pub fn formatRr(w: *std.Io.Writer, rr: *const Rr) std.Io.Writer.Error!void { var tb: [16]u8 = undefined; try rr.name.format(w); @@ -631,26 +639,19 @@ pub fn formatRr(w: *std.Io.Writer, rr: *const Rr) std.Io.Writer.Error!void { return w.writeAll(" (signature)"); } else |_| {}, // NSEC and NSEC3 used to stand in for their type bitmaps with - // "(types)", which is likewise not parseable. The bitmap is small, so - // it is enumerated into a stack buffer and written as mnemonics. + // "(types)", which is likewise not parseable. Every type the bitmap + // sets is streamed as a mnemonic; nothing is buffered, so none is lost. .nsec => if (rdata_mod.Nsec.parse(rd)) |n| { try n.next.format(w); - var tbuf: [128]Type = undefined; - for (n.types.fill(&tbuf)) |t| { - var mb: [16]u8 = undefined; - try w.print(" {s}", .{t.mnemonic(&mb)}); - } - return; + return writeTypes(w, n.types); } else |_| {}, .nsec3 => if (rdata_mod.Nsec3.parse(rd)) |n| { var b32: [512]u8 = undefined; - try w.print("{d} {d} {d} {x} {s}", .{ @backingInt(n.hash_algorithm), n.flags, n.iterations, n.salt, encoding.base32HexEncode(&b32, n.next_hashed_owner) }); - var tbuf: [128]Type = undefined; - for (n.types.fill(&tbuf)) |t| { - var mb: [16]u8 = undefined; - try w.print(" {s}", .{t.mnemonic(&mb)}); - } - return; + try w.print("{d} {d} {d} ", .{ @backingInt(n.hash_algorithm), n.flags, n.iterations }); + // RFC 5155 §3.3: an empty salt is written "-", not left empty. + if (n.salt.len == 0) try w.writeByte('-') else try w.print("{x}", .{n.salt}); + try w.print(" {s}", .{encoding.base32HexEncode(&b32, n.next_hashed_owner)}); + return writeTypes(w, n.types); } else |_| {}, else => {}, } @@ -842,3 +843,54 @@ test "formatRr emits complete, parseable RDATA for DNSKEY, NSEC and NSEC3" { try testing.expect(std.mem.startsWith(u8, w.buffered(), "example. 3600 IN DNSKEY \\# 2048 01 00 03 08 5a")); } } + +test "formatRr writes an empty NSEC3 salt as \"-\"" { + // RFC 5155 §3.3: an empty salt is written "-". RFC 9276 recommends the + // empty salt, so it is the common case; an empty field would shift every + // later field and make the record unparseable. + const owner = try Name.fromText("example."); + const hash = [_]u8{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 }; + var rd: [64]u8 = undefined; + rd[0] = 1; // SHA-1 + rd[1] = 0; // flags + std.mem.writeInt(u16, rd[2..4], 0, .big); + rd[4] = 0; // salt length + rd[5] = 20; + @memcpy(rd[6..26], &hash); + rd[26] = 0; + rd[27] = 1; + rd[28] = 0x40; // A + const rr: Rr = .{ .name = owner, .type = .nsec3, .class = .in, .ttl = 300, .rdata = rd[0..29] }; + var out: [256]u8 = undefined; + var w = std.Io.Writer.fixed(&out); + try formatRr(&w, &rr); + const got = w.buffered(); + const prefix = "example. 300 IN NSEC3 1 0 0 - "; + try testing.expect(std.mem.startsWith(u8, got, prefix)); + // The next hashed owner follows the salt: 20 octets are 32 base32hex digits. + const rest = got[prefix.len..]; + try testing.expectEqual(@as(?usize, 32), std.mem.indexOfScalar(u8, rest, ' ')); + try testing.expect(std.mem.endsWith(u8, got, " A")); +} + +test "formatRr writes every type in an NSEC bitmap, however many" { + // Window 0 with all 256 bits set: every type 0..255. A fixed buffer of + // types would truncate this silently and still print parseable text. + const owner = try Name.fromText("example."); + var rd: [3 + 2 + 32]u8 = undefined; + @memcpy(rd[0..3], &[_]u8{ 1, 'x', 0 }); // next name "x." + rd[3] = 0; // window 0 + rd[4] = 32; + @memset(rd[5..], 0xFF); + const rr: Rr = .{ .name = owner, .type = .nsec, .class = .in, .ttl = 300, .rdata = &rd }; + var out: [8192]u8 = undefined; + var w = std.Io.Writer.fixed(&out); + try formatRr(&w, &rr); + const got = w.buffered(); + // Owner, TTL, class, type, next name, then one field per type. + var fields: usize = 0; + var it = std.mem.tokenizeScalar(u8, got, ' '); + while (it.next()) |_| fields += 1; + try testing.expectEqual(@as(usize, 5 + 256), fields); + try testing.expect(std.mem.endsWith(u8, got, " TYPE255") or std.mem.endsWith(u8, got, " ANY")); +} diff --git a/zig-dnssec_chora.deed b/zig-dnssec_chora.deed index 2085da80..a9aeb880 100644 --- a/zig-dnssec_chora.deed +++ b/zig-dnssec_chora.deed @@ -1185,6 +1185,7 @@ "build/container/stapeln/manifest.toml" "build/container/stapeln/rokur.toml" "build/container/stapeln/vordr.toml" + "build/guix.scm" "build/just/container.just" "build/just/groove.just" "build/just/repo-init.just" @@ -1203,6 +1204,7 @@ "docs/governance/TEMPLATE-STANDARDS-AUDIT.adoc" "docs/onboarding/QUICKSTART-DEV.adoc" "docs/onboarding/QUICKSTART-MAINTAINER.adoc" + "docs/onboarding/QUICKSTART-USER.adoc" "docs/practice/AI-CONVENTIONS.adoc" "docs/practice/STATE-VISUALIZER-GUIDE.adoc" "docs/status/PROOF-NEEDS.adoc"