diff --git a/.github/workflows/zig-ci.yml b/.github/workflows/zig-ci.yml index 03df6527..7cf81ebc 100644 --- a/.github/workflows/zig-ci.yml +++ b/.github/workflows/zig-ci.yml @@ -39,9 +39,9 @@ jobs: echo "$RUNNER_TEMP/zig-x86_64-linux-${ZIG_VERSION}" >> "$GITHUB_PATH" - name: Formatting - run: zig fmt --check build.zig src/root.zig src/wire src/dnssec src/stub src/cli tests + run: zig fmt --check build.zig src/root.zig src/wire src/dnssec src/stub src/cli src/interface/ffi tests - - name: Unit, RFC-vector, denial, replay and fuzz-corpus tests + - name: Unit, RFC-vector, denial, replay, fuzz-corpus and C ABI tests run: zig build test --summary all - name: ReleaseSafe build @@ -51,3 +51,56 @@ jobs: run: | zig build fuzz-tool -Doptimize=ReleaseSafe ./zig-out/bin/dnssec-fuzz all 20 0x2026 + + # The Idris2 side of the ABI seam: typecheck the proofs, then run the + # Idris2 -> C ABI -> Zig end-to-end test. Idris2 is built from a pinned + # release commit (it has no checksummed binary release). + abi-seam: + runs-on: ubuntu-24.04 + timeout-minutes: 45 + permissions: + contents: read + env: + ZIG_VERSION: "0.17.0" + ZIG_SHA256: "1cbe9df9f27e6b78d14ccbca43b6703a404ef79ef1c463de901d7f088d4e2026" + IDRIS2_TAG: "v0.7.0" + IDRIS2_COMMIT: "27780073c8631826d846499840b3857d9b9a4fd5" + steps: + - uses: actions/checkout@v7.0.1 + + - name: Install Zig (checksum-verified) + run: | + set -euo pipefail + curl --proto '=https' --tlsv1.2 -fsSL -o "$RUNNER_TEMP/zig.tar.xz" \ + "https://ziglang.org/download/${ZIG_VERSION}/zig-x86_64-linux-${ZIG_VERSION}.tar.xz" + echo "${ZIG_SHA256} $RUNNER_TEMP/zig.tar.xz" | sha256sum -c - + tar -xJf "$RUNNER_TEMP/zig.tar.xz" -C "$RUNNER_TEMP" + echo "$RUNNER_TEMP/zig-x86_64-linux-${ZIG_VERSION}" >> "$GITHUB_PATH" + + - name: Build Idris2 from the pinned release commit + run: | + set -euo pipefail + sudo apt-get update -q + sudo apt-get install -y -q chezscheme libgmp-dev + git clone -q --depth 1 --branch "$IDRIS2_TAG" https://github.com/idris-lang/Idris2.git "$RUNNER_TEMP/idris2-src" + test "$(git -C "$RUNNER_TEMP/idris2-src" rev-parse HEAD)" = "$IDRIS2_COMMIT" + make -C "$RUNNER_TEMP/idris2-src" bootstrap SCHEME=chezscheme PREFIX="$RUNNER_TEMP/idris2" -j"$(nproc)" + make -C "$RUNNER_TEMP/idris2-src" install PREFIX="$RUNNER_TEMP/idris2" + echo "$RUNNER_TEMP/idris2/bin" >> "$GITHUB_PATH" + + # `idris2 --typecheck` can exit 0 with an Error: line (see + # scripts/check-proofs.sh), so both are checked. + - name: Typecheck the Idris2 ABI model + run: | + set -euo pipefail + out="$(idris2 --typecheck src/interface/abi.ipkg 2>&1)" || { echo "$out"; exit 1; } + echo "$out" + if echo "$out" | grep -q '^Error'; then exit 1; fi + + - name: Idris2 -> C ABI -> Zig end-to-end test + run: | + set -euo pipefail + zig build ffi + idris2 --build src/interface/E2e/abi-e2e.ipkg + LD_LIBRARY_PATH=zig-out/lib src/interface/E2e/build/exec/abi-e2e \ + tests/testdata/crosscheck.traces tests/testdata/crosscheck-root.anchor diff --git a/CHANGELOG.adoc b/CHANGELOG.adoc index 99019f64..2852f5df 100644 --- a/CHANGELOG.adoc +++ b/CHANGELOG.adoc @@ -25,6 +25,11 @@ https://semver.org/spec/v2.0.0.html[Semantic Versioning]. recorded responses replayed offline, mutation attacks, fuzz targets with a corpus; a cross-check against Unbound and ldns (`tests/crosscheck/`). * `zig-ci` workflow; container image (`build/container/Containerfile`). +* C ABI (`zig build ffi`): `zig_dnssec.h` as the contract, a pure-Zig + `libzig_dnssec` checked against it at compile time, and an Idris2 model of + the interface (`src/interface/Abi/`) whose result type cannot carry an + answer for a bogus or indeterminate verdict; tests keep the three in step, + and an Idris2 end-to-end test (`just abi-e2e`) runs in CI. ==== Fixed @@ -36,6 +41,9 @@ https://semver.org/spec/v2.0.0.html[Semantic Versioning]. ==== Changed * Toolchain pin: Zig 0.16.0 → 0.17.0 (`mise.lock`). +* `src/interface/`: the template's example ABI/FFI seam is replaced by the + zig-dnssec C ABI; its separate `ffi/build.zig` is gone (the root + `build.zig` builds and tests the seam). === Inherited from rsr-template-repo at mint (2026-10-13) diff --git a/Justfile b/Justfile index ff77b8d4..bccb60ce 100644 --- a/Justfile +++ b/Justfile @@ -130,10 +130,9 @@ clean-all: clean # TEST & QUALITY # ═══════════════════════════════════════════════════════════════════════════════ -# Run every detected language's tests: `zig build test` covers src/interface/ffi -# (unit tests in src/main.zig, test/integration_test.zig). It compiles only after -# `just repo-init` has filled the template tokens, so an un-initialised template -# fails here loudly instead of reporting a pass over nothing. +# Run every detected language's tests: `zig build test` (library, C ABI and the +# Idris2/header consistency checks in src/interface/ffi/test/) and +# `idris2 --typecheck src/interface/abi.ipkg` (the seam's proofs). test: provision::test # Run tests with verbose output @@ -145,9 +144,15 @@ test-smoke: @echo "FAIL: 'just test-smoke' is not wired yet — no smoke check ran. Edit the 'test-smoke' recipe." >&2; exit 1 # Run end-to-end tests (full pipeline: build → run → verify) -e2e: +e2e: abi-e2e bash tests/e2e.sh +# Idris2 -> C ABI -> Zig validator, over the recorded fixtures. Needs zig and idris2. +abi-e2e: + zig build ffi + idris2 --build src/interface/E2e/abi-e2e.ipkg + LD_LIBRARY_PATH=zig-out/lib src/interface/E2e/build/exec/abi-e2e tests/testdata/crosscheck.traces tests/testdata/crosscheck-root.anchor + # Run aspect tests (cross-cutting concern validation) aspect: # Aspect tests validate architectural invariants: diff --git a/README.adoc b/README.adoc index dd941384..c1f79540 100644 --- a/README.adoc +++ b/README.adoc @@ -91,6 +91,15 @@ $ ./zig-out/bin/dnssec-stub --doh https://cloudflare-dns.com/dns-query dnssec-fa verdict=bogus reason=dnskey_not_authenticated at=dnssec-failed.org. type=dnskey ---- +=== From C, Idris2 and other languages + +`zig build ffi` builds `libzig_dnssec` (static and shared, pure Zig, no libc) and +installs `zig_dnssec.h`. The header is the contract: a verdict whose security is never +`SECURE` unless the call succeeded, and answer text only for `SECURE` and `INSECURE`. +The caller supplies the transport as a callback. An Idris2 model of the interface in +`src/interface/Abi/` states the same rule as a type. See +link:src/interface/README.adoc[`src/interface/README.adoc`]. + [[ai-install]] == AI-Assisted Installation (Recommended) @@ -121,7 +130,9 @@ is sent anywhere. Running the tests needs no network. Only the live examples abo [source,console] ---- -zig build test # unit, RFC vector, denial, replay and fuzz smoke tests +zig build test # unit, RFC vector, denial, replay, fuzz smoke and C ABI tests +idris2 --typecheck src/interface/abi.ipkg # proofs of the Idris2 ABI model +just abi-e2e # Idris2 -> C ABI -> Zig end to end zig build fuzz --fuzz=500K -Doptimize=ReleaseSafe # coverage-guided fuzzing zig build fuzz-tool -Doptimize=ReleaseSafe && ./zig-out/bin/dnssec-fuzz all 60 tests/crosscheck/make-zones.sh && tests/crosscheck/servers.sh start && tests/crosscheck/run.sh diff --git a/build.zig b/build.zig index f1116046..ba4b85f2 100644 --- a/build.zig +++ b/build.zig @@ -90,4 +90,82 @@ pub fn build(b: *std.Build) void { }); const fuzz_install = b.addInstallArtifact(fuzz_exe, .{}); b.step("fuzz-tool", "Build the standalone mutation fuzzer (use -Doptimize=ReleaseSafe)").dependOn(&fuzz_install.step); + + // ---- C ABI seam (src/interface/) --------------------------------------- + // The header is the contract: translate-c turns it into the module the + // Zig implementation is type-checked against. + const header_path = b.path("src/interface/ffi/include/zig_dnssec.h"); + const header_mod = b.addTranslateC(.{ + .root_source_file = header_path, + .target = target, + .optimize = optimize, + .link_libc = false, + }).createModule(); + + const ffi_static = b.addLibrary(.{ + .name = "zig_dnssec", + .linkage = .static, + .root_module = ffiModule(b, target, optimize, mod, header_mod, null), + }); + const ffi_shared = b.addLibrary(.{ + .name = "zig_dnssec", + .linkage = .dynamic, + .root_module = ffiModule(b, target, optimize, mod, header_mod, true), + }); + const ffi_step = b.step("ffi", "Build the C ABI (static and shared libzig_dnssec) and install the header"); + ffi_step.dependOn(&b.addInstallArtifact(ffi_static, .{}).step); + ffi_step.dependOn(&b.addInstallArtifact(ffi_shared, .{}).step); + ffi_step.dependOn(&b.addInstallFileWithDir(header_path, .header, "zig_dnssec.h").step); + + // C-ABI behaviour: calls through the header's declarations into the + // library, plus allocator-checked calls of the same code. + const ffi_tests = b.addTest(.{ .root_module = b.createModule(.{ + .root_source_file = b.path("src/interface/ffi/test/abi_test.zig"), + .target = target, + .optimize = optimize, + .imports = &.{ + .{ .name = "ffi", .module = ffiModule(b, target, optimize, mod, header_mod, null) }, + .{ .name = "zig_dnssec_h", .module = header_mod }, + .{ .name = "dnssec", .module = mod }, + }, + }) }); + ffi_tests.root_module.addAnonymousImport("crosscheck.traces", .{ .root_source_file = b.path("tests/testdata/crosscheck.traces") }); + ffi_tests.root_module.addAnonymousImport("crosscheck-root.anchor", .{ .root_source_file = b.path("tests/testdata/crosscheck-root.anchor") }); + test_step.dependOn(&b.addRunArtifact(ffi_tests).step); + + // The Idris2 model and the header must agree: codes, names and layout. + const seam_tests = b.addTest(.{ .root_module = b.createModule(.{ + .root_source_file = b.path("src/interface/ffi/test/seam_test.zig"), + .target = target, + .optimize = optimize, + .imports = &.{ + .{ .name = "ffi", .module = ffiModule(b, target, optimize, mod, header_mod, null) }, + .{ .name = "zig_dnssec_h", .module = header_mod }, + .{ .name = "dnssec", .module = mod }, + }, + }) }); + seam_tests.root_module.addAnonymousImport("Types.idr", .{ .root_source_file = b.path("src/interface/Abi/Types.idr") }); + seam_tests.root_module.addAnonymousImport("Layout.idr", .{ .root_source_file = b.path("src/interface/Abi/Layout.idr") }); + seam_tests.root_module.addAnonymousImport("Foreign.idr", .{ .root_source_file = b.path("src/interface/Abi/Foreign.idr") }); + test_step.dependOn(&b.addRunArtifact(seam_tests).step); +} + +fn ffiModule( + b: *std.Build, + target: std.Build.ResolvedTarget, + optimize: std.builtin.OptimizeMode, + dnssec: *std.Build.Module, + header: *std.Build.Module, + pic: ?bool, +) *std.Build.Module { + return b.createModule(.{ + .root_source_file = b.path("src/interface/ffi/src/main.zig"), + .target = target, + .optimize = optimize, + .pic = pic, + .imports = &.{ + .{ .name = "dnssec", .module = dnssec }, + .{ .name = "zig_dnssec_h", .module = header }, + }, + }); } diff --git a/docs/AI_INSTALLATION_GUIDE.adoc b/docs/AI_INSTALLATION_GUIDE.adoc index cada923e..994d6d3b 100644 --- a/docs/AI_INSTALLATION_GUIDE.adoc +++ b/docs/AI_INSTALLATION_GUIDE.adoc @@ -34,6 +34,8 @@ cd zig-dnssec === 3. Install the toolchain The toolchain is pinned in `mise.toml` / `mise.lock` (Zig 0.17.0, just, shellcheck). +Idris2 0.7.0, which checks the ABI model in `src/interface/Abi/`, is not a mise tool: +it comes from pack or a source build (`just doctor` reports whether it is present). [source,bash] ---- @@ -48,7 +50,9 @@ SHA-256 against `mise.lock` (or its minisign signature) before use. [source,bash] ---- -zig build test --summary all # unit, RFC-vector, denial, replay, fuzz-corpus tests +zig build test --summary all # unit, RFC-vector, denial, replay, fuzz-corpus, C ABI tests +just test # the above plus the Idris2 typecheck +just abi-e2e # Idris2 -> C ABI -> Zig end to end zig build -Doptimize=ReleaseSafe # library + dnssec-stub just validate # repository-standard checks ---- diff --git a/docs/architecture/THREAT-MODEL.adoc b/docs/architecture/THREAT-MODEL.adoc index 85019790..3766d4d3 100644 --- a/docs/architecture/THREAT-MODEL.adoc +++ b/docs/architecture/THREAT-MODEL.adoc @@ -146,6 +146,25 @@ Every item here is a known limitation, not a hidden one. as malformed; trailing zero octets are tolerated. * A response must answer exactly the question asked, with `QR=1` and opcode QUERY. +== The C ABI (`src/interface/`) + +* *What C callers are trusted for* — what any C API trusts: NUL-terminated strings, a + verdict pointer to a whole `zig_dnssec_verdict`, and `text_cap` writable bytes at + `text`. Breaking that is undefined behaviour. The library itself checks NULL + pointers, unknown policy bits, meta-type and zero query types, and malformed names, + anchors and traces, and reports each as a status with `security` NONE. +* *The transport callback is untrusted* — its responses go through the same strict + parser and validation as DoH responses, and a reported length beyond the buffer is a + failed exchange. A failure of the first query is `ZIG_DNSSEC_ERR_QUERY_FAILED`; a + failure of a later DS or DNSKEY fetch is a verdict (`bogus` or `indeterminate`). +* *The caller supplies the time* — the library never reads the clock, so a wrong `now` + gives wrong signature-validity decisions. +* No global state; each call allocates with Zig's thread-safe general-purpose allocator + and frees everything before it returns. The shared object exports the six header + functions and nothing else, and links no libc. +* The Idris2 wrapper reads the verdict struct little-endian and is tested on x86_64 + Linux only. + == Trust-anchor handling assumptions * Anchors are *static configuration*: DS and/or DNSKEY records in presentation format diff --git a/docs/reports/VERIFICATION.adoc b/docs/reports/VERIFICATION.adoc index 4d9c8a15..99469c5b 100644 --- a/docs/reports/VERIFICATION.adoc +++ b/docs/reports/VERIFICATION.adoc @@ -3,14 +3,15 @@ = zig-dnssec: what has been verified, and what has not :toc: -Status as of 2026-10-13, Zig 0.17.0. Every claim below is tagged with the estate's -five statuses and names the artefact that discharges it. Nothing is tagged PROVEN: -there is no machine-checked proof in this repository yet. +Status as of 2026-10-13, Zig 0.17.0, Idris2 0.7.0. Every claim below is tagged with the +estate's five statuses and names the artefact that discharges it. The PROVEN rows are +about the C ABI seam (`src/interface/`) and are checked by Idris2; nothing about the +validator's own logic is proved yet. [cols="1,4",options="header"] |=== | Status | Meaning here -| PROVEN | discharged by a machine-checked proof (none yet) +| PROVEN | discharged by a machine-checked proof (Idris2 typecheck of `src/interface/abi.ipkg`) | TESTED | discharged by a test or run that is in the repository and reproducible | ASSUMED | relied on without being checked here | DESIGNED | built and reasoned about, but not exercised by a test @@ -74,12 +75,41 @@ there is no machine-checked proof in this repository yet. | Failures are never reported as insecure | TESTED (for the cases above) / DESIGNED (in general) | the mutation tests assert `bogus`; the type of `Verdict` makes the answer unreachable - from failure arms. A general proof is OPEN (see the estate note below). + from failure arms, and at the C ABI seam the Idris2 model makes it unrepresentable + (PROVEN row above). A proof about the validator's own decisions is OPEN (see the + estate note below). | Resource limits (fetches, signatures, failures per RRset, NSEC3 hashes) | TESTED | `tests/replay.zig` budget cases; `tests/denial.zig` hash budget +| C ABI seam, Idris2 model: every status, security and reason code round-trips; code 0 + decodes to no verdict; the verdict struct's fields are aligned, in order, not + overlapping, and its size is a multiple of its alignment; an `Outcome` for `Bogus` or + `Indeterminate` cannot hold an answer, and `answerOf` cannot be applied to one +| PROVEN +| `src/interface/Abi/Types.idr`, `Layout.idr`, `Foreign.idr` (no `believe_me` or + `assert_total`; `%default total`); `idris2 --typecheck src/interface/abi.ipkg` + +| The Idris2 model describes the real interface: codes, field offsets and sizes, struct + size, `%foreign` parameter kinds agree with the C header as the C compiler sees it; the + Zig exports have exactly the header's types; every validator reason has a header code +| TESTED (model ↔ header) / checked at compile time (Zig ↔ header) +| `src/interface/ffi/test/seam_test.zig`; `exportChecked` and `reasonCode` in + `src/interface/ffi/src/main.zig`. Eleven deliberate mismatches, one of each kind, were + each caught when this was written + +| C ABI fail-closed rules: security NONE on every non-OK status, no answer text for + bogus verdicts (all 51 recorded bogus scenarios), unknown policy bits and meta-types + rejected, buffer sizing, callback transport, no leaks, allocation failure at every point +| TESTED +| `src/interface/ffi/test/abi_test.zig` (through the header's declarations) + +| Idris2 -> C ABI -> Zig end to end +| TESTED +| `just abi-e2e` (`src/interface/E2e/Main.idr`, 9 checks over recorded responses); + `abi-seam` job in `.github/workflows/zig-ci.yml` + | Live validation against the real root | TESTED (manually, 2026-10-13) | `dnssec-stub` over Cloudflare DoH through an HTTP CONNECT proxy: `example.com A` @@ -95,7 +125,8 @@ there is no machine-checked proof in this repository yet. | Container build and test | TESTED | `build/container/Containerfile --target test` built on Wolfi with the - checksum-verified Zig 0.17.0 tarball; all 88 tests passed inside it + checksum-verified Zig 0.17.0 tarball; all 110 tests (C ABI tests included) passed + inside it | `crosscheck` and `runtime` container targets | DESIGNED @@ -172,12 +203,16 @@ include::FUZZ-RESULTS.adoc[] * `drill -S` reported success for the DNSKEY RRset of a zone whose signatures had expired a month earlier. Not investigated further; noted for whoever reviews ldns. -== Estate note: where a proof would go +== Estate note: what is proved, and where the next proof would go The guarantee "answer data is only reachable with secure evidence or a proven-insecure -reason" is currently enforced by the shape of a Zig tagged union and by tests. It is the -kind of invariant the estate's epistemic-types work is meant to state: a `secure` answer -as knowledge, `insecure` as justified non-knowledge, and the absence of any path from -`bogus` to an answer. A small Idris2 model of `Verdict` at the ABI seam, with that -property as a type, is a short and legitimate next step; it would move the row -"Failures are never reported as insecure" from TESTED/DESIGNED towards PROVEN. +reason" is the kind of invariant the estate's epistemic-types work is meant to state: a +`secure` answer as knowledge, `insecure` as justified absence of authentication, and no +path from `bogus` to an answer. It is now stated as a type at the ABI seam +(`src/interface/Abi/`): an Idris2 caller cannot receive answer data with a bogus or +indeterminate verdict, even if the library wrote answer text for one (the FFI +marshalling and the library's memory safety are assumed). Inside the library the same +guarantee rests on the shape of a Zig tagged union and on tests. The next step towards +PROVEN is a model of the validator's decision procedure (the chain walk and the denial +proofs) in which "secure" can only be built from verified signatures up to an anchor; +that is a larger piece of work and is not started. diff --git a/docs/status/ROADMAP.adoc b/docs/status/ROADMAP.adoc index 31b3d78a..7f05ed3e 100644 --- a/docs/status/ROADMAP.adoc +++ b/docs/status/ROADMAP.adoc @@ -4,8 +4,8 @@ == Current status -Experimental. The first milestone (codec, DNSSEC validation, DoH stub) is complete and -tested, and has *not* been independently reviewed. See +Experimental. Milestone 1 (codec, DNSSEC validation, DoH stub) and milestone 2 (the C +ABI seam) are complete and tested, and have *not* been independently reviewed. See `docs/reports/VERIFICATION.adoc` for what is and is not verified. == Milestone 1 — codec, validator, DoH stub (done, 2026-10-13) @@ -19,6 +19,15 @@ tested, and has *not* been independently reviewed. See * [x] Cross-check against Unbound and ldns on a fixed zone set * [x] CI workflow running the tests +== Milestone 2 — C ABI seam (done, 2026-10-13) + +* [x] C header as the contract (`src/interface/ffi/include/zig_dnssec.h`), version 1 +* [x] Pure-Zig implementation, type-checked against the header at compile time +* [x] Idris2 model: codes with round-trip proofs, verdict layout proofs, and a result + type that cannot carry an answer for a bogus or indeterminate verdict +* [x] Tests keeping header, Zig and Idris2 in step; C-ABI behaviour tests +* [x] Idris2 -> C ABI -> Zig end-to-end test, in CI + == Next . *Independent review* of the validator, the proof logic, the parsers and the DoH @@ -28,16 +37,14 @@ tested, and has *not* been independently reviewed. See on prompts, as the template's onboarding docs warn; a table cell lost to placeholder deletion; references to the template's own issues renamed by the global substitution; REPOSITORY-MAP.adoc and the coaptation receipt left stale; the - ABI/FFI seam below); add a Zig-library archetype so `build.zig` and - `build.zig.zon` are expected at the root. -. Specialise the ABI/FFI seam in `src/interface/`. As minted it is the template's - generic example, not wired to this library: the Zig side does not compile on - Zig 0.17.0 (`Allocator.dupeZ` is gone), its `Result` enum differs from the Idris2 - one, and the two sides name different symbols (`rsr_*` against `zig_dnssec_*`). - The replacement: an Idris2 model of the verdict at the seam, stating "no answer - data without secure or proven-insecure evidence" as a type (estate - epistemic-types work), and a Zig C ABI over the validator, with tests that keep - the two sides in step. + template's example ABI/FFI seam, which does not build on Zig 0.17.0 and whose + Idris2 and Zig sides disagree on result codes and symbol names); add a + Zig-library archetype so `build.zig` and `build.zig.zon` are expected at the root. +. A live transport for Idris2 callers: a DNS-over-HTTPS entry point in the C ABI, or + an Idris2 callback for `zig_dnssec_validate`. +. A model of the validator's decision procedure in which "secure" can only be built + from verified signatures up to an anchor (`docs/reports/VERIFICATION.adoc`, estate + note). == Later diff --git a/src/interface/Abi/Foreign.idr b/src/interface/Abi/Foreign.idr index ca66b082..52845ef2 100644 --- a/src/interface/Abi/Foreign.idr +++ b/src/interface/Abi/Foreign.idr @@ -1,83 +1,173 @@ -- SPDX-License-Identifier: MPL-2.0 --- Copyright (c) Jonathan D.A. Jewell -||| Foreign Function Interface Bridge +-- SPDX-FileCopyrightText: 2026 Jonathan D.A. Jewell +||| Idris2 bindings to the zig-dnssec C ABI (libzig_dnssec, built by +||| `zig build ffi`), and a safe wrapper whose result type keeps the seam's +||| rule: an answer is only ever returned with a Secure or Insecure verdict. ||| -||| This module defines the raw FFI calls and their safe wrappers, -||| implemented in the Zig FFI layer. +||| The wrapper does not trust the library to keep that rule. It decodes the +||| verdict first and reads answer text only when the decoded security is +||| usable, so even a library that wrote text for a Bogus verdict could not +||| hand it to an Idris caller. +||| +||| What is trusted here, and not proved: that the foreign signatures below +||| match the header (checked by `zig build test`, which parses this file), and +||| the Chez/RefC FFI marshalling itself. Raw struct fields are read +||| little-endian, as Data.Buffer does; big-endian targets are not supported. module Abi.Foreign import Abi.Types import Abi.Layout +import Data.Buffer +import Data.Fin +import Data.Vect %default total -------------------------------------------------------------------------------- --- Library Lifecycle +-- Raw bindings (types follow zig_dnssec.h) -------------------------------------------------------------------------------- -||| Raw FFI call to initialize the library -%foreign "C:rsr_init,librsr" -prim__init : PrimIO Bits64 +%foreign "C:zig_dnssec_abi_version,libzig_dnssec" +prim__abiVersion : PrimIO Bits32 -||| Raw FFI call to free library resources -%foreign "C:rsr_free,librsr" -prim__free : Bits64 -> PrimIO () +-- trace, anchors, qname, qtype, now, policy, out, text, text_cap +%foreign "C:zig_dnssec_validate_trace,libzig_dnssec" +prim__validateTrace : String -> String -> String -> Bits16 -> Int64 -> Bits32 -> Buffer -> Buffer -> Bits64 -> PrimIO Int -||| Safe wrapper for initialization -export -init : IO (Maybe Handle) -init = do - ptr <- primIO prim__init - pure (createHandle ptr) +-- The same function with anchors = NULL (the built-in IANA root anchors). +%foreign "C:zig_dnssec_validate_trace,libzig_dnssec" +prim__validateTraceRoot : String -> AnyPtr -> String -> Bits16 -> Int64 -> Bits32 -> Buffer -> Buffer -> Bits64 -> PrimIO Int + +||| The ABI version this binding was written for. +public export +abiVersion : Bits32 +abiVersion = 1 -||| Safe wrapper for cleanup +||| The ABI version of the library actually loaded. export -free : Handle -> IO () -free h = primIO (prim__free h.ptr) +linkedAbiVersion : HasIO io => io Bits32 +linkedAbiVersion = primIO prim__abiVersion -------------------------------------------------------------------------------- --- Core Operations +-- Results -------------------------------------------------------------------------------- -||| Raw FFI call for main processing -%foreign "C:rsr_process,librsr" -prim__process : Bits64 -> Bits32 -> PrimIO Bits32 - -||| Safe wrapper with error handling +||| A decoded verdict. The type of `answer` depends on `security`: text for +||| Secure and Insecure, `()` for Bogus and Indeterminate (Abi.Types.AnswerFor). +public export +record Outcome where + constructor MkOutcome + security : Security + reason : Maybe Reason + ||| Zone where insecurity was established, or name where validation failed. + location : String + rcode : Bits16 + rtype : Bits16 + ttl : Bits32 + fetches : Bits32 + verifications : Bits32 + answer : AnswerFor security + +||| The answer of a usable outcome. There is no way to call this for a Bogus or +||| Indeterminate outcome: no `Usable` value exists for them. export -process : Handle -> Bits32 -> IO (Either Result Bits32) -process h input = do - result <- primIO (prim__process h.ptr input) - if result == 0 - then pure (Left Error) - else pure (Right result) +answerOf : (o : Outcome) -> Usable o.security -> String +answerOf (MkOutcome Secure _ _ _ _ _ _ _ a) UsableSecure = a +answerOf (MkOutcome Insecure _ _ _ _ _ _ _ a) UsableInsecure = a + +public export +data CallError + = ||| The library refused the call (status other than OK). + Refused Status + | ||| The library broke the header's contract (an unknown code, or OK with no verdict). + BrokenContract String + | ||| Could not allocate the buffers. + NoMemory + +public export +Show CallError where + show (Refused s) = "refused: " ++ show s + show (BrokenContract m) = "broken contract: " ++ m + show NoMemory = "out of memory" -------------------------------------------------------------------------------- --- Status and Metrics +-- Reading the raw verdict -------------------------------------------------------------------------------- -||| Get the current error description from the library -%foreign "C:rsr_get_error,librsr" -prim__getError : Bits64 -> PrimIO (Ptr String) - -||| Detailed error string helper -export -errorDescription : Result -> String -errorDescription Ok = "Success" -errorDescription Error = "Generic error" -errorDescription InvalidParam = "Invalid parameter" -errorDescription Busy = "Library is busy" +verdictSize : Int +verdictSize = cast verdictLayout.totalSize + +off : (i : Fin 10) -> (n : String) -> {auto 0 named : (index i Abi.Layout.verdictFields).name = n} -> Int +off i n = cast (offsetNamed i n) + +||| Length of the NUL-terminated string at `off`, at most `limit` bytes. +cStringLength : HasIO io => Buffer -> (off : Int) -> (limit : Nat) -> io Int +cStringLength buf off limit = go 0 limit + where + go : Int -> Nat -> io Int + go n Z = pure n + go n (S k) = do + b <- getBits8 buf (off + n) + if b == 0 then pure n else go (n + 1) k + +||| Decodes the verdict struct. `readText` is run only for usable verdicts. +decodeVerdict : HasIO io => Buffer -> (readText : Bits32 -> io String) -> io (Either CallError Outcome) +decodeVerdict v readText = do + sec <- getBits8 v (off 0 "security") + rsn <- getBits8 v (off 1 "reason") + rc <- getBits16 v (off 3 "rcode") + rt <- getBits16 v (off 4 "rtype") + tl <- getBits32 v (off 5 "ttl") + fe <- getBits32 v (off 6 "fetches") + ve <- getBits32 v (off 7 "verifications") + tlen <- getBits32 v (off 8 "text_len") + wlen <- cStringLength v (off 9 "where") (minus whereMax 1) + loc <- getString v (off 9 "where") wlen + let reason = if rsn == 0 then Right Nothing else maybe (Left rsn) (Right . Just) (reasonFromCode rsn) + case (securityFromCode sec, reason) of + (Nothing, _) => pure (Left (BrokenContract ("security code " ++ show sec ++ " with status OK"))) + (_, Left r) => pure (Left (BrokenContract ("unknown reason code " ++ show r))) + (Just Secure, Right why) => do + t <- readText tlen + pure (Right (MkOutcome Secure why loc rc rt tl fe ve t)) + (Just Insecure, Right why) => do + t <- readText tlen + pure (Right (MkOutcome Insecure why loc rc rt tl fe ve t)) + (Just Bogus, Right why) => pure (Right (MkOutcome Bogus why loc rc rt tl fe ve ())) + (Just Indeterminate, Right why) => pure (Right (MkOutcome Indeterminate why loc rc rt tl fe ve ())) -------------------------------------------------------------------------------- --- Documentation +-- Safe wrapper -------------------------------------------------------------------------------- -||| Summary of ABI safety properties: -||| 1. All functions are total (total keyword enforced). -||| 2. Pointers are verified non-null before being wrapped in Handle. -||| 3. Memory layouts are proven C-ABI compliant in Abi.Layout. -||| 4. FFI boundary uses explicitly tagged types from Abi.Types. -public export -abiSafetyGuarantees : String -abiSafetyGuarantees = "RSR-Template ABI: 4 proven safety properties for FFI integration" +||| Validates `qname`/`qtype` against a recorded trace (see +||| 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. +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) + where + call : Buffer -> Buffer -> Int -> io Int + call out text cap = case anchors of + Just a => primIO (prim__validateTrace trace a qname qtype now (policyWord policy) out text (cast cap)) + Nothing => primIO (prim__validateTraceRoot trace prim__getNullAnyPtr qname qtype now (policyWord policy) out text (cast cap)) + + attempt : Int -> Nat -> io (Either CallError Outcome) + attempt cap retries = do + Just out <- newBuffer verdictSize | Nothing => pure (Left NoMemory) + Just text <- newBuffer cap | Nothing => pure (Left NoMemory) + st <- call out text cap + case statusFromCode st of + Nothing => pure (Left (BrokenContract ("status code " ++ show st))) + Just Ok => decodeVerdict out (\n => getString text 0 (cast n)) + Just BufferTooSmall => case retries of + S k => do + need <- getBits32 out (off 8 "text_len") + attempt (cast need + 1) k + Z => pure (Left (Refused BufferTooSmall)) + Just s => pure (Left (Refused s)) diff --git a/src/interface/Abi/Layout.idr b/src/interface/Abi/Layout.idr index e1f42759..3c94a963 100644 --- a/src/interface/Abi/Layout.idr +++ b/src/interface/Abi/Layout.idr @@ -1,65 +1,34 @@ -- SPDX-License-Identifier: MPL-2.0 --- Copyright (c) Jonathan D.A. Jewell -||| ABI Layout Verification +-- SPDX-FileCopyrightText: 2026 Jonathan D.A. Jewell +||| Memory layout of `zig_dnssec_verdict` (src/interface/ffi/include/zig_dnssec.h), +||| with proofs that every field is aligned, that the fields are in order and do +||| not overlap, and that the struct size is a multiple of its alignment. ||| -||| This module provides formal proofs about memory layout, alignment, -||| and padding for C-compatible structs. +||| The offsets here are compared with the C compiler's (`@offsetOf` of the +||| translated header) by `zig build test`, so this model and the real struct +||| cannot drift silently. The model assumes natural alignment and 8-bit bytes, +||| as on the 64-bit targets the library is built for; it is tested on x86_64 +||| Linux only. module Abi.Layout -import Abi.Types -import Data.Vect +import Data.Fin +import Data.Nat import Data.So +import Data.Vect %default total -------------------------------------------------------------------------------- --- Alignment Invariants +-- Layout model -------------------------------------------------------------------------------- -||| Predicate: n divides m +||| n divides m public export data Divides : (n, m : Nat) -> Type where MkDivides : (k : Nat) -> (0 prf : m = k * n) -> Divides n m -||| Implementation of divides for common sizes -public export -div8_24 : Divides 8 24 -div8_24 = MkDivides 3 Refl - -public export -div4_0 : Divides 4 0 -div4_0 = MkDivides 0 Refl - -public export -div8_8 : Divides 8 8 -div8_8 = MkDivides 1 Refl - -public export -div8_16 : Divides 8 16 -div8_16 = MkDivides 2 Refl - -||| Calculate padding required for an offset to meet alignment -public export -paddingFor : (offset : Nat) -> (alignment : Nat) -> Nat -paddingFor offset 0 = 0 -paddingFor offset alignment = - let m = offset `mod` alignment in - if m == 0 - then 0 - else alignment `minus` m - -||| Align a size up to the next multiple of alignment -public export -alignUp : (size : Nat) -> (alignment : Nat) -> Nat -alignUp size alignment = - size + paddingFor size alignment - --------------------------------------------------------------------------------- --- Struct Model --------------------------------------------------------------------------------- - -||| Representation of a single field in a struct +||| A field: name, byte offset, size and alignment. public export record Field where constructor MkField @@ -68,61 +37,94 @@ record Field where size : Nat alignment : Nat -||| Valid memory layout for a C struct -public export -record StructLayout where - constructor MkStructLayout - {n : Nat} - fields : Vect n Field - totalSize : Nat - alignment : Nat - {auto 0 aligned : Divides alignment totalSize} - --------------------------------------------------------------------------------- --- Compliance Predicates --------------------------------------------------------------------------------- - -||| Proof that all fields in a struct are correctly aligned +||| Every field is aligned. public export -data FieldsAligned : Vect n Field -> Type where +data FieldsAligned : Vect k Field -> Type where NoFields : FieldsAligned [] ConsField : (f : Field) -> - (rest : Vect n Field) -> (0 prf : Divides f.alignment f.offset) -> FieldsAligned rest -> FieldsAligned (f :: rest) -||| Predicate: Struct is C-ABI compliant +||| Fields start at or after `from`, appear in increasing order without +||| overlapping, and the last one ends at or before `end`. public export -data CABICompliant : StructLayout -> Type where - CABIOk : (l : StructLayout) -> - (0 prf : FieldsAligned l.fields) -> - CABICompliant l +data InOrder : (from, end : Nat) -> Vect k Field -> Type where + Fits : (0 prf : So (lte from end)) -> InOrder from end [] + Next : + (f : Field) -> + (0 prf : So (lte from f.offset)) -> + InOrder (f.offset + f.size) end rest -> + InOrder from end (f :: rest) + +||| A C-compatible struct layout. +public export +record StructLayout where + constructor MkStructLayout + {0 k : Nat} + fields : Vect k Field + totalSize : Nat + alignment : Nat + +||| What makes a layout valid: aligned fields, no overlap, size a multiple of +||| the alignment. +public export +record CABICompliant (l : StructLayout) where + constructor CABIOk + 0 aligned : FieldsAligned l.fields + 0 ordered : InOrder 0 l.totalSize l.fields + 0 padded : Divides l.alignment l.totalSize -------------------------------------------------------------------------------- --- Example and Proofs +-- zig_dnssec_verdict -------------------------------------------------------------------------------- -||| Example: struct { int32_t x; int64_t y; double z; } -||| On 64-bit Linux, this should have size 24, alignment 8. +||| ZIG_DNSSEC_WHERE_MAX +public export +whereMax : Nat +whereMax = 1024 + +public export +verdictFields : Vect 10 Field +verdictFields = + [ MkField "security" 0 1 1 + , MkField "reason" 1 1 1 + , MkField "reserved" 2 2 2 + , MkField "rcode" 4 2 2 + , MkField "rtype" 6 2 2 + , MkField "ttl" 8 4 4 + , MkField "fetches" 12 4 4 + , MkField "verifications" 16 4 4 + , MkField "text_len" 20 4 4 + , MkField "where" 24 1024 1 + ] + public export -exampleLayout : StructLayout -exampleLayout = - MkStructLayout - [ MkField "x" 0 4 4 -- Bits32 at offset 0 - , MkField "y" 8 8 8 -- Bits64 at offset 8 (4 bytes padding) - , MkField "z" 16 8 8 -- Double at offset 16 - ] - 24 -- Total size: 24 bytes - 8 -- Alignment: 8 bytes - {aligned = div8_24} - -||| Proof that example layout is valid +verdictLayout : StructLayout +verdictLayout = MkStructLayout verdictFields 1048 4 + +export +verdictLayoutValid : CABICompliant Abi.Layout.verdictLayout +verdictLayoutValid = CABIOk + (ConsField _ (MkDivides 0 Refl) + (ConsField _ (MkDivides 1 Refl) + (ConsField _ (MkDivides 1 Refl) + (ConsField _ (MkDivides 2 Refl) + (ConsField _ (MkDivides 3 Refl) + (ConsField _ (MkDivides 2 Refl) + (ConsField _ (MkDivides 3 Refl) + (ConsField _ (MkDivides 4 Refl) + (ConsField _ (MkDivides 5 Refl) + (ConsField _ (MkDivides 24 Refl) + NoFields)))))))))) + (Next _ Oh (Next _ Oh (Next _ Oh (Next _ Oh (Next _ Oh + (Next _ Oh (Next _ Oh (Next _ Oh (Next _ Oh (Next _ Oh + (Fits Oh))))))))))) + (MkDivides 262 Refl) + +||| The offset of verdict field `i`, which must be called `n`: a reader that +||| names the wrong field does not typecheck. public export -exampleLayoutValid : CABICompliant Abi.Layout.exampleLayout -exampleLayoutValid = CABIOk Abi.Layout.exampleLayout ( - ConsField (MkField "x" 0 4 4) _ div4_0 ( - ConsField (MkField "y" 8 8 8) _ div8_8 ( - ConsField (MkField "z" 16 8 8) _ div8_16 ( - NoFields)))) +offsetNamed : (i : Fin 10) -> (n : String) -> {auto 0 named : (index i Abi.Layout.verdictFields).name = n} -> Nat +offsetNamed i _ = (index i verdictFields).offset diff --git a/src/interface/Abi/README.adoc b/src/interface/Abi/README.adoc index 4a99517a..e62680a7 100644 --- a/src/interface/Abi/README.adoc +++ b/src/interface/Abi/README.adoc @@ -1,3 +1,8 @@ // SPDX-License-Identifier: CC-BY-SA-4.0 -// Copyright (c) Jonathan D.A. Jewell -= abi Logic +// SPDX-FileCopyrightText: 2026 Jonathan D.A. Jewell += Idris2 model of the C ABI + +`Types.idr` (codes, round trips, what a verdict permits), `Layout.idr` (the verdict +struct, with alignment and no-overlap proofs) and `Foreign.idr` (bindings and the safe +wrapper). Typecheck with `idris2 --typecheck src/interface/abi.ipkg`. See +`../README.adoc`. diff --git a/src/interface/Abi/Types.idr b/src/interface/Abi/Types.idr index 9d300513..ed92aef0 100644 --- a/src/interface/Abi/Types.idr +++ b/src/interface/Abi/Types.idr @@ -1,112 +1,331 @@ -- SPDX-License-Identifier: MPL-2.0 --- Copyright (c) Jonathan D.A. Jewell -||| ABI Type Definitions Template +-- SPDX-FileCopyrightText: 2026 Jonathan D.A. Jewell +||| zig-dnssec ABI, version 1: the codes of the C interface and what a verdict +||| permits, as types. ||| -||| This module defines the Application Binary Interface (ABI) for this library. -||| All type definitions include formal proofs of correctness. +||| The contract is src/interface/ffi/include/zig_dnssec.h. Every code below is +||| compared with the header's macros by `zig build test` +||| (src/interface/ffi/test/seam_test.zig), so the two cannot drift silently. +||| +||| The central rule of the seam, stated here as a type rather than a comment: +||| answer data exists only with a SECURE verdict (authenticated to a trust +||| anchor) or an INSECURE one (proven unsigned, or allowed by an explicit +||| policy). A BOGUS or INDETERMINATE outcome has no field that could hold an +||| answer. In the estate's epistemic vocabulary, SECURE is knowledge, INSECURE +||| is justified absence of authentication, and BOGUS and INDETERMINATE are +||| failures that must not be mistaken for either. module Abi.Types -import Data.Bits -import Data.So -import Data.Vect -import Decidable.Equality - %default total -------------------------------------------------------------------------------- --- Platform Model +-- Call status -------------------------------------------------------------------------------- -||| Target platforms for the FFI bridge +||| ZIG_DNSSEC_OK and ZIG_DNSSEC_ERR_* public export -data Platform = Linux | MacOS | Windows | WASM | RISCV +data Status + = Ok + | InvalidArgument + | OutOfMemory + | BadAnchors + | BadName + | BadTrace + | QueryFailed + | BufferTooSmall -||| Pointer size in bits per platform public export -ptrSize : Platform -> Nat -ptrSize Linux = 64 -ptrSize MacOS = 64 -ptrSize Windows = 64 -ptrSize WASM = 32 -ptrSize RISCV = 64 +statusCode : Status -> Int +statusCode Ok = 0 +statusCode InvalidArgument = 1 +statusCode OutOfMemory = 2 +statusCode BadAnchors = 3 +statusCode BadName = 4 +statusCode BadTrace = 5 +statusCode QueryFailed = 6 +statusCode BufferTooSmall = 7 + +public export +statusFromCode : Int -> Maybe Status +statusFromCode 0 = Just Ok +statusFromCode 1 = Just InvalidArgument +statusFromCode 2 = Just OutOfMemory +statusFromCode 3 = Just BadAnchors +statusFromCode 4 = Just BadName +statusFromCode 5 = Just BadTrace +statusFromCode 6 = Just QueryFailed +statusFromCode 7 = Just BufferTooSmall +statusFromCode _ = Nothing + +export +statusRoundTrip : (s : Status) -> statusFromCode (statusCode s) = Just s +statusRoundTrip Ok = Refl +statusRoundTrip InvalidArgument = Refl +statusRoundTrip OutOfMemory = Refl +statusRoundTrip BadAnchors = Refl +statusRoundTrip BadName = Refl +statusRoundTrip BadTrace = Refl +statusRoundTrip QueryFailed = Refl +statusRoundTrip BufferTooSmall = Refl -||| Current target platform (detected at compile-time) public export -thisPlatform : Platform -thisPlatform = Linux -- Simplified for template +Show Status where + show Ok = "ok" + show InvalidArgument = "invalid_argument" + show OutOfMemory = "out_of_memory" + show BadAnchors = "bad_anchors" + show BadName = "bad_name" + show BadTrace = "bad_trace" + show QueryFailed = "query_failed" + show BufferTooSmall = "buffer_too_small" -------------------------------------------------------------------------------- --- Core Types +-- Security -------------------------------------------------------------------------------- -||| Return codes for FFI calls -public export -data Result = Ok | Error | InvalidParam | Busy - -||| Results are decidably equal -public export -implementation DecEq Result where - decEq Ok Ok = Yes Refl - decEq Error Error = Yes Refl - decEq InvalidParam InvalidParam = Yes Refl - decEq Busy Busy = Yes Refl - decEq Ok Error = No (\case Refl impossible) - decEq Ok InvalidParam = No (\case Refl impossible) - decEq Ok Busy = No (\case Refl impossible) - decEq Error Ok = No (\case Refl impossible) - decEq Error InvalidParam = No (\case Refl impossible) - decEq Error Busy = No (\case Refl impossible) - decEq InvalidParam Ok = No (\case Refl impossible) - decEq InvalidParam Error = No (\case Refl impossible) - decEq InvalidParam Busy = No (\case Refl impossible) - decEq Busy Ok = No (\case Refl impossible) - decEq Busy Error = No (\case Refl impossible) - decEq Busy InvalidParam = No (\case Refl impossible) - -||| Opaque handle for library resources -||| Invariant: Handle pointer must be non-null -public export -record Handle where - constructor MkHandle - ptr : Bits64 - 0 prf : So (ptr /= 0) - -||| Returns Nothing if pointer is null -public export -createHandle : Bits64 -> Maybe Handle -createHandle 0 = Nothing -createHandle ptr = case decSo (ptr /= 0) of - Yes p => Just (MkHandle ptr p) - No _ => Nothing +||| ZIG_DNSSEC_SECURITY_*, without NONE: NONE is the absence of a verdict and +||| has no constructor here. +public export +data Security = Secure | Insecure | Bogus | Indeterminate + +public export +securityCode : Security -> Bits8 +securityCode Secure = 1 +securityCode Insecure = 2 +securityCode Bogus = 3 +securityCode Indeterminate = 4 + +public export +securityFromCode : Bits8 -> Maybe Security +securityFromCode 1 = Just Secure +securityFromCode 2 = Just Insecure +securityFromCode 3 = Just Bogus +securityFromCode 4 = Just Indeterminate +securityFromCode _ = Nothing + +export +securityRoundTrip : (s : Security) -> securityFromCode (securityCode s) = Just s +securityRoundTrip Secure = Refl +securityRoundTrip Insecure = Refl +securityRoundTrip Bogus = Refl +securityRoundTrip Indeterminate = Refl + +||| A zeroed verdict (ZIG_DNSSEC_SECURITY_NONE) decodes to no verdict at all, +||| never to Secure. +export +zeroIsNoVerdict : securityFromCode 0 = Nothing +zeroIsNoVerdict = Refl + +public export +Show Security where + show Secure = "secure" + show Insecure = "insecure" + show Bogus = "bogus" + show Indeterminate = "indeterminate" -------------------------------------------------------------------------------- --- C-Types Mapping +-- What a verdict permits -------------------------------------------------------------------------------- -||| Tagged types for C-FFI boundary +||| Evidence that a verdict permits using its answer. public export -data CType = CInt | CUInt | CLong | CULong | CPtrType +data Usable : Security -> Type where + UsableSecure : Usable Secure + UsableInsecure : Usable Insecure + +export +Uninhabited (Usable Bogus) where + uninhabited x impossible + +export +Uninhabited (Usable Indeterminate) where + uninhabited x impossible -||| Pointer type for platform public export -CPtr : Platform -> CType -> Type -CPtr p _ = Bits64 -- Simplified for 64-bit template +usable : (s : Security) -> Dec (Usable s) +usable Secure = Yes UsableSecure +usable Insecure = Yes UsableInsecure +usable Bogus = No absurd +usable Indeterminate = No absurd -||| Size of C types (platform-specific) +||| The answer a verdict can carry: text for Secure and Insecure, nothing +||| (the unit type) for Bogus and Indeterminate. public export -cSizeOf : (p : Platform) -> (t : CType) -> Nat -cSizeOf p CInt = 4 -cSizeOf p CUInt = 4 -cSizeOf p CLong = 8 -cSizeOf p CULong = 8 -cSizeOf p CPtrType = 8 +AnswerFor : Security -> Type +AnswerFor Secure = String +AnswerFor Insecure = String +AnswerFor Bogus = () +AnswerFor Indeterminate = () + +||| Only a usable verdict carries an answer. +export +answerOnlyIfUsable : (s : Security) -> Not (Usable s) -> AnswerFor s = () +answerOnlyIfUsable Secure no = absurd (no UsableSecure) +answerOnlyIfUsable Insecure no = absurd (no UsableInsecure) +answerOnlyIfUsable Bogus _ = Refl +answerOnlyIfUsable Indeterminate _ = Refl + +-------------------------------------------------------------------------------- +-- Reasons +-------------------------------------------------------------------------------- + +||| ZIG_DNSSEC_REASON_* (NONE is the absence of a reason). Names follow the +||| validator's `Reason` enum: InsecureDelegation is insecure_delegation. +public export +data Reason + -- insecure + = InsecureDelegation + | Nsec3OptOut + | UnsupportedAlgorithmPolicy + | Nsec3IterationsPolicy + -- bogus + | SignatureInvalid + | SignatureExpired + | SignatureNotYetValid + | SignatureBadPeriod + | NoMatchingKey + | NoSupportedSignature + | MissingSignature + | DnskeyMissing + | DnskeyNotAuthenticated + | DsNotAuthenticated + | BadSigner + | DenialFailed + | DenialMissing + | Nsec3InconsistentParams + | UnsupportedAlgorithm + | Nsec3IterationsExceeded + | ResourceLimit + | CnameLoop + | DnameMismatch + | MalformedResponse + | ChainLoop + -- indeterminate + | NoTrustAnchor + | FetchFailed + | UpstreamRcode + | Truncated + +public export +reasonCode : Reason -> Bits8 +reasonCode InsecureDelegation = 1 +reasonCode Nsec3OptOut = 2 +reasonCode UnsupportedAlgorithmPolicy = 3 +reasonCode Nsec3IterationsPolicy = 4 +reasonCode SignatureInvalid = 5 +reasonCode SignatureExpired = 6 +reasonCode SignatureNotYetValid = 7 +reasonCode SignatureBadPeriod = 8 +reasonCode NoMatchingKey = 9 +reasonCode NoSupportedSignature = 10 +reasonCode MissingSignature = 11 +reasonCode DnskeyMissing = 12 +reasonCode DnskeyNotAuthenticated = 13 +reasonCode DsNotAuthenticated = 14 +reasonCode BadSigner = 15 +reasonCode DenialFailed = 16 +reasonCode DenialMissing = 17 +reasonCode Nsec3InconsistentParams = 18 +reasonCode UnsupportedAlgorithm = 19 +reasonCode Nsec3IterationsExceeded = 20 +reasonCode ResourceLimit = 21 +reasonCode CnameLoop = 22 +reasonCode DnameMismatch = 23 +reasonCode MalformedResponse = 24 +reasonCode ChainLoop = 25 +reasonCode NoTrustAnchor = 26 +reasonCode FetchFailed = 27 +reasonCode UpstreamRcode = 28 +reasonCode Truncated = 29 + +public export +reasonFromCode : Bits8 -> Maybe Reason +reasonFromCode 1 = Just InsecureDelegation +reasonFromCode 2 = Just Nsec3OptOut +reasonFromCode 3 = Just UnsupportedAlgorithmPolicy +reasonFromCode 4 = Just Nsec3IterationsPolicy +reasonFromCode 5 = Just SignatureInvalid +reasonFromCode 6 = Just SignatureExpired +reasonFromCode 7 = Just SignatureNotYetValid +reasonFromCode 8 = Just SignatureBadPeriod +reasonFromCode 9 = Just NoMatchingKey +reasonFromCode 10 = Just NoSupportedSignature +reasonFromCode 11 = Just MissingSignature +reasonFromCode 12 = Just DnskeyMissing +reasonFromCode 13 = Just DnskeyNotAuthenticated +reasonFromCode 14 = Just DsNotAuthenticated +reasonFromCode 15 = Just BadSigner +reasonFromCode 16 = Just DenialFailed +reasonFromCode 17 = Just DenialMissing +reasonFromCode 18 = Just Nsec3InconsistentParams +reasonFromCode 19 = Just UnsupportedAlgorithm +reasonFromCode 20 = Just Nsec3IterationsExceeded +reasonFromCode 21 = Just ResourceLimit +reasonFromCode 22 = Just CnameLoop +reasonFromCode 23 = Just DnameMismatch +reasonFromCode 24 = Just MalformedResponse +reasonFromCode 25 = Just ChainLoop +reasonFromCode 26 = Just NoTrustAnchor +reasonFromCode 27 = Just FetchFailed +reasonFromCode 28 = Just UpstreamRcode +reasonFromCode 29 = Just Truncated +reasonFromCode _ = Nothing + +export +reasonRoundTrip : (r : Reason) -> reasonFromCode (reasonCode r) = Just r +reasonRoundTrip InsecureDelegation = Refl +reasonRoundTrip Nsec3OptOut = Refl +reasonRoundTrip UnsupportedAlgorithmPolicy = Refl +reasonRoundTrip Nsec3IterationsPolicy = Refl +reasonRoundTrip SignatureInvalid = Refl +reasonRoundTrip SignatureExpired = Refl +reasonRoundTrip SignatureNotYetValid = Refl +reasonRoundTrip SignatureBadPeriod = Refl +reasonRoundTrip NoMatchingKey = Refl +reasonRoundTrip NoSupportedSignature = Refl +reasonRoundTrip MissingSignature = Refl +reasonRoundTrip DnskeyMissing = Refl +reasonRoundTrip DnskeyNotAuthenticated = Refl +reasonRoundTrip DsNotAuthenticated = Refl +reasonRoundTrip BadSigner = Refl +reasonRoundTrip DenialFailed = Refl +reasonRoundTrip DenialMissing = Refl +reasonRoundTrip Nsec3InconsistentParams = Refl +reasonRoundTrip UnsupportedAlgorithm = Refl +reasonRoundTrip Nsec3IterationsExceeded = Refl +reasonRoundTrip ResourceLimit = Refl +reasonRoundTrip CnameLoop = Refl +reasonRoundTrip DnameMismatch = Refl +reasonRoundTrip MalformedResponse = Refl +reasonRoundTrip ChainLoop = Refl +reasonRoundTrip NoTrustAnchor = Refl +reasonRoundTrip FetchFailed = Refl +reasonRoundTrip UpstreamRcode = Refl +reasonRoundTrip Truncated = Refl + +-------------------------------------------------------------------------------- +-- Policy flags +-------------------------------------------------------------------------------- + +||| ZIG_DNSSEC_POLICY_*; the empty list is the library's fail-closed default. +public export +data PolicyFlag = UnsupportedInsecure | IterationsInsecure | NoSha1 + +public export +policyBit : PolicyFlag -> Bits32 +policyBit UnsupportedInsecure = 1 +policyBit IterationsInsecure = 2 +policyBit NoSha1 = 4 + +||| No flag shares a bit with another (checked by evaluation: each pair's AND is 0). +export +policyBitsDisjoint : ( prim__and_Bits32 1 2 = 0 + , prim__and_Bits32 1 4 = 0 + , prim__and_Bits32 2 4 = 0 ) +policyBitsDisjoint = (Refl, Refl, Refl) -||| Alignment of C types (platform-specific) +||| The policy word for a list of flags (duplicates are harmless). public export -cAlignOf : (p : Platform) -> (t : CType) -> Nat -cAlignOf p CInt = 4 -cAlignOf p CUInt = 4 -cAlignOf p CLong = 8 -cAlignOf p CULong = 8 -cAlignOf p CPtrType = 8 +policyWord : List PolicyFlag -> Bits32 +policyWord = foldr (\f, acc => prim__or_Bits32 (policyBit f) acc) 0 diff --git a/src/interface/E2e/Main.idr b/src/interface/E2e/Main.idr new file mode 100644 index 00000000..81c8f358 --- /dev/null +++ b/src/interface/E2e/Main.idr @@ -0,0 +1,117 @@ +-- SPDX-License-Identifier: MPL-2.0 +-- SPDX-FileCopyrightText: 2026 Jonathan D.A. Jewell +||| End-to-end test of the seam: Idris2 -> C ABI -> Zig validator, over the +||| recorded cross-check responses (tests/testdata/). Exits non-zero on any +||| failure. +||| +||| Usage: abi-e2e + +module E2e.Main + +import Abi.Types +import Abi.Foreign +import Data.List +import Data.Maybe +import Data.String +import System +import System.File + +%default total + +||| 2026-10-14T00:00:00Z: inside the fixtures' signing window. +now : Int64 +now = 1791936000 + +||| The trace lines of one recorded scenario. +scenario : String -> String -> String -> String +scenario traces qname qtype = + let header = "@query " ++ qname ++ " " ++ qtype ++ " " + rest = drop 1 (dropWhile (not . isPrefixOf header) (lines traces)) + in unlines (takeWhile (not . isPrefixOf "@query ") rest) + +data Check = Pass String | Fail String + +check : String -> Bool -> Check +check name True = Pass name +check name False = Fail name + +isReason : Reason -> Maybe Reason -> Bool +isReason r (Just r') = reasonCode r == reasonCode r' +isReason _ Nothing = False + +||| A usable outcome's answer, if any. Bogus and Indeterminate have none to give. +answerText : Outcome -> Maybe String +answerText o = case usable o.security of + Yes ok => Just (answerOf o ok) + No _ => Nothing + +expectSecure : String -> Either CallError Outcome -> Check +expectSecure name (Right o@(MkOutcome Secure Nothing "" _ _ _ _ _ _)) = + check name (maybe False (isPrefixOf "www.rsasha256.test.") (answerText o)) +expectSecure name _ = Fail name + +expectInsecure : String -> Reason -> String -> Either CallError Outcome -> Check +expectInsecure name r zone (Right o@(MkOutcome Insecure why loc _ _ _ _ _ _)) = + check name (isReason r why && loc == zone && isJust (answerText o)) +expectInsecure name _ _ _ = Fail name + +expectBogus : String -> Reason -> Either CallError Outcome -> Check +expectBogus name r (Right (MkOutcome Bogus why _ _ _ _ _ _ ())) = check name (isReason r why) +expectBogus name _ _ = Fail name + +expectBogusAny : String -> Either CallError Outcome -> Check +expectBogusAny name (Right (MkOutcome Bogus _ _ _ _ _ _ _ ())) = Pass name +expectBogusAny name _ = Fail name + +expectRefused : String -> Status -> Either CallError Outcome -> Check +expectRefused name s (Left (Refused s')) = check name (statusCode s == statusCode s') +expectRefused name _ _ = Fail name + +isFail : Check -> Bool +isFail (Fail _) = True +isFail (Pass _) = False + +||| Validates one recorded scenario against the fixture anchor. +runQ : (traces, anchor, qname, qtype : String) -> Bits16 -> List PolicyFlag -> IO (Either CallError Outcome) +runQ traces anchor q t ty pol = validateTrace (scenario traces q t) (Just anchor) q ty now pol + +report : List Check -> IO Bool +report cs = do + traverse_ (\c => case c of + Pass n => putStrLn ("PASS " ++ n) + Fail n => putStrLn ("FAIL " ++ n)) cs + let failed = length (filter isFail cs) + putStrLn (show (length cs) ++ " checks, " ++ show failed ++ " failed") + pure (failed == 0) + +covering +main : IO () +main = do + [_, tracesPath, anchorPath] <- getArgs + | _ => do putStrLn "usage: abi-e2e "; exitWith (ExitFailure 2) + Right traces <- readFile tracesPath + | Left e => do putStrLn ("cannot read " ++ tracesPath ++ ": " ++ show e); exitWith (ExitFailure 2) + Right anchor <- readFile anchorPath + | Left e => do putStrLn ("cannot read " ++ anchorPath ++ ": " ++ show e); exitWith (ExitFailure 2) + let run = runQ traces anchor + linked <- linkedAbiVersion + secure <- run "www.rsasha256.test." "A" 1 [] + insecure <- run "www.insecure.test." "A" 1 [] + expired <- run "www.expired.test." "A" 1 [] + ed448 <- run "www.ed448.test." "A" 1 [] + ed448Policy <- run "www.ed448.test." "A" 1 [UnsupportedInsecure] + badName <- run "a..b" "A" 1 [] + meta <- run "www.rsasha256.test." "A" 255 [] + ianaRoot <- validateTrace (scenario traces "www.rsasha256.test." "A") Nothing "www.rsasha256.test." 1 now [] + ok <- report + [ check "linked library speaks ABI version 1" (linked == abiVersion) + , expectSecure "secure answer with its records" secure + , expectInsecure "insecure delegation, zone and answer" InsecureDelegation "insecure.test." insecure + , expectBogus "expired signatures are bogus, with no answer" SignatureExpired expired + , expectBogus "Ed448 is bogus by default" UnsupportedAlgorithm ed448 + , expectInsecure "Ed448 is insecure under the RFC policy" UnsupportedAlgorithmPolicy "ed448.test." ed448Policy + , expectRefused "a malformed name is refused" BadName badName + , expectRefused "a meta-type is refused" InvalidArgument meta + , expectBogusAny "the IANA root does not sign the fixtures" ianaRoot + ] + if ok then exitSuccess else exitWith (ExitFailure 1) diff --git a/src/interface/E2e/README.adoc b/src/interface/E2e/README.adoc new file mode 100644 index 00000000..324615a9 --- /dev/null +++ b/src/interface/E2e/README.adoc @@ -0,0 +1,6 @@ +// SPDX-License-Identifier: CC-BY-SA-4.0 +// SPDX-FileCopyrightText: 2026 Jonathan D.A. Jewell += Idris2 end-to-end test + +`Main.idr` loads `libzig_dnssec.so` and validates recorded responses through +`Abi.Foreign`. Run with `just abi-e2e` (needs zig and idris2). diff --git a/src/interface/E2e/abi-e2e.ipkg b/src/interface/E2e/abi-e2e.ipkg new file mode 100644 index 00000000..9fb881b9 --- /dev/null +++ b/src/interface/E2e/abi-e2e.ipkg @@ -0,0 +1,29 @@ +-- SPDX-License-Identifier: MPL-2.0 +-- SPDX-FileCopyrightText: 2026 Jonathan D.A. Jewell +-- +-- End-to-end test of the seam: an Idris2 program that loads libzig_dnssec +-- (built by `zig build ffi`) and validates recorded responses through +-- Abi.Foreign. Run with `just abi-e2e`. It lives one level below abi.ipkg so +-- that `just test` (which typechecks the first .ipkg it finds) keeps +-- choosing abi.ipkg. + +package abi-e2e + +version = 0.1.0 + +authors = "Jonathan D.A. Jewell" + +brief = "End-to-end test of the zig-dnssec Idris2/Zig seam" + +sourcedir = ".." + +depends = base + +modules = Abi.Types + , Abi.Layout + , Abi.Foreign + , E2e.Main + +main = E2e.Main + +executable = abi-e2e diff --git a/src/interface/README.adoc b/src/interface/README.adoc index 4fde7080..f061d269 100644 --- a/src/interface/README.adoc +++ b/src/interface/README.adoc @@ -1,3 +1,85 @@ // SPDX-License-Identifier: CC-BY-SA-4.0 -// Copyright (c) Jonathan D.A. Jewell -= interface Unit +// SPDX-FileCopyrightText: 2026 Jonathan D.A. Jewell += The C ABI seam +:toc: + +The library is used from Zig as a module (`src/root.zig`). Every other language reaches +it through this seam: a C ABI implemented in Zig, and an Idris2 model of that ABI that +states its rules as types. It is experimental and unreviewed, like the rest of the +repository. + +== The three parts + +[cols="1,2,3",options="header"] +|=== +| Part | File | Role + +| Contract +| `ffi/include/zig_dnssec.h` +| The C interface, version 1: codes, the `zig_dnssec_verdict` struct, the transport + callback, six functions, and the fail-closed rules in its opening comment. + +| Implementation +| `ffi/src/main.zig` +| Pure Zig, no libc. Built by `zig build ffi` as `libzig_dnssec.a` and + `libzig_dnssec.so` (the shared object exports the six functions and nothing else). + +| Model +| `Abi/Types.idr`, `Abi/Layout.idr`, `Abi/Foreign.idr` +| Idris2: the codes with round-trip proofs, the struct layout with alignment and + no-overlap proofs, and bindings whose result type cannot carry an answer for a bogus + or indeterminate verdict. +|=== + +== The rule the seam keeps + +Answer data leaves the library only with a SECURE verdict (authenticated to a trust +anchor) or an INSECURE one (proven unsigned, or allowed by an explicit policy flag). + +* In C, `verdict.security` is `ZIG_DNSSEC_SECURITY_NONE` (0) unless the call returned + `ZIG_DNSSEC_OK`, so a zeroed or stale verdict never reads as secure, and the answer + buffer stays the empty string for BOGUS and INDETERMINATE. +* In Idris2, `Outcome.answer` has type `AnswerFor security`, which is `String` for + `Secure` and `Insecure` and `()` otherwise; `answerOf` needs a `Usable` proof that + does not exist for `Bogus` or `Indeterminate`. `Abi.Foreign` decodes the security + code before it reads any text, so the rule holds for Idris callers even if the + library broke it. + +== How the parts are kept in step + +* The Zig implementation imports the header through translate-c. Each exported + function is checked at compile time to have exactly the header's type, and each + reason code is looked up by the header macro of the same name, so a validator reason + without a macro does not compile. +* `ffi/test/seam_test.zig` reads the Idris sources and compares every status, security, + reason and policy code, every field offset, size and alignment, the struct size, and + the parameter kinds of every `%foreign` declaration with the header as the C compiler + sees it; it also rejects `believe_me`, `assert_total` and the like in the model. + Eleven deliberate mismatches (one per kind) were each caught when this was written. +* `idris2 --typecheck abi.ipkg` checks the model's proofs (`just test` runs it). +* `ffi/test/abi_test.zig` exercises the C functions through the header's declarations: + verdicts on recorded responses, every bad-argument path, buffer sizing, the callback + transport, names, leaks and allocation failure at every point. +* `E2e/` is an Idris2 program that loads `libzig_dnssec.so` and validates recorded + responses through `Abi.Foreign` (`just abi-e2e`). + +== Using it + +From C: build with `zig build ffi -Doptimize=ReleaseSafe`, include +`zig-out/include/zig_dnssec.h`, link `zig-out/lib/libzig_dnssec.a` (or the shared +object). Supply the transport as a callback that sends one DNS message to a resolver +you trust to pass messages through (DNS-over-HTTPS is the intended carrier) and +returns the response; the library sets CD and DO and validates everything itself. + +From Idris2: `Abi.Foreign.validateTrace` validates against recorded responses. A live +transport for Idris2 callers is not provided yet (it needs a C callback from Idris2 or +a DoH entry point in the ABI; see `docs/status/ROADMAP.adoc`). + +== Limits + +* The Idris2 model reads the struct little-endian and assumes natural alignment; the + seam is tested on x86_64 Linux only. +* What the proofs cover is the model and the decoding in `Abi.Foreign`. That the + validator itself never reports a failure as SECURE or INSECURE is tested, not proved + (`docs/reports/VERIFICATION.adoc`). +* The FFI marshalling of the Idris2 Chez backend is trusted. diff --git a/src/interface/ffi/README.adoc b/src/interface/ffi/README.adoc index ca143207..beee8aee 100644 --- a/src/interface/ffi/README.adoc +++ b/src/interface/ffi/README.adoc @@ -1,3 +1,8 @@ // SPDX-License-Identifier: CC-BY-SA-4.0 -// Copyright (c) Jonathan D.A. Jewell -= ffi Logic +// SPDX-FileCopyrightText: 2026 Jonathan D.A. Jewell += Zig side of the C ABI + +`include/zig_dnssec.h` is the contract, `src/main.zig` implements it in pure Zig, and +`test/` checks both the behaviour and the agreement with the Idris2 model. Built from +the repository root: `zig build ffi` (libraries and header into `zig-out/`) and +`zig build test`. See `../README.adoc`. diff --git a/src/interface/ffi/build.zig b/src/interface/ffi/build.zig deleted file mode 100644 index 0596e52c..00000000 --- a/src/interface/ffi/build.zig +++ /dev/null @@ -1,29 +0,0 @@ -// SPDX-License-Identifier: MPL-2.0 -// Copyright (c) Jonathan D.A. Jewell -// -// Template FFI build (Zig 0.15.2+). -// -// zig build test runs the unit tests in src/main.zig and test/integration_test.zig -// -// src/main.zig carries template tokens until `just repo-init` fills them, so the -// test step compiles only in an instantiated repository. - -const std = @import("std"); - -pub fn build(b: *std.Build) void { - const target = b.standardTargetOptions(.{}); - const optimize = b.standardOptimizeOption(.{}); - - const test_step = b.step("test", "Run the FFI unit and integration tests"); - for ([_][]const u8{ "src/main.zig", "test/integration_test.zig" }) |path| { - const t = b.addTest(.{ - .root_module = b.createModule(.{ - .root_source_file = b.path(path), - .target = target, - .optimize = optimize, - .link_libc = true, // main.zig allocates with std.heap.c_allocator - }), - }); - test_step.dependOn(&b.addRunArtifact(t).step); - } -} diff --git a/src/interface/ffi/include/zig_dnssec.h b/src/interface/ffi/include/zig_dnssec.h new file mode 100644 index 00000000..55f61aa3 --- /dev/null +++ b/src/interface/ffi/include/zig_dnssec.h @@ -0,0 +1,192 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +/* SPDX-FileCopyrightText: 2026 Jonathan D.A. Jewell */ + +/* + * zig-dnssec C ABI, version 1. + * + * EXPERIMENTAL and not independently reviewed. Do not rely on it for security + * decisions yet; see docs/reports/VERIFICATION.adoc. + * + * This header is the contract of the seam. The Zig implementation + * (src/interface/ffi/src/main.zig) is checked against it at compile time, and + * the Idris2 model (src/interface/Abi/) is checked against it by + * `zig build test`. + * + * Fail-closed rules every function keeps: + * - verdict.security is ZIG_DNSSEC_SECURITY_NONE (0) whenever a call returns + * anything other than ZIG_DNSSEC_OK, so a zeroed or stale verdict never + * reads as secure; + * - answer text is written only when the security is SECURE or INSECURE; + * for BOGUS and INDETERMINATE text stays the empty string and text_len + * is 0; + * - unknown policy bits are rejected, not ignored. + * + * No global state: calls are independent and may run on different threads. + * Nothing returned needs freeing; the *_name functions return static strings. + */ + +#ifndef ZIG_DNSSEC_H +#define ZIG_DNSSEC_H + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#define ZIG_DNSSEC_ABI_VERSION 1 + +/* ---- Call status (return value of the validate functions) --------------- */ + +#define ZIG_DNSSEC_OK 0 +/* A required pointer was NULL, the policy had unknown bits, or the query + * type was a meta-type (OPT, ANY, AXFR, ...). */ +#define ZIG_DNSSEC_ERR_INVALID_ARGUMENT 1 +#define ZIG_DNSSEC_ERR_OUT_OF_MEMORY 2 +/* The trust-anchor text did not parse, or held no DS/DNSKEY records. */ +#define ZIG_DNSSEC_ERR_BAD_ANCHORS 3 +/* The query name is not a valid domain name in presentation format. */ +#define ZIG_DNSSEC_ERR_BAD_NAME 4 +/* The recorded trace did not parse (zig_dnssec_validate_trace only). */ +#define ZIG_DNSSEC_ERR_BAD_TRACE 5 +/* The initial query got no usable response (transport error, or a response + * that does not match the question). Failures of the follow-up DS/DNSKEY + * fetches are reported in the verdict instead. */ +#define ZIG_DNSSEC_ERR_QUERY_FAILED 6 +/* text was non-NULL and too small; verdict.text_len holds the length needed + * (excluding the terminating NUL). */ +#define ZIG_DNSSEC_ERR_BUFFER_TOO_SMALL 7 + +/* ---- Security of the answer (verdict.security) --------------------------- */ + +#define ZIG_DNSSEC_SECURITY_NONE 0 /* no verdict: the call failed */ +#define ZIG_DNSSEC_SECURITY_SECURE 1 /* authenticated to a trust anchor */ +#define ZIG_DNSSEC_SECURITY_INSECURE 2 /* proven unsigned, or allowed by policy */ +#define ZIG_DNSSEC_SECURITY_BOGUS 3 /* validation failed: do not use */ +#define ZIG_DNSSEC_SECURITY_INDETERMINATE 4 /* could not decide: do not use */ + +/* ---- Reason (verdict.reason); 0 for SECURE -------------------------------- */ + +#define ZIG_DNSSEC_REASON_NONE 0 +/* insecure */ +#define ZIG_DNSSEC_REASON_INSECURE_DELEGATION 1 +#define ZIG_DNSSEC_REASON_NSEC3_OPT_OUT 2 +#define ZIG_DNSSEC_REASON_UNSUPPORTED_ALGORITHM_POLICY 3 +#define ZIG_DNSSEC_REASON_NSEC3_ITERATIONS_POLICY 4 +/* bogus */ +#define ZIG_DNSSEC_REASON_SIGNATURE_INVALID 5 +#define ZIG_DNSSEC_REASON_SIGNATURE_EXPIRED 6 +#define ZIG_DNSSEC_REASON_SIGNATURE_NOT_YET_VALID 7 +#define ZIG_DNSSEC_REASON_SIGNATURE_BAD_PERIOD 8 +#define ZIG_DNSSEC_REASON_NO_MATCHING_KEY 9 +#define ZIG_DNSSEC_REASON_NO_SUPPORTED_SIGNATURE 10 +#define ZIG_DNSSEC_REASON_MISSING_SIGNATURE 11 +#define ZIG_DNSSEC_REASON_DNSKEY_MISSING 12 +#define ZIG_DNSSEC_REASON_DNSKEY_NOT_AUTHENTICATED 13 +#define ZIG_DNSSEC_REASON_DS_NOT_AUTHENTICATED 14 +#define ZIG_DNSSEC_REASON_BAD_SIGNER 15 +#define ZIG_DNSSEC_REASON_DENIAL_FAILED 16 +#define ZIG_DNSSEC_REASON_DENIAL_MISSING 17 +#define ZIG_DNSSEC_REASON_NSEC3_INCONSISTENT_PARAMS 18 +#define ZIG_DNSSEC_REASON_UNSUPPORTED_ALGORITHM 19 +#define ZIG_DNSSEC_REASON_NSEC3_ITERATIONS_EXCEEDED 20 +#define ZIG_DNSSEC_REASON_RESOURCE_LIMIT 21 +#define ZIG_DNSSEC_REASON_CNAME_LOOP 22 +#define ZIG_DNSSEC_REASON_DNAME_MISMATCH 23 +#define ZIG_DNSSEC_REASON_MALFORMED_RESPONSE 24 +#define ZIG_DNSSEC_REASON_CHAIN_LOOP 25 +/* indeterminate */ +#define ZIG_DNSSEC_REASON_NO_TRUST_ANCHOR 26 +#define ZIG_DNSSEC_REASON_FETCH_FAILED 27 +#define ZIG_DNSSEC_REASON_UPSTREAM_RCODE 28 +#define ZIG_DNSSEC_REASON_TRUNCATED 29 + +/* ---- Policy flags (0 = the library's fail-closed defaults) --------------- */ + +/* Treat zones whose DS set holds only unsupported algorithms as insecure + * (RFC 4035 section 5.2) instead of bogus. */ +#define ZIG_DNSSEC_POLICY_UNSUPPORTED_INSECURE 1 +/* Treat NSEC3 with iterations above 150 as insecure (RFC 9276) instead of + * bogus. */ +#define ZIG_DNSSEC_POLICY_ITERATIONS_INSECURE 2 +/* Refuse SHA-1 in signatures and DS digests. */ +#define ZIG_DNSSEC_POLICY_NO_SHA1 4 + +/* ---- Verdict --------------------------------------------------------------- */ + +#define ZIG_DNSSEC_WHERE_MAX 1024 + +/* 1048 bytes, 4-byte alignment; the layout is part of the ABI and is proved + * aligned in src/interface/Abi/Layout.idr. */ +typedef struct zig_dnssec_verdict { + uint8_t security; /* ZIG_DNSSEC_SECURITY_* */ + uint8_t reason; /* ZIG_DNSSEC_REASON_* */ + uint16_t reserved; /* always 0 */ + uint16_t rcode; /* response code of the answer (SECURE, INSECURE) */ + uint16_t rtype; /* RR type where validation failed (BOGUS, INDETERMINATE) */ + uint32_t ttl; /* TTL to cache the answer for (SECURE, INSECURE) */ + uint32_t fetches; /* follow-up queries made */ + uint32_t verifications; /* signature verifications made */ + uint32_t text_len; /* bytes of answer text, excluding the NUL */ + /* NUL-terminated presentation-format name: the zone where insecurity was + * established (INSECURE) or where validation failed (BOGUS, + * INDETERMINATE); empty otherwise. */ + char where[ZIG_DNSSEC_WHERE_MAX]; +} zig_dnssec_verdict; + +/* ---- Transport -------------------------------------------------------------- + * + * Sends one DNS query message and stores the response message. The library + * sets the CD and DO bits and validates everything itself; the upstream only + * has to pass messages through (DNS-over-HTTPS is the intended carrier). + * Return 0 on success and any other value on failure. response_cap is 65535. + */ +typedef int (*zig_dnssec_exchange_fn)(void *ctx, const uint8_t *query, size_t query_len, + uint8_t *response, size_t response_cap, + size_t *response_len); + +/* ---- Functions ------------------------------------------------------------ */ + +/* ZIG_DNSSEC_ABI_VERSION of the library actually linked. */ +uint32_t zig_dnssec_abi_version(void); + +/* + * Queries qname/qtype through `exchange` and validates the answer. + * + * anchors trust anchors as DS or DNSKEY records in presentation format, + * NUL-terminated; NULL selects the built-in IANA root anchors. + * qname NUL-terminated domain name; qtype a data RR type (not a meta-type). + * now the time to check signature validity against, in seconds since + * the Unix epoch. The library never reads the clock itself. + * policy ZIG_DNSSEC_POLICY_* bits, 0 for the defaults. + * out receives the verdict (required). + * text set to the empty string first; then receives the answer RRsets in + * presentation format, one record per line, NUL-terminated, for + * SECURE and INSECURE only. May be NULL when only the verdict is + * wanted (text_len still reports the size). + */ +int zig_dnssec_validate(zig_dnssec_exchange_fn exchange, void *ctx, const char *anchors, + const char *qname, uint16_t qtype, int64_t now, uint32_t policy, + zig_dnssec_verdict *out, char *text, size_t text_cap); + +/* + * As zig_dnssec_validate, answering every query from a recorded trace + * (lines of " ", as written by + * `dnssec-stub --record`). Offline and deterministic; meant for tests and for + * re-checking a recorded resolution. + */ +int zig_dnssec_validate_trace(const char *trace, const char *anchors, const char *qname, + uint16_t qtype, int64_t now, uint32_t policy, + zig_dnssec_verdict *out, char *text, size_t text_cap); + +/* Static, NUL-terminated names; "unknown" for codes outside the tables. */ +const char *zig_dnssec_status_name(int status); +const char *zig_dnssec_security_name(uint8_t security); +const char *zig_dnssec_reason_name(uint8_t reason); + +#ifdef __cplusplus +} +#endif + +#endif /* ZIG_DNSSEC_H */ diff --git a/src/interface/ffi/src/README.adoc b/src/interface/ffi/src/README.adoc index d5631f60..5cc55f7c 100644 --- a/src/interface/ffi/src/README.adoc +++ b/src/interface/ffi/src/README.adoc @@ -1,3 +1,6 @@ // SPDX-License-Identifier: CC-BY-SA-4.0 -// Copyright (c) Jonathan D.A. Jewell -= Src Logic +// SPDX-FileCopyrightText: 2026 Jonathan D.A. Jewell += C ABI implementation + +`main.zig` exports the functions declared in `../include/zig_dnssec.h`, each checked at +compile time against the header's type. diff --git a/src/interface/ffi/src/main.zig b/src/interface/ffi/src/main.zig index e76c13c3..7b13e20a 100644 --- a/src/interface/ffi/src/main.zig +++ b/src/interface/ffi/src/main.zig @@ -1,275 +1,350 @@ // SPDX-License-Identifier: MPL-2.0 -// Copyright (c) Jonathan D.A. Jewell -// ZIG_DNSSEC FFI Implementation -// -// This module implements the C-compatible FFI declared in src/abi/Foreign.idr -// All types and layouts must match the Idris2 ABI definitions. -// +// SPDX-FileCopyrightText: 2026 Jonathan D.A. Jewell + +//! zig-dnssec C ABI, version 1: the Zig side of the seam. +//! +//! The contract is `src/interface/ffi/include/zig_dnssec.h`. This file does +//! not restate it: the verdict struct *is* the header's struct (through +//! translate-c), every exported function is checked at compile time to have +//! exactly the type the header declares, and every code is taken from the +//! header's macros by name, so a reason added to the validator without a +//! header macro does not compile. +//! +//! Experimental and unreviewed, like the library. const std = @import("std"); +const lib = @import("dnssec"); +pub const h = @import("zig_dnssec_h"); + +const Allocator = std.mem.Allocator; +const validator = lib.sec.validator; +const TrustAnchors = lib.sec.anchors.TrustAnchors; +const transport = lib.stub.transport; +const StubClient = lib.stub.client.StubClient; +const Name = lib.wire.Name; +const Type = lib.wire.Type; + +pub const Verdict = h.zig_dnssec_verdict; + +/// Call status, valued from the header. +pub const Status = enum(c_int) { + ok = h.ZIG_DNSSEC_OK, + invalid_argument = h.ZIG_DNSSEC_ERR_INVALID_ARGUMENT, + out_of_memory = h.ZIG_DNSSEC_ERR_OUT_OF_MEMORY, + bad_anchors = h.ZIG_DNSSEC_ERR_BAD_ANCHORS, + bad_name = h.ZIG_DNSSEC_ERR_BAD_NAME, + bad_trace = h.ZIG_DNSSEC_ERR_BAD_TRACE, + query_failed = h.ZIG_DNSSEC_ERR_QUERY_FAILED, + buffer_too_small = h.ZIG_DNSSEC_ERR_BUFFER_TOO_SMALL, +}; -// Version information (keep in sync with project) -const VERSION = "0.1.0"; -const BUILD_INFO = "ZIG_DNSSEC built with Zig " ++ @import("builtin").zig_version_string; +/// verdict.security, valued from the header. `none` is 0 so that a zeroed +/// verdict never reads as secure. +pub const Security = enum(u8) { + none = h.ZIG_DNSSEC_SECURITY_NONE, + secure = h.ZIG_DNSSEC_SECURITY_SECURE, + insecure = h.ZIG_DNSSEC_SECURITY_INSECURE, + bogus = h.ZIG_DNSSEC_SECURITY_BOGUS, + indeterminate = h.ZIG_DNSSEC_SECURITY_INDETERMINATE, +}; -/// Thread-local error storage -threadlocal var last_error: ?[]const u8 = null; +pub const policy_mask: u32 = h.ZIG_DNSSEC_POLICY_UNSUPPORTED_INSECURE | + h.ZIG_DNSSEC_POLICY_ITERATIONS_INSECURE | + h.ZIG_DNSSEC_POLICY_NO_SHA1; -/// Set the last error message -fn setError(msg: []const u8) void { - last_error = msg; +fn upperComptime(comptime s: []const u8) [s.len]u8 { + @setEvalBranchQuota(10_000); + var out: [s.len]u8 = undefined; + for (s, 0..) |c, i| out[i] = std.ascii.toUpper(c); + return out; } -/// Clear the last error -fn clearError() void { - last_error = null; +/// The header macro that carries the code of reason `r`. +pub fn reasonMacro(comptime r: validator.Reason) []const u8 { + return "ZIG_DNSSEC_REASON_" ++ upperComptime(@tagName(r)); } -//============================================================================== -// Core Types (must match src/abi/Types.idr) -//============================================================================== - -/// Result codes (must match Idris2 Result type) -pub const Result = enum(c_int) { - ok = 0, - @"error" = 1, - invalid_param = 2, - out_of_memory = 3, - null_pointer = 4, -}; +/// The reason code of `r`, read from the header macro of the same name. +pub fn reasonCode(r: validator.Reason) u8 { + @setEvalBranchQuota(100_000); + switch (r) { + inline else => |tag| return @field(h, reasonMacro(tag)), + } +} -/// Library handle. C sees only a pointer, so the fields stay private to Zig. -pub const Handle = struct { - // Internal state hidden from C - allocator: std.mem.Allocator, - initialized: bool, - // Add your fields here +/// Reason names by code; index 0 is "none". +const reason_names: [std.enums.values(validator.Reason).len + 1][*:0]const u8 = blk: { + @setEvalBranchQuota(100_000); + var t: [std.enums.values(validator.Reason).len + 1][*:0]const u8 = undefined; + for (&t) |*e| e.* = "unknown"; + t[h.ZIG_DNSSEC_REASON_NONE] = "none"; + for (std.enums.values(validator.Reason)) |r| { + const code = @field(h, reasonMacro(r)); + if (code >= t.len) @compileError("reason codes must be dense: " ++ reasonMacro(r)); + if (!std.mem.eql(u8, std.mem.span(t[code]), "unknown")) @compileError("duplicate reason code: " ++ reasonMacro(r)); + t[code] = @tagName(r); + } + break :blk t; }; -//============================================================================== -// Library Lifecycle -//============================================================================== - -/// Initialize the library -/// Returns a handle, or null on failure -export fn zig_dnssec_init() ?*Handle { - const allocator = std.heap.c_allocator; +// --------------------------------------------------------------------------- +// Core, allocator-parametric (the tests run it under the leak checker) +// --------------------------------------------------------------------------- + +pub const Request = struct { + anchors: ?[*:0]const u8, + qname: ?[*:0]const u8, + qtype: u16, + now: i64, + policy: u32, + out: ?*Verdict, + text: ?[*]u8, + text_cap: usize, +}; - const handle = allocator.create(Handle) catch { - setError("Failed to allocate handle"); - return null; +/// 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 { + 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); + if (req.qtype == 0 or qtype.isMetaOrQtype()) return .invalid_argument; + const qname = Name.fromText(std.mem.span(qname_z)) catch return .bad_name; + + var anchors = if (req.anchors) |a| + TrustAnchors.fromText(gpa, std.mem.span(a)) catch |e| return switch (e) { + error.OutOfMemory => .out_of_memory, + else => .bad_anchors, + } + else + TrustAnchors.ianaRoot(gpa) catch |e| return switch (e) { + error.OutOfMemory => .out_of_memory, + else => .bad_anchors, + }; + defer anchors.deinit(); + if (anchors.anchors.len == 0) return .bad_anchors; + + var policy: validator.Policy = .{}; + if (req.policy & h.ZIG_DNSSEC_POLICY_UNSUPPORTED_INSECURE != 0) policy.unsupported_algorithm = .insecure; + if (req.policy & h.ZIG_DNSSEC_POLICY_ITERATIONS_INSECURE != 0) policy.nsec3_iterations = .insecure; + if (req.policy & h.ZIG_DNSSEC_POLICY_NO_SHA1 != 0) policy.allow_sha1 = false; + + var client: StubClient = .{ .transport = t, .anchors = &anchors, .policy = policy }; + var result = client.resolve(gpa, qname, qtype, req.now) catch |e| return switch (e) { + error.OutOfMemory => .out_of_memory, + else => .query_failed, }; - - // Initialize handle - handle.* = .{ - .allocator = allocator, - .initialized = true, + defer result.deinit(); + + // Only the SECURE and INSECURE arms carry an answer; the failure arms + // have no path to answer data. + const answer: ?*const validator.Answer = switch (result.verdict) { + .secure => |*ans| ans, + .insecure => |*ins| &ins.answer, + .bogus, .indeterminate => null, }; + var text: std.Io.Writer.Allocating = .init(gpa); + defer text.deinit(); + if (answer) |ans| writeAnswer(&text.writer, ans) catch return .out_of_memory; + const body = text.written(); + const body_len = std.math.cast(u32, body.len) orelse return .out_of_memory; + + if (req.text) |p| { + if (req.text_cap < body.len + 1) { + out.text_len = body_len; + return .buffer_too_small; + } + @memcpy(p[0..body.len], body); + p[body.len] = 0; + } - clearError(); - return handle; + out.text_len = body_len; + out.fetches = result.stats.fetches; + out.verifications = result.stats.verifications; + switch (result.verdict) { + .secure => |ans| { + out.security = @backingInt(Security.secure); + out.rcode = @backingInt(ans.rcode); + out.ttl = ans.ttl; + }, + .insecure => |ins| { + out.security = @backingInt(Security.insecure); + out.reason = reasonCode(ins.reason); + out.rcode = @backingInt(ins.answer.rcode); + out.ttl = ins.answer.ttl; + setWhere(out, &ins.zone); + }, + .bogus, .indeterminate => |f| { + out.security = @backingInt(if (result.verdict == .bogus) Security.bogus else Security.indeterminate); + out.reason = reasonCode(f.reason); + out.rtype = f.rtype.toInt(); + setWhere(out, &f.name); + }, + } + return .ok; } -/// Free the library handle -export fn zig_dnssec_free(handle: ?*Handle) void { - const h = handle orelse return; - const allocator = h.allocator; - - // Clean up resources - h.initialized = false; - - allocator.destroy(h); - clearError(); +fn setWhere(out: *Verdict, n: *const Name) void { + const buf: []u8 = out.where[0 .. out.where.len - 1]; + const s = n.toText(buf); + out.where[s.len] = 0; } -//============================================================================== -// Core Operations -//============================================================================== - -/// Process data (example operation) -export fn zig_dnssec_process(handle: ?*Handle, input: u32) Result { - const h = handle orelse { - setError("Null handle"); - return .null_pointer; - }; - - if (!h.initialized) { - setError("Handle not initialized"); - return .@"error"; +fn writeAnswer(w: *std.Io.Writer, ans: *const validator.Answer) !void { + for (ans.rrsets) |set| { + for (set.rdatas) |rd| { + const rr: lib.wire.Rr = .{ .name = set.name, .type = set.type, .class = set.class, .ttl = set.ttl, .rdata = rd }; + try lib.wire.text.formatRr(w, &rr); + try w.writeByte('\n'); + } } - - // Example processing logic - _ = input; - - clearError(); - return .ok; } -//============================================================================== -// String Operations -//============================================================================== - -/// Get a string result (example) -/// Caller must free the returned string -export fn zig_dnssec_get_string(handle: ?*Handle) ?[*:0]const u8 { - const h = handle orelse { - setError("Null handle"); - return null; - }; +/// Transport over a caller-supplied C callback. +pub const CallbackTransport = struct { + exchange: h.zig_dnssec_exchange_fn, + ctx: ?*anyopaque, - if (!h.initialized) { - setError("Handle not initialized"); - return null; + pub fn asTransport(self: *CallbackTransport) transport.Transport { + return .{ .ptr = self, .exchangeFn = exchangeImpl }; } - // Example: allocate and return a string - const result = h.allocator.dupeZ(u8, "Example result") catch { - setError("Failed to allocate string"); - return null; - }; - - clearError(); - return result.ptr; -} - -/// Free a string allocated by the library -export fn zig_dnssec_free_string(str: ?[*:0]const u8) void { - const s = str orelse return; - const allocator = std.heap.c_allocator; + fn exchangeImpl(ptr: *anyopaque, gpa: Allocator, query: []u8) anyerror![]u8 { + const self: *CallbackTransport = @ptrCast(@alignCast(ptr)); + const f = self.exchange orelse return error.ExchangeFailed; + const buf = try gpa.alloc(u8, 65535); + errdefer gpa.free(buf); + var len: usize = 0; + if (f(self.ctx, query.ptr, query.len, buf.ptr, buf.len, &len) != 0) return error.ExchangeFailed; + if (len > buf.len) return error.ExchangeFailed; + return gpa.realloc(buf, len); + } +}; - const slice = std.mem.span(s); - allocator.free(slice); +pub fn validateWith( + gpa: Allocator, + exchange: h.zig_dnssec_exchange_fn, + ctx: ?*anyopaque, + req: Request, +) Status { + if (exchange == null) { + if (req.out) |o| o.* = std.mem.zeroes(Verdict); + return .invalid_argument; + } + var cb: CallbackTransport = .{ .exchange = exchange, .ctx = ctx }; + return run(gpa, cb.asTransport(), req); } -//============================================================================== -// Array/Buffer Operations -//============================================================================== - -/// Process an array of data -export fn zig_dnssec_process_array( - handle: ?*Handle, - buffer: ?[*]const u8, - len: u32, -) Result { - const h = handle orelse { - setError("Null handle"); - return .null_pointer; +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; }; - - const buf = buffer orelse { - setError("Null buffer"); - return .null_pointer; + 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, + }; }; - - if (!h.initialized) { - setError("Handle not initialized"); - return .@"error"; - } - - // Access the buffer - const data = buf[0..len]; - _ = data; - - // Process data here - - clearError(); - return .ok; + defer tr.deinit(); + var replay: transport.ReplayTransport = .{ .records = tr.records }; + return run(gpa, replay.transport(), req); } -//============================================================================== -// Error Handling -//============================================================================== +// --------------------------------------------------------------------------- +// Exported C functions +// --------------------------------------------------------------------------- -/// Get the last error message -/// Returns null if no error -export fn zig_dnssec_last_error() ?[*:0]const u8 { - const err = last_error orelse return null; +const c_allocator = std.heap.smp_allocator; - // Return C string (static storage, no need to free) - const allocator = std.heap.c_allocator; - const c_str = allocator.dupeZ(u8, err) catch return null; - return c_str.ptr; +fn abiVersion() callconv(.c) u32 { + return h.ZIG_DNSSEC_ABI_VERSION; } -//============================================================================== -// Version Information -//============================================================================== - -/// Get the library version -export fn zig_dnssec_version() [*:0]const u8 { - return VERSION.ptr; +fn validateC( + exchange: h.zig_dnssec_exchange_fn, + ctx: ?*anyopaque, + anchors: [*c]const u8, + qname: [*c]const u8, + qtype: u16, + now: i64, + policy: u32, + out: [*c]Verdict, + text: [*c]u8, + text_cap: usize, +) callconv(.c) c_int { + return @backingInt(validateWith(c_allocator, exchange, ctx, .{ + .anchors = @ptrCast(anchors), + .qname = @ptrCast(qname), + .qtype = qtype, + .now = now, + .policy = policy, + .out = out, + .text = text, + .text_cap = text_cap, + })); } -/// Get build information -export fn zig_dnssec_build_info() [*:0]const u8 { - return BUILD_INFO.ptr; +fn validateTraceC( + trace: [*c]const u8, + anchors: [*c]const u8, + qname: [*c]const u8, + qtype: u16, + now: i64, + policy: u32, + out: [*c]Verdict, + text: [*c]u8, + text_cap: usize, +) callconv(.c) c_int { + return @backingInt(validateTraceWith(c_allocator, @ptrCast(trace), .{ + .anchors = @ptrCast(anchors), + .qname = @ptrCast(qname), + .qtype = qtype, + .now = now, + .policy = policy, + .out = out, + .text = text, + .text_cap = text_cap, + })); } -//============================================================================== -// Callback Support -//============================================================================== - -/// Callback function type (C ABI) -pub const Callback = *const fn (u64, u32) callconv(.c) u32; - -/// Register a callback -export fn zig_dnssec_register_callback( - handle: ?*Handle, - callback: ?Callback, -) Result { - const h = handle orelse { - setError("Null handle"); - return .null_pointer; - }; - - const cb = callback orelse { - setError("Null callback"); - return .null_pointer; - }; - - if (!h.initialized) { - setError("Handle not initialized"); - return .@"error"; - } - - // Store callback for later use - _ = cb; - - clearError(); - return .ok; +fn statusName(status: c_int) callconv(.c) [*c]const u8 { + const s = std.enums.fromInt(Status, status) orelse return "unknown"; + return @tagName(s); } -//============================================================================== -// Utility Functions -//============================================================================== - -/// Check if handle is initialized -export fn zig_dnssec_is_initialized(handle: ?*Handle) u32 { - const h = handle orelse return 0; - return if (h.initialized) 1 else 0; +fn securityName(security: u8) callconv(.c) [*c]const u8 { + const s = std.enums.fromInt(Security, security) orelse return "unknown"; + return @tagName(s); } -//============================================================================== -// Tests -//============================================================================== - -test "lifecycle" { - const handle = zig_dnssec_init() orelse return error.InitFailed; - defer zig_dnssec_free(handle); - - try std.testing.expect(zig_dnssec_is_initialized(handle) == 1); +fn reasonName(reason: u8) callconv(.c) [*c]const u8 { + if (reason >= reason_names.len) return "unknown"; + return reason_names[reason]; } -test "error handling" { - const result = zig_dnssec_process(null, 0); - try std.testing.expectEqual(Result.null_pointer, result); - - const err = zig_dnssec_last_error(); - try std.testing.expect(err != null); +/// Exports each function under its header name after checking that its type +/// is exactly the type the header declares. +fn exportChecked(comptime f: anytype, comptime name: []const u8) void { + if (@TypeOf(f) != @TypeOf(@field(h, name))) + @compileError(name ++ ": implementation type " ++ @typeName(@TypeOf(f)) ++ + " differs from the header's " ++ @typeName(@TypeOf(@field(h, name)))); + @export(&f, .{ .name = name }); } -test "version" { - const ver = zig_dnssec_version(); - const ver_str = std.mem.span(ver); - try std.testing.expectEqualStrings(VERSION, ver_str); +comptime { + exportChecked(abiVersion, "zig_dnssec_abi_version"); + exportChecked(validateC, "zig_dnssec_validate"); + exportChecked(validateTraceC, "zig_dnssec_validate_trace"); + exportChecked(statusName, "zig_dnssec_status_name"); + exportChecked(securityName, "zig_dnssec_security_name"); + exportChecked(reasonName, "zig_dnssec_reason_name"); } diff --git a/src/interface/ffi/test/README.adoc b/src/interface/ffi/test/README.adoc index e6ff2679..9b0c208c 100644 --- a/src/interface/ffi/test/README.adoc +++ b/src/interface/ffi/test/README.adoc @@ -1,3 +1,6 @@ // SPDX-License-Identifier: CC-BY-SA-4.0 -// Copyright (c) Jonathan D.A. Jewell -= Test Logic +// SPDX-FileCopyrightText: 2026 Jonathan D.A. Jewell += C ABI tests + +`abi_test.zig` calls the library through the header's declarations; `seam_test.zig` +compares the Idris2 model with the header. Both run in `zig build test`. diff --git a/src/interface/ffi/test/abi_test.zig b/src/interface/ffi/test/abi_test.zig new file mode 100644 index 00000000..7b8af8ef --- /dev/null +++ b/src/interface/ffi/test/abi_test.zig @@ -0,0 +1,383 @@ +// SPDX-License-Identifier: MPL-2.0 +// SPDX-FileCopyrightText: 2026 Jonathan D.A. Jewell + +//! Tests of the C ABI. Most calls go through the header's own declarations +//! (`h.zig_dnssec_*`, the extern functions translate-c makes from +//! zig_dnssec.h), so they exercise the exported symbols with the C calling +//! convention exactly as a C caller would. The allocator-checked tests call +//! the same code through `ffi.validateTraceWith` under the leak checker. +//! +//! Fixtures are the recorded cross-check responses (tests/testdata/), replayed +//! offline. + +const std = @import("std"); +const testing = std.testing; +const h = @import("zig_dnssec_h"); +const ffi = @import("ffi"); +const lib = @import("dnssec"); + +const traces_src = @embedFile("crosscheck.traces"); +const anchor_src = @embedFile("crosscheck-root.anchor"); + +/// 2026-10-14T00:00:00Z: inside the fixtures' signing window. +const now: i64 = 1791936000; + +const qtype_a: u16 = 1; +const qtype_aaaa: u16 = 28; + +/// The trace lines of one recorded scenario, as a NUL-terminated string. +fn scenario(gpa: std.mem.Allocator, qname: []const u8, qtype: []const u8) ![:0]u8 { + var header_buf: [300]u8 = undefined; + const header = try std.fmt.bufPrint(&header_buf, "@query {s} {s} ", .{ qname, qtype }); + const start = std.mem.indexOf(u8, traces_src, header) orelse return error.NoSuchScenario; + const body_start = std.mem.indexOfScalarPos(u8, traces_src, start, '\n').? + 1; + const end = std.mem.indexOfPos(u8, traces_src, body_start, "\n@query ") orelse traces_src.len; + return gpa.dupeSentinel(u8, traces_src[body_start..end], 0); +} + +fn poisoned() h.zig_dnssec_verdict { + var v: h.zig_dnssec_verdict = undefined; + @memset(std.mem.asBytes(&v), 0xAA); + return v; +} + +fn whereText(v: *const h.zig_dnssec_verdict) []const u8 { + return std.mem.sliceTo(&v.where, 0); +} + +const anchors_z: [:0]const u8 = anchor_src; + +test "ABI version and layout" { + try testing.expectEqual(@as(u32, h.ZIG_DNSSEC_ABI_VERSION), h.zig_dnssec_abi_version()); + try testing.expectEqual(@as(usize, 1048), @sizeOf(h.zig_dnssec_verdict)); + try testing.expectEqual(@as(usize, 4), @alignOf(h.zig_dnssec_verdict)); +} + +test "secure answer: verdict, text and NUL" { + const trace = try scenario(testing.allocator, "www.rsasha256.test.", "A"); + defer testing.allocator.free(trace); + var v = poisoned(); + var text: [4096]u8 = undefined; + const rc = h.zig_dnssec_validate_trace(trace.ptr, anchors_z.ptr, "www.rsasha256.test.", qtype_a, now, 0, &v, &text, text.len); + try testing.expectEqual(@as(c_int, h.ZIG_DNSSEC_OK), rc); + try testing.expectEqual(@as(u8, h.ZIG_DNSSEC_SECURITY_SECURE), v.security); + try testing.expectEqual(@as(u8, h.ZIG_DNSSEC_REASON_NONE), v.reason); + try testing.expectEqual(@as(u16, 0), v.reserved); + try testing.expectEqual(@as(u16, 0), v.rcode); + try testing.expectEqual(@as(u16, 0), v.rtype); + try testing.expect(v.ttl > 0); + try testing.expect(v.verifications > 0); + try testing.expectEqualStrings("", whereText(&v)); + const body = text[0..v.text_len]; + try testing.expectEqual(@as(u8, 0), text[v.text_len]); + try testing.expect(std.mem.startsWith(u8, body, "www.rsasha256.test.")); + try testing.expect(std.mem.endsWith(u8, body, "\n")); + try testing.expect(std.mem.indexOf(u8, body, "\tA\t") != null or std.mem.indexOf(u8, body, " A ") != null); +} + +test "insecure answer carries the reason, the zone and the answer" { + const trace = try scenario(testing.allocator, "www.insecure.test.", "A"); + defer testing.allocator.free(trace); + var v = poisoned(); + var text: [4096]u8 = undefined; + const rc = h.zig_dnssec_validate_trace(trace.ptr, anchors_z.ptr, "www.insecure.test.", qtype_a, now, 0, &v, &text, text.len); + try testing.expectEqual(@as(c_int, h.ZIG_DNSSEC_OK), rc); + try testing.expectEqual(@as(u8, h.ZIG_DNSSEC_SECURITY_INSECURE), v.security); + try testing.expectEqual(@as(u8, h.ZIG_DNSSEC_REASON_INSECURE_DELEGATION), v.reason); + try testing.expectEqualStrings("insecure.test.", whereText(&v)); + try testing.expect(v.text_len > 0); + try testing.expect(std.mem.startsWith(u8, text[0..v.text_len], "www.insecure.test.")); +} + +test "bogus answer: no answer text at all" { + const trace = try scenario(testing.allocator, "www.expired.test.", "A"); + defer testing.allocator.free(trace); + var v = poisoned(); + var text: [4096]u8 = undefined; + @memset(&text, 'X'); + const rc = h.zig_dnssec_validate_trace(trace.ptr, anchors_z.ptr, "www.expired.test.", qtype_a, now, 0, &v, &text, text.len); + try testing.expectEqual(@as(c_int, h.ZIG_DNSSEC_OK), rc); + try testing.expectEqual(@as(u8, h.ZIG_DNSSEC_SECURITY_BOGUS), v.security); + try testing.expectEqual(@as(u8, h.ZIG_DNSSEC_REASON_SIGNATURE_EXPIRED), v.reason); + try testing.expectEqual(@as(u32, 0), v.text_len); + try testing.expectEqual(@as(u32, 0), v.ttl); + try testing.expect(whereText(&v).len > 0); + try testing.expect(v.rtype != 0); + // The buffer is the empty string; nothing past the NUL was touched. + try testing.expectEqual(@as(u8, 0), text[0]); + for (text[1..]) |c| try testing.expectEqual(@as(u8, 'X'), c); +} + +test "every recorded bogus scenario yields no answer text through the C ABI" { + var lines = std.mem.splitScalar(u8, traces_src, '\n'); + var checked: usize = 0; + var text: [65536]u8 = undefined; + while (lines.next()) |line| { + if (!std.mem.startsWith(u8, line, "@query ")) continue; + var it = std.mem.tokenizeScalar(u8, line[7..], ' '); + const qname = it.next().?; + const qtype_text = it.next().?; + const expected = it.next().?; + if (!std.mem.eql(u8, expected, "bogus")) continue; + const trace = try scenario(testing.allocator, qname, qtype_text); + defer testing.allocator.free(trace); + const qname_z = try testing.allocator.dupeSentinel(u8, qname, 0); + defer testing.allocator.free(qname_z); + const qtype = lib.wire.Type.fromMnemonic(qtype_text).?.toInt(); + var v = poisoned(); + @memset(&text, 'X'); + const rc = h.zig_dnssec_validate_trace(trace.ptr, anchors_z.ptr, qname_z.ptr, qtype, now, 0, &v, &text, text.len); + try testing.expectEqual(@as(c_int, h.ZIG_DNSSEC_OK), rc); + // Unbound's bogus is ours too in every recorded case (tests/replay.zig). + try testing.expect(v.security == h.ZIG_DNSSEC_SECURITY_BOGUS); + try testing.expectEqual(@as(u32, 0), v.text_len); + try testing.expectEqual(@as(u8, 0), text[0]); + try testing.expectEqual(@as(u8, 'X'), text[1]); + checked += 1; + } + try testing.expect(checked >= 40); +} + +test "policy flags reach the validator" { + const trace = try scenario(testing.allocator, "www.ed448.test.", "A"); + defer testing.allocator.free(trace); + var v = poisoned(); + var rc = h.zig_dnssec_validate_trace(trace.ptr, anchors_z.ptr, "www.ed448.test.", qtype_a, now, 0, &v, null, 0); + try testing.expectEqual(@as(c_int, h.ZIG_DNSSEC_OK), rc); + try testing.expectEqual(@as(u8, h.ZIG_DNSSEC_SECURITY_BOGUS), v.security); + try testing.expectEqual(@as(u8, h.ZIG_DNSSEC_REASON_UNSUPPORTED_ALGORITHM), v.reason); + + rc = h.zig_dnssec_validate_trace(trace.ptr, anchors_z.ptr, "www.ed448.test.", qtype_a, now, h.ZIG_DNSSEC_POLICY_UNSUPPORTED_INSECURE, &v, null, 0); + try testing.expectEqual(@as(c_int, h.ZIG_DNSSEC_OK), rc); + try testing.expectEqual(@as(u8, h.ZIG_DNSSEC_SECURITY_INSECURE), v.security); + try testing.expectEqual(@as(u8, h.ZIG_DNSSEC_REASON_UNSUPPORTED_ALGORITHM_POLICY), v.reason); + // text == NULL: verdict only, but the size is still reported. + try testing.expect(v.text_len > 0); + + const hi = try scenario(testing.allocator, "nx.highiter.test.", "A"); + defer testing.allocator.free(hi); + rc = h.zig_dnssec_validate_trace(hi.ptr, anchors_z.ptr, "nx.highiter.test.", qtype_a, now, 0, &v, null, 0); + try testing.expectEqual(@as(u8, h.ZIG_DNSSEC_REASON_NSEC3_ITERATIONS_EXCEEDED), v.reason); + rc = h.zig_dnssec_validate_trace(hi.ptr, anchors_z.ptr, "nx.highiter.test.", qtype_a, now, h.ZIG_DNSSEC_POLICY_ITERATIONS_INSECURE, &v, null, 0); + try testing.expectEqual(@as(c_int, h.ZIG_DNSSEC_OK), rc); + try testing.expectEqual(@as(u8, h.ZIG_DNSSEC_SECURITY_INSECURE), v.security); + try testing.expectEqual(@as(u8, h.ZIG_DNSSEC_REASON_NSEC3_ITERATIONS_POLICY), v.reason); +} + +test "bad arguments fail closed: status set, security NONE" { + const trace = try scenario(testing.allocator, "www.rsasha256.test.", "A"); + defer testing.allocator.free(trace); + const T = struct { + trace: ?[*:0]const u8, + anchors: ?[*:0]const u8, + qname: ?[*:0]const u8, + qtype: u16 = qtype_a, + policy: u32 = 0, + expect: c_int, + }; + const cases = [_]T{ + .{ .trace = null, .anchors = anchors_z.ptr, .qname = "www.rsasha256.test.", .expect = h.ZIG_DNSSEC_ERR_INVALID_ARGUMENT }, + .{ .trace = trace.ptr, .anchors = anchors_z.ptr, .qname = null, .expect = h.ZIG_DNSSEC_ERR_INVALID_ARGUMENT }, + .{ .trace = trace.ptr, .anchors = anchors_z.ptr, .qname = "www.rsasha256.test.", .policy = 8, .expect = h.ZIG_DNSSEC_ERR_INVALID_ARGUMENT }, + .{ .trace = trace.ptr, .anchors = anchors_z.ptr, .qname = "www.rsasha256.test.", .policy = 0x8000_0000, .expect = h.ZIG_DNSSEC_ERR_INVALID_ARGUMENT }, + .{ .trace = trace.ptr, .anchors = anchors_z.ptr, .qname = "www.rsasha256.test.", .qtype = 0, .expect = h.ZIG_DNSSEC_ERR_INVALID_ARGUMENT }, + .{ .trace = trace.ptr, .anchors = anchors_z.ptr, .qname = "www.rsasha256.test.", .qtype = 255, .expect = h.ZIG_DNSSEC_ERR_INVALID_ARGUMENT }, + .{ .trace = trace.ptr, .anchors = anchors_z.ptr, .qname = "www.rsasha256.test.", .qtype = 41, .expect = h.ZIG_DNSSEC_ERR_INVALID_ARGUMENT }, + .{ .trace = trace.ptr, .anchors = anchors_z.ptr, .qname = "a..b", .expect = h.ZIG_DNSSEC_ERR_BAD_NAME }, + .{ .trace = trace.ptr, .anchors = "not an anchor", .qname = "www.rsasha256.test.", .expect = h.ZIG_DNSSEC_ERR_BAD_ANCHORS }, + .{ .trace = trace.ptr, .anchors = "", .qname = "www.rsasha256.test.", .expect = h.ZIG_DNSSEC_ERR_BAD_ANCHORS }, + .{ .trace = trace.ptr, .anchors = ". 3600 IN A 192.0.2.1\n", .qname = "www.rsasha256.test.", .expect = h.ZIG_DNSSEC_ERR_BAD_ANCHORS }, + .{ .trace = "www.rsasha256.test. A !!!not-base64!!!\n", .anchors = anchors_z.ptr, .qname = "www.rsasha256.test.", .expect = h.ZIG_DNSSEC_ERR_BAD_TRACE }, + // A trace with nothing for the question: the initial query fails. + .{ .trace = "", .anchors = anchors_z.ptr, .qname = "www.rsasha256.test.", .expect = h.ZIG_DNSSEC_ERR_QUERY_FAILED }, + }; + for (cases) |c| { + var v = poisoned(); + var text: [64]u8 = undefined; + @memset(&text, 'X'); + const rc = h.zig_dnssec_validate_trace(c.trace, c.anchors, c.qname, c.qtype, now, c.policy, &v, &text, text.len); + 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'); + } + // A NULL verdict pointer is rejected without writing anything. + 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)); +} + +test "NULL anchors select the IANA root, which does not sign the fixtures" { + const trace = try scenario(testing.allocator, "www.rsasha256.test.", "A"); + defer testing.allocator.free(trace); + var v = poisoned(); + var text: [256]u8 = undefined; + const rc = h.zig_dnssec_validate_trace(trace.ptr, null, "www.rsasha256.test.", qtype_a, now, 0, &v, &text, text.len); + try testing.expectEqual(@as(c_int, h.ZIG_DNSSEC_OK), rc); + try testing.expectEqual(@as(u8, h.ZIG_DNSSEC_SECURITY_BOGUS), v.security); + try testing.expectEqual(@as(u32, 0), v.text_len); +} + +test "a buffer that is too small: status, size needed, no verdict" { + const trace = try scenario(testing.allocator, "www.rsasha256.test.", "A"); + defer testing.allocator.free(trace); + var v = poisoned(); + var small: [4]u8 = undefined; + var rc = h.zig_dnssec_validate_trace(trace.ptr, anchors_z.ptr, "www.rsasha256.test.", qtype_a, now, 0, &v, &small, small.len); + try testing.expectEqual(@as(c_int, h.ZIG_DNSSEC_ERR_BUFFER_TOO_SMALL), rc); + try testing.expectEqual(@as(u8, h.ZIG_DNSSEC_SECURITY_NONE), v.security); + try testing.expectEqual(@as(u8, 0), small[0]); + const need = v.text_len; + try testing.expect(need > small.len); + + // Exactly the size needed plus the NUL is enough. + const buf = try testing.allocator.alloc(u8, need + 1); + defer testing.allocator.free(buf); + rc = h.zig_dnssec_validate_trace(trace.ptr, anchors_z.ptr, "www.rsasha256.test.", qtype_a, now, 0, &v, buf.ptr, buf.len); + try testing.expectEqual(@as(c_int, h.ZIG_DNSSEC_OK), rc); + try testing.expectEqual(@as(u8, h.ZIG_DNSSEC_SECURITY_SECURE), v.security); + try testing.expectEqual(need, v.text_len); + try testing.expectEqual(@as(u8, 0), buf[need]); + // One byte less is not. + rc = h.zig_dnssec_validate_trace(trace.ptr, anchors_z.ptr, "www.rsasha256.test.", qtype_a, now, 0, &v, buf.ptr, need); + try testing.expectEqual(@as(c_int, h.ZIG_DNSSEC_ERR_BUFFER_TOO_SMALL), rc); +} + +// ---- callback transport ---------------------------------------------------- + +const Served = struct { + records: []const lib.stub.transport.Recorded, + calls: usize = 0, + fail: bool = false, +}; + +fn serve(ctx: ?*anyopaque, query: [*c]const u8, query_len: usize, response: [*c]u8, cap: usize, len: [*c]usize) callconv(.c) c_int { + const s: *Served = @ptrCast(@alignCast(ctx.?)); + s.calls += 1; + if (s.fail) return 1; + var replay: lib.stub.transport.ReplayTransport = .{ .records = s.records }; + const q = testing.allocator.dupe(u8, query[0..query_len]) catch return 1; + defer testing.allocator.free(q); + const r = replay.transport().exchange(testing.allocator, q) catch return 1; + defer testing.allocator.free(r); + if (r.len > cap) return 1; + @memcpy(response[0..r.len], r); + len.* = r.len; + return 0; +} + +test "callback transport: queries go through the caller's function" { + const trace = try scenario(testing.allocator, "www.ecdsa256.test.", "AAAA"); + defer testing.allocator.free(trace); + var parsed = try lib.stub.transport.Trace.parse(testing.allocator, trace); + defer parsed.deinit(); + var served: Served = .{ .records = parsed.records }; + var v = poisoned(); + var text: [4096]u8 = undefined; + const rc = h.zig_dnssec_validate(serve, &served, anchors_z.ptr, "www.ecdsa256.test.", qtype_aaaa, now, 0, &v, &text, text.len); + try testing.expectEqual(@as(c_int, h.ZIG_DNSSEC_OK), rc); + try testing.expectEqual(@as(u8, h.ZIG_DNSSEC_SECURITY_SECURE), v.security); + try testing.expectEqual(served.calls, v.fetches + 1); + try testing.expect(std.mem.startsWith(u8, text[0..v.text_len], "www.ecdsa256.test.")); + + // A failing transport on the first query is QUERY_FAILED, not a verdict. + served = .{ .records = parsed.records, .fail = true }; + v = poisoned(); + try testing.expectEqual(@as(c_int, h.ZIG_DNSSEC_ERR_QUERY_FAILED), h.zig_dnssec_validate(serve, &served, anchors_z.ptr, "www.ecdsa256.test.", qtype_aaaa, now, 0, &v, &text, text.len)); + try testing.expectEqual(@as(u8, h.ZIG_DNSSEC_SECURITY_NONE), v.security); + + // A NULL callback is an invalid argument. + v = poisoned(); + try testing.expectEqual(@as(c_int, h.ZIG_DNSSEC_ERR_INVALID_ARGUMENT), h.zig_dnssec_validate(null, null, anchors_z.ptr, "www.ecdsa256.test.", qtype_aaaa, now, 0, &v, &text, text.len)); + try testing.expectEqual(@as(u8, h.ZIG_DNSSEC_SECURITY_NONE), v.security); +} + +fn lie(ctx: ?*anyopaque, query: [*c]const u8, query_len: usize, response: [*c]u8, cap: usize, len: [*c]usize) callconv(.c) c_int { + _ = .{ ctx, query, query_len, response }; + len.* = cap + 1; + return 0; +} + +test "callback transport: a length beyond the buffer is a failed exchange" { + var v = poisoned(); + try testing.expectEqual(@as(c_int, h.ZIG_DNSSEC_ERR_QUERY_FAILED), h.zig_dnssec_validate(lie, null, anchors_z.ptr, "www.ecdsa256.test.", qtype_aaaa, now, 0, &v, null, 0)); + try testing.expectEqual(@as(u8, h.ZIG_DNSSEC_SECURITY_NONE), v.security); +} + +test "names" { + try testing.expectEqualStrings("ok", std.mem.span(h.zig_dnssec_status_name(h.ZIG_DNSSEC_OK))); + try testing.expectEqualStrings("buffer_too_small", std.mem.span(h.zig_dnssec_status_name(h.ZIG_DNSSEC_ERR_BUFFER_TOO_SMALL))); + try testing.expectEqualStrings("unknown", std.mem.span(h.zig_dnssec_status_name(-1))); + try testing.expectEqualStrings("unknown", std.mem.span(h.zig_dnssec_status_name(99))); + try testing.expectEqualStrings("none", std.mem.span(h.zig_dnssec_security_name(h.ZIG_DNSSEC_SECURITY_NONE))); + try testing.expectEqualStrings("secure", std.mem.span(h.zig_dnssec_security_name(h.ZIG_DNSSEC_SECURITY_SECURE))); + try testing.expectEqualStrings("indeterminate", std.mem.span(h.zig_dnssec_security_name(h.ZIG_DNSSEC_SECURITY_INDETERMINATE))); + try testing.expectEqualStrings("unknown", std.mem.span(h.zig_dnssec_security_name(5))); + try testing.expectEqualStrings("none", std.mem.span(h.zig_dnssec_reason_name(0))); + try testing.expectEqualStrings("signature_expired", std.mem.span(h.zig_dnssec_reason_name(h.ZIG_DNSSEC_REASON_SIGNATURE_EXPIRED))); + try testing.expectEqualStrings("truncated", std.mem.span(h.zig_dnssec_reason_name(h.ZIG_DNSSEC_REASON_TRUNCATED))); + try testing.expectEqualStrings("unknown", std.mem.span(h.zig_dnssec_reason_name(30))); + try testing.expectEqualStrings("unknown", std.mem.span(h.zig_dnssec_reason_name(255))); + // Every validator reason has a name equal to its Zig tag. + for (std.enums.values(lib.sec.validator.Reason)) |r| { + try testing.expectEqualStrings(@tagName(r), std.mem.span(h.zig_dnssec_reason_name(ffi.reasonCode(r)))); + } +} + +test "no leaks, through the allocator-parametric core" { + const qs = [_]struct { n: [:0]const u8, t: []const u8, ty: u16 }{ + .{ .n = "www.rsasha256.test.", .t = "A", .ty = qtype_a }, + .{ .n = "www.insecure.test.", .t = "A", .ty = qtype_a }, + .{ .n = "www.expired.test.", .t = "A", .ty = qtype_a }, + .{ .n = "nx.ecdsa256.test.", .t = "A", .ty = qtype_a }, + }; + for (qs) |q| { + const trace = try scenario(testing.allocator, q.n, q.t); + defer testing.allocator.free(trace); + var v: h.zig_dnssec_verdict = undefined; + var text: [4096]u8 = undefined; + const st = ffi.validateTraceWith(testing.allocator, trace.ptr, .{ + .anchors = anchors_z.ptr, + .qname = q.n.ptr, + .qtype = q.ty, + .now = now, + .policy = 0, + .out = &v, + .text = &text, + .text_cap = text.len, + }); + try testing.expectEqual(ffi.Status.ok, st); + try testing.expect(v.security != h.ZIG_DNSSEC_SECURITY_NONE); + } +} + +test "no leaks or crashes when allocation fails at any point" { + const trace = try scenario(testing.allocator, "www.rsasha256.test.", "A"); + defer testing.allocator.free(trace); + var i: usize = 0; + while (true) : (i += 1) { + var failing = std.testing.FailingAllocator.init(testing.allocator, .{ .fail_index = i }); + var v: h.zig_dnssec_verdict = undefined; + var text: [4096]u8 = undefined; + const st = ffi.validateTraceWith(failing.allocator(), trace.ptr, .{ + .anchors = anchors_z.ptr, + .qname = "www.rsasha256.test.", + .qtype = qtype_a, + .now = now, + .policy = 0, + .out = &v, + .text = &text, + .text_cap = text.len, + }); + if (!failing.has_induced_failure) { + try testing.expectEqual(ffi.Status.ok, st); + try testing.expectEqual(@as(u8, h.ZIG_DNSSEC_SECURITY_SECURE), v.security); + break; + } + // An allocation failure never produces a verdict that could be used. + if (st != .ok) { + try testing.expectEqual(@as(u8, h.ZIG_DNSSEC_SECURITY_NONE), v.security); + } else { + try testing.expect(v.security != h.ZIG_DNSSEC_SECURITY_SECURE); + } + } + try testing.expect(i > 10); +} diff --git a/src/interface/ffi/test/integration_test.zig b/src/interface/ffi/test/integration_test.zig deleted file mode 100644 index 484e1566..00000000 --- a/src/interface/ffi/test/integration_test.zig +++ /dev/null @@ -1,66 +0,0 @@ -// SPDX-License-Identifier: MPL-2.0 -// Copyright (c) Jonathan D.A. Jewell -// RSR Template FFI Integration Tests -// -// These tests verify that the Zig FFI correctly implements the Idris2 ABI. -// This is a TEMPLATE FILE — when instantiating a new project: -// 1. Replace "template" with your project name in lowercase -// 2. Link against your actual FFI implementation library -// 3. Uncomment the test functions below -// -// For now, this file contains documentation of what tests should exist. - -const std = @import("std"); - -// NOTE: When instantiated, declare the actual FFI functions here: -// extern fn mylib_init() ?*Handle; -// extern fn mylib_free(?*Handle) void; -// ... etc - -// And define Handle appropriately: -// const Handle = opaque {}; - -test "placeholder test - implementation required" { - // This test ensures the file compiles - // Actual tests depend on FFI implementation - try std.testing.expect(true); -} - -// ============================================================================== -// Example tests (uncomment when instantiated with real FFI): -// ============================================================================== -// -// test "lifecycle: create and destroy handle" { -// const handle = mylib_init() orelse return error.InitFailed; -// defer mylib_free(handle); -// } -// -// test "operations: process with valid handle" { -// const handle = mylib_init() orelse return error.InitFailed; -// defer mylib_free(handle); -// -// const result = mylib_process(handle, 42); -// try std.testing.expectEqual(@as(c_int, 0), result); -// } -// -// test "memory safety: double free is safe" { -// const handle = mylib_init() orelse return error.InitFailed; -// mylib_free(handle); -// mylib_free(handle); // Should not crash -// } -// -// test "strings: get string result from handle" { -// const handle = mylib_init() orelse return error.InitFailed; -// defer mylib_free(handle); -// -// const str = mylib_get_string(handle); -// defer if (str) |s| mylib_free_string(s); -// -// try std.testing.expect(str != null); -// } -// -// test "version: returns non-empty version string" { -// const ver = mylib_version(); -// const ver_str = std.mem.span(ver); -// try std.testing.expect(ver_str.len > 0); -// } diff --git a/src/interface/ffi/test/seam_test.zig b/src/interface/ffi/test/seam_test.zig new file mode 100644 index 00000000..207cb3e2 --- /dev/null +++ b/src/interface/ffi/test/seam_test.zig @@ -0,0 +1,293 @@ +// SPDX-License-Identifier: MPL-2.0 +// SPDX-FileCopyrightText: 2026 Jonathan D.A. Jewell + +//! Keeps the three sides of the seam in step: the C header (the contract), +//! the Zig validator, and the Idris2 model in src/interface/Abi/. +//! +//! The Idris sources are read as text and the facts they state (codes, +//! field offsets, foreign signatures) are compared with the header as the C +//! compiler sees it (translate-c). The Idris side's own proofs (round trips, +//! alignment, the answer rule) are checked by `idris2 --typecheck`; this test +//! checks that what it proves things *about* is the real interface. + +const std = @import("std"); +const testing = std.testing; +const h = @import("zig_dnssec_h"); +const lib = @import("dnssec"); +// Links the exported functions, whose types the signature checks inspect. +comptime { + _ = @import("ffi"); +} + +const types_idr = @embedFile("Types.idr"); +const layout_idr = @embedFile("Layout.idr"); +const foreign_idr = @embedFile("Foreign.idr"); + +/// "Nsec3OptOut" -> "NSEC3_OPT_OUT" +fn screaming(buf: []u8, camel: []const u8) []const u8 { + var n: usize = 0; + for (camel, 0..) |c, i| { + if (i > 0 and std.ascii.isUpper(c)) { + buf[n] = '_'; + n += 1; + } + buf[n] = std.ascii.toUpper(c); + n += 1; + } + return buf[0..n]; +} + +/// The header's integer macros, by name, as the C preprocessor defines them. +fn macro(name: []const u8) ?i64 { + @setEvalBranchQuota(100_000); + inline for (comptime std.meta.declarations(h)) |d| { + if (comptime std.mem.startsWith(u8, d, "ZIG_DNSSEC_")) { + const v = @field(h, d); + if (comptime (@typeInfo(@TypeOf(v)) == .int or @typeInfo(@TypeOf(v)) == .comptime_int)) { + if (std.mem.eql(u8, d, name)) return v; + } + } + } + return null; +} + +/// Header macro names with a given prefix. +fn macrosWithPrefix(gpa: std.mem.Allocator, prefix: []const u8) ![][]const u8 { + var list: std.ArrayList([]const u8) = .empty; + @setEvalBranchQuota(100_000); + inline for (comptime std.meta.declarations(h)) |d| { + if (std.mem.startsWith(u8, d, prefix)) try list.append(gpa, d); + } + return list.toOwnedSlice(gpa); +} + +const Clause = struct { ctor: []const u8, value: i64 }; + +/// Lines of the form " = " in Types.idr. +fn clauses(gpa: std.mem.Allocator, fun: []const u8) ![]Clause { + var list: std.ArrayList(Clause) = .empty; + var lines = std.mem.splitScalar(u8, types_idr, '\n'); + while (lines.next()) |line| { + var it = std.mem.tokenizeScalar(u8, line, ' '); + const f = it.next() orelse continue; + if (!std.mem.eql(u8, f, fun)) continue; + const ctor = it.next() orelse continue; + const eq = it.next() orelse continue; + if (!std.mem.eql(u8, eq, "=")) continue; + const v = it.next() orelse continue; + try list.append(gpa, .{ .ctor = ctor, .value = try std.fmt.parseInt(i64, v, 10) }); + } + return list.toOwnedSlice(gpa); +} + +fn expectCodes(fun: []const u8, comptime prefix: []const u8, ok_name: ?[]const u8) !void { + var arena: std.heap.ArenaAllocator = .init(testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const cs = try clauses(a, fun); + try testing.expect(cs.len > 0); + var buf: [128]u8 = undefined; + var seen: std.StringHashMap(void) = .init(a); + for (cs) |c| { + const name = if (ok_name != null and std.mem.eql(u8, c.ctor, "Ok")) + ok_name.? + else + try std.fmt.allocPrint(a, "{s}{s}", .{ prefix, screaming(&buf, c.ctor) }); + const v = macro(name) orelse { + std.debug.print("Idris {s} {s}: header has no {s}\n", .{ fun, c.ctor, name }); + return error.MissingMacro; + }; + if (v != c.value) { + std.debug.print("Idris {s} {s} = {d}, header {s} = {d}\n", .{ fun, c.ctor, c.value, name, v }); + return error.CodeMismatch; + } + try seen.put(name, {}); + } + // ... and every header code of this family is modelled in Idris (NONE is + // the absence of a value and is deliberately not a constructor). + for (try macrosWithPrefix(a, prefix)) |m| { + if (std.mem.endsWith(u8, m, "_NONE")) continue; + if (!seen.contains(m)) { + std.debug.print("header {s} has no Idris constructor in {s}\n", .{ m, fun }); + return error.UnmodelledMacro; + } + } +} + +test "Idris status codes are the header's" { + try expectCodes("statusCode", "ZIG_DNSSEC_ERR_", "ZIG_DNSSEC_OK"); +} + +test "Idris security codes are the header's" { + try expectCodes("securityCode", "ZIG_DNSSEC_SECURITY_", null); +} + +test "Idris reason codes are the header's" { + try expectCodes("reasonCode", "ZIG_DNSSEC_REASON_", null); +} + +test "Idris policy bits are the header's" { + try expectCodes("policyBit", "ZIG_DNSSEC_POLICY_", null); +} + +test "Idris reasons are the validator's reasons, one for one" { + var arena: std.heap.ArenaAllocator = .init(testing.allocator); + defer arena.deinit(); + const cs = try clauses(arena.allocator(), "reasonCode"); + const zig_reasons = std.enums.values(lib.sec.validator.Reason); + try testing.expectEqual(zig_reasons.len, cs.len); + var buf: [128]u8 = undefined; + for (zig_reasons) |r| { + const found = for (cs) |c| { + const snake = std.ascii.lowerString(&buf, screaming(&buf, c.ctor)); + if (std.mem.eql(u8, snake, @tagName(r))) break true; + } else false; + if (!found) { + std.debug.print("validator reason {t} has no Idris constructor\n", .{r}); + return error.UnmodelledReason; + } + } +} + +test "Idris verdict layout is the C compiler's" { + const V = h.zig_dnssec_verdict; + var count: usize = 0; + var lines = std.mem.splitScalar(u8, layout_idr, '\n'); + while (lines.next()) |line| { + const at = std.mem.indexOf(u8, line, "MkField \"") orelse continue; + var rest = line[at + "MkField \"".len ..]; + const q = std.mem.indexOfScalar(u8, rest, '"') orelse continue; + const name = rest[0..q]; + rest = rest[q + 1 ..]; + var it = std.mem.tokenizeScalar(u8, rest, ' '); + const off = try std.fmt.parseInt(usize, it.next().?, 10); + const size = try std.fmt.parseInt(usize, it.next().?, 10); + const alignment = try std.fmt.parseInt(usize, it.next().?, 10); + var matched = false; + const vi = @typeInfo(V).@"struct"; + inline for (vi.field_names, vi.field_types) |fname, FT| { + if (std.mem.eql(u8, fname, name)) { + matched = true; + try testing.expectEqual(@offsetOf(V, fname), off); + try testing.expectEqual(@sizeOf(FT), size); + const elem_align = switch (@typeInfo(FT)) { + .array => |arr| @alignOf(arr.child), + else => @alignOf(FT), + }; + try testing.expectEqual(elem_align, alignment); + } + } + if (!matched) { + std.debug.print("Idris field {s} is not in zig_dnssec_verdict\n", .{name}); + return error.UnknownField; + } + count += 1; + } + try testing.expectEqual(@typeInfo(V).@"struct".field_names.len, count); + + const total = std.mem.indexOf(u8, layout_idr, "MkStructLayout verdictFields ").?; + var it = std.mem.tokenizeAny(u8, layout_idr[total + "MkStructLayout verdictFields ".len ..], " \n"); + try testing.expectEqual(@sizeOf(V), try std.fmt.parseInt(usize, it.next().?, 10)); + try testing.expectEqual(@alignOf(V), try std.fmt.parseInt(usize, it.next().?, 10)); + + const wm = std.mem.indexOf(u8, layout_idr, "whereMax = ").?; + var wit = std.mem.tokenizeAny(u8, layout_idr[wm + "whereMax = ".len ..], " \n"); + try testing.expectEqual(@as(i64, h.ZIG_DNSSEC_WHERE_MAX), try std.fmt.parseInt(i64, wit.next().?, 10)); +} + +const Kind = enum { pointer, c_int, u8, u16, u32, u64, i64, other }; + +fn kindOf(comptime T: type) Kind { + return switch (@typeInfo(T)) { + .pointer => .pointer, + .optional => |o| if (@typeInfo(o.child) == .pointer) .pointer else .other, + .int => if (T == c_int) .c_int else if (T == u8) .u8 else if (T == u16) .u16 else if (T == u32) .u32 else if (T == u64 or T == usize) .u64 else if (T == i64) .i64 else .other, + else => .other, + }; +} + +fn idrisKind(t: []const u8) Kind { + if (std.mem.eql(u8, t, "String") or std.mem.eql(u8, t, "AnyPtr") or std.mem.eql(u8, t, "Buffer")) return .pointer; + if (std.mem.eql(u8, t, "Int")) return .c_int; + if (std.mem.eql(u8, t, "Bits8")) return .u8; + if (std.mem.eql(u8, t, "Bits16")) return .u16; + if (std.mem.eql(u8, t, "Bits32")) return .u32; + if (std.mem.eql(u8, t, "Bits64")) return .u64; + if (std.mem.eql(u8, t, "Int64")) return .i64; + return .other; +} + +const header_functions = [_][]const u8{ + "zig_dnssec_abi_version", + "zig_dnssec_validate", + "zig_dnssec_validate_trace", + "zig_dnssec_status_name", + "zig_dnssec_security_name", + "zig_dnssec_reason_name", +}; + +fn signatureMatches(sym: []const u8, args: []const Kind, ret: Kind) !bool { + inline for (header_functions) |name| { + if (std.mem.eql(u8, name, sym)) { + const info = @typeInfo(@TypeOf(@field(h, name))).@"fn"; + if (info.param_types.len != args.len) return false; + inline for (info.param_types, 0..) |pt, i| { + if (kindOf(pt.?) != args[i]) return false; + } + return kindOf(info.return_type.?) == ret; + } + } + return error.NotInHeader; +} + +test "Idris foreign declarations match the header's functions" { + var lines = std.mem.splitScalar(u8, foreign_idr, '\n'); + var checked: usize = 0; + while (lines.next()) |line| { + if (!std.mem.startsWith(u8, line, "%foreign \"C:")) continue; + const spec = line["%foreign \"C:".len..]; + const comma = std.mem.indexOfScalar(u8, spec, ',').?; + const sym = spec[0..comma]; + try testing.expect(std.mem.startsWith(u8, spec[comma + 1 ..], "libzig_dnssec\"")); + // The declaration is the next non-comment line: "prim__x : A -> B -> PrimIO R". + const decl = while (lines.next()) |l| { + if (l.len > 0 and !std.mem.startsWith(u8, l, "--")) break l; + } else return error.NoDeclaration; + const colon = std.mem.indexOf(u8, decl, " : ").?; + var parts = std.mem.splitSequence(u8, decl[colon + 3 ..], " -> "); + var args: [16]Kind = undefined; + var n: usize = 0; + var ret: Kind = .other; + while (parts.next()) |p| { + const t = std.mem.trim(u8, p, " "); + if (std.mem.startsWith(u8, t, "PrimIO ")) { + ret = idrisKind(t["PrimIO ".len..]); + } else { + args[n] = idrisKind(t); + n += 1; + } + } + if (!try signatureMatches(sym, args[0..n], ret)) { + std.debug.print("Idris foreign {s} does not match the header: {s}\n", .{ sym, decl }); + return error.SignatureMismatch; + } + checked += 1; + } + try testing.expect(checked >= 3); + + const v = std.mem.indexOf(u8, foreign_idr, "abiVersion = ").?; + var it = std.mem.tokenizeAny(u8, foreign_idr[v + "abiVersion = ".len ..], " \n"); + try testing.expectEqual(@as(i64, h.ZIG_DNSSEC_ABI_VERSION), try std.fmt.parseInt(i64, it.next().?, 10)); +} + +test "the Idris model has no escape hatches" { + for ([_][]const u8{ types_idr, layout_idr, foreign_idr }) |src| { + try testing.expect(std.mem.indexOf(u8, src, "%default total") != null); + for ([_][]const u8{ "believe_me", "assert_total", "assert_smaller", "idris_crash", "%default partial", "partial\n" }) |bad| { + if (std.mem.indexOf(u8, src, bad) != null) { + std.debug.print("found {s} in the Idris model\n", .{bad}); + return error.EscapeHatch; + } + } + } +} diff --git a/zig-dnssec_chora.deed b/zig-dnssec_chora.deed index c475dbf3..3bb3c1f5 100644 --- a/zig-dnssec_chora.deed +++ b/zig-dnssec_chora.deed @@ -1097,6 +1097,10 @@ "docs/usage.adoc" "src/cli/" "src/dnssec/" + "src/interface/E2e/" + "src/interface/ffi/include/" + "src/interface/ffi/test/abi_test.zig" + "src/interface/ffi/test/seam_test.zig" "src/root.zig" "src/stub/" "src/wire/" @@ -1116,7 +1120,9 @@ "archetypes/" "build/docs-seed/" "build/templates/" - "rsr-template-repo_chora.deed") + "rsr-template-repo_chora.deed" + "src/interface/ffi/build.zig" + "src/interface/ffi/test/integration_test.zig") :diverged ( ".clinerules" ".cursorrules" @@ -1208,7 +1214,15 @@ "scripts/campaigns/www-bundle.campaign" "scripts/check-no-placeholders.sh" "src/README.adoc" + "src/interface/Abi/Foreign.idr" + "src/interface/Abi/Layout.idr" + "src/interface/Abi/README.adoc" + "src/interface/Abi/Types.idr" + "src/interface/README.adoc" + "src/interface/ffi/README.adoc" + "src/interface/ffi/src/README.adoc" "src/interface/ffi/src/main.zig" + "src/interface/ffi/test/README.adoc" "tests/aspect_tests.sh" "tests/e2e.sh" "tests/e2e/template_instantiation_test.sh"