diff --git a/ROADMAP.adoc b/ROADMAP.adoc index 64180e7f..64419755 100644 --- a/ROADMAP.adoc +++ b/ROADMAP.adoc @@ -8,6 +8,20 @@ toc::[] +== Header public-boundary qualification (2026-11-25) + +The next Atoma consumer slice adds a bounded Idris2 span contract and instruments +the actual Zig public entry for null-before-call, exact pointer/length forwarding +and error mapping. Four compiled source mutants and an invalid-span type witness +must reject. The real RefC-backed ABI tests remain required alongside the +instrumented backend. Three additional exported-forwarder mutants exercise +pointer, extent and null refusal through the actual library. A bounded pure Zig +benchmark records correctness-guarded timings of the exported Idris-backed +header operation; these initial samples establish no regression threshold. +Hosted qualification remains required for each changed head; no full +pointer-safety or ownership claim follows from the source files alone. See +link:docs/adr/2026-11-25-header-public-boundary.adoc[the boundary decision]. + == Lifecycle integration (2026-11-25) PR246 integrates lifecycle policy with the current Idris-backed header profile diff --git a/benchmarks/header_boundary.zig b/benchmarks/header_boundary.zig new file mode 100644 index 00000000..82c748e1 --- /dev/null +++ b/benchmarks/header_boundary.zig @@ -0,0 +1,49 @@ +// SPDX-License-Identifier: MPL-2.0 +// Copyright (c) 2026 Jonathan D.A. Jewell +const std = @import("std"); +const builtin = @import("builtin"); +const BoolResult = extern struct { status: c_int, value: bool }; +extern fn proven_header_has_crlf(?[*]const u8, usize) callconv(.c) BoolResult; + +fn requireCorrect(result: BoolResult, expected: bool) !void { + if (result.status != 0) return error.WrongHeaderStatus; + if (result.value != expected) return error.WrongHeaderResult; +} + +fn sampleCase(name: []const u8, input: []const u8, expected: bool, iterations: usize) !void { + // Qualify each corpus before measuring. Timed calls retain correctness + // guards too; elapsed time includes those guards, not only the foreign call. + try requireCorrect(proven_header_has_crlf(input.ptr, input.len), expected); + for (0..32) |_| try requireCorrect(proven_header_has_crlf(input.ptr, input.len), expected); + var digest = [_]u8{0} ** 32; + std.crypto.hash.sha2.Sha256.hash(input, &digest, .{}); + const input_hash = std.fmt.bytesToHex(digest, .lower); + for (0..3) |sample| { + var checksum: usize = 0; + var timer = try std.time.Timer.start(); + for (0..iterations) |_| { + const result = proven_header_has_crlf(input.ptr, input.len); + try requireCorrect(result, expected); + checksum += @intFromBool(result.value); + } + const elapsed = timer.read(); + if (elapsed == 0) return error.TimerResolutionUnavailable; + var buffer = [_]u8{0} ** 1024; + const row = try std.fmt.bufPrint(&buffer, + "{{\"schema\":\"proven.header.benchmark/1\",\"backend\":\"actual-exported-refc-abi\",\"case\":\"{s}\",\"zig\":\"{s}\",\"mode\":\"{s}\",\"sample\":{d},\"bytes\":{d},\"iterations\":{d},\"warmup_iterations\":32,\"elapsed_ns\":{d},\"checksum\":{d},\"expected\":{},\"input_sha256\":\"{s}\",\"timed_correctness_guards\":true,\"correctness\":\"PASS\"}}\n", + .{ name, builtin.zig_version_string, @tagName(builtin.mode), sample, input.len, iterations, elapsed, checksum, expected, input_hash }); + try std.fs.File.stdout().writeAll(row); + } +} + +pub fn main() !void { + var input = [_]u8{'A'} ** 4096; + try sampleCase("empty", input[0..0], false, 4096); + try sampleCase("clean-byte", input[0..1], false, 4096); + try sampleCase("clean-64", input[0..64], false, 2048); + input[63] = 13; + try sampleCase("forbidden-64", input[0..64], true, 2048); + input[63] = 'A'; + input[4095] = 10; + try sampleCase("forbidden-4096", &input, true, 256); +} diff --git a/docs/adr/2026-11-25-header-public-boundary.adoc b/docs/adr/2026-11-25-header-public-boundary.adoc new file mode 100644 index 00000000..bfe4f074 --- /dev/null +++ b/docs/adr/2026-11-25-header-public-boundary.adoc @@ -0,0 +1,92 @@ +// SPDX-License-Identifier: CC-BY-SA-4.0 +// Copyright (c) 2026 Jonathan D.A. Jewell += Header public-entry spans and ownership premises +:revdate: 2026-11-25 + +== Contract and implementation + +The actual public RefC root is `ffi/zig/src/main_refc.zig`. Its export delegates +to `core.headerHasCrlf` with `header_refc.zig` as the backend. The unavailable +root in `main.zig` is a separate profile. The production entry is unchanged: +null is refused with status -1 before creating a slice or invoking a backend; +a non-null pointer is forwarded as exactly `p[0..len]`. Success preserves the +backend Boolean, unavailable maps to -99, and other backend errors map to -7. +Every error result has value false. Backend errors also update thread-local +error storage, which is separate from the borrowed input in the contract. + +`Proven.FFI.HeaderBoundary` defines a bounded logical span over an exact byte +snapshot. An erased proof requires `offset + count <= length memory`. +`spanLength` proves the selected list has exactly the requested count, and +`entryRefinesFold` composes the public-entry contract with the existing checked +Idris scan and authoritative ByteKernel fold. Null and both error classes have +explicit result laws. These are Idris2 ABI contracts, not runtime pointer checks. + +== Native and source qualification + +`scripts/test-header-boundary.sh` compiles a fixture importing the actual +`core.zig`. Its deterministic injected backend observes invocation count, +pointer identity, length and result/error forwarding. Every bounded subspan of +the fixture buffer is exercised, including empty slices and interior offsets. +Null tests include the maximum usize length; the null branch must refuse +without constructing a slice or calling the backend. No invalid non-null +pointer or out-of-bounds native span is dereferenced by the test. + +Four private source mutants must compile and then fail executable assertions: +wrong slice extent, wrong null status, swapped backend-error statuses and an +extra backend invocation before null refusal. A malformed Idris span must +produce a type error. A zero-exit compiler-error control must invalidate a +planted PASS marker and finish with FAIL. Sources are snapshotted before work, +private copies are checked, and both manifests are rechecked before PASS. + +The instrumented backend tests dispatch only. The existing header bridge and +borrow tests continue to link the real exported RefC-backed library, including +every bounded interior subspan of the caller's fixture buffer. All four +caller optimisation modes are checked remotely. Writing these files is not +evidence that the gate passed; the PR and hosted artifacts record qualification. +Atoma separately binds the original public-entry/export source to its heap and +source interpretation; neither test doubles nor hashes alone prove that link. + +`scripts/test-header-export-controls.sh` additionally compiles three mutations +of the actual `main_refc.zig` exported forwarder: shortened extent, shifted +pointer with a correspondingly shortened extent, and skipped null refusal. +The real exported-ABI caller must reject each mutant with an assertion failure. +The shifted pointer remains within the valid caller allocation; no deliberately +invalid native address is dereferenced. These controls cover the export layer +that the injected core fixture cannot observe. + +== Actual-library benchmark + +`scripts/bench-header-boundary.sh LIBRARY_DIR` links the pure Zig benchmark +caller against the qualified real RefC-backed `libproven.so`. Five corpora +(empty, one byte, clean 64 bytes, forbidden byte at the end of 64 bytes and +4096 bytes) run in four caller optimisation modes. Each corpus has a correctness +check, 32 warmups and three bounded samples; timed calls retain correctness +guards. A compiled always-clean Zig export must fail the same caller's checks. + +NDJSON evidence records input SHA-256, bytes, iterations, elapsed nanoseconds, +checksum, compiler and caller mode. The environment and actual library hash are +retained separately. All caller modes use the same qualified library binary. +These are initial timing samples, not a performance-regression threshold or +proof of the foreign boundary. CI host noise and the per-call guards affect +timings. The bridge gate retains the report under `header-evidence/benchmark`. + +== Remaining premises + +For a non-null request the caller supplies a live readable allocation, a span +within that allocation and a representable machine address/range. The pointer +must correspond to the stated logical region/snapshot, and the read lease must +remain valid and immutable throughout the synchronous backend call. The backend +must not retain the input or invalidate its storage. A non-null test does not +establish any of these facts. A logical constructor cannot make stale or forged +machine addresses safe. No ABI compatibility change is introduced here. + +Atoma's backend frame premise states final region equality. It does not by +itself prohibit a write followed by restoration during the call. Continuous +immutability and no retention remain distinct foreign-call obligations. Its +thread-local error marker is an effect/presence projection, not the native +pointer identity or a message-storage layout theorem. + +Atoma's heap model tracks retained references and active read borrows; release +is permitted only when both counts are zero. Connecting that model to physical +allocations, compiler lowering, foreign calls and cross-kernel proof transport +remains explicit work. Independent hand re-proofs remain BRIDGE-PENDING. diff --git a/ffi/zig/build_standalone.zig b/ffi/zig/build_standalone.zig index 6663b8ed..1b95d509 100644 --- a/ffi/zig/build_standalone.zig +++ b/ffi/zig/build_standalone.zig @@ -86,4 +86,19 @@ pub fn build(b: *std.Build) void { const run_unit_tests = b.addRunArtifact(unit_tests); const test_step = b.step("test", "Run proven_ffi unit tests"); test_step.dependOn(&run_unit_tests.step); + + // Instrument the real public entry with a deterministic backend double. + // The existing test step above continues to qualify the actual RefC path. + const boundary_mod = b.createModule(.{ + .root_source_file = b.path("src/header_boundary_tests.zig"), + .target = target, + .optimize = optimize, + .link_libc = true, + }); + boundary_mod.addImport("lifecycle", lifecycle_mod); + const boundary_tests = b.addTest(.{ .root_module = boundary_mod }); + b.step("header-boundary-test", "Check actual header entry dispatch and span forwarding") + .dependOn(&b.addRunArtifact(boundary_tests).step); + b.step("header-boundary-build", "Compile the public-entry fixture without running it") + .dependOn(&b.addInstallArtifact(boundary_tests, .{ .dest_sub_path = "header-boundary-tests" }).step); } diff --git a/ffi/zig/src/header_boundary_tests.zig b/ffi/zig/src/header_boundary_tests.zig new file mode 100644 index 00000000..93151248 --- /dev/null +++ b/ffi/zig/src/header_boundary_tests.zig @@ -0,0 +1,104 @@ +// SPDX-License-Identifier: MPL-2.0 +// Copyright (c) 2026 Jonathan D.A. Jewell +const std = @import("std"); +const core = @import("core.zig"); + +// This double observes the actual public entry's dispatch. The separate real +// ABI fixtures still link the Idris backend; this is not a replacement for it. +const Probe = struct { + const Mode = enum { clean, found, unavailable, invalid }; + var mode: Mode = .clean; + var calls: usize = 0; + var received: ?[*]const u8 = null; + var length: usize = 0; + + fn reset(next: Mode) void { + mode = next; + calls = 0; + received = null; + length = 0; + } + + pub fn detect(bytes: []const u8) error{ BackendUnavailable, InvalidRefcResult }!bool { + calls += 1; + received = bytes.ptr; + length = bytes.len; + return switch (mode) { + .clean => false, + .found => true, + .unavailable => error.BackendUnavailable, + .invalid => error.InvalidRefcResult, + }; + } +}; + +test "header public boundary refuses null before invoking backend" { + for ([_]usize{ 0, 9, std.math.maxInt(usize) }) |len| { + Probe.reset(.found); + const result = core.headerHasCrlf(Probe, null, len); + try std.testing.expectEqual(@as(c_int, -1), result.status); + try std.testing.expectEqual(false, result.value); + try std.testing.expectEqual(@as(usize, 0), Probe.calls); + try std.testing.expectEqual(@as(?[*]const u8, null), Probe.received); + } +} + +test "header public boundary forwards every bounded subspan once and preserves storage" { + var memory = [_]u8{ 255, 0, 13, 128, 10, 7 }; + const before = memory; + for (0..memory.len + 1) |offset| { + for (offset..memory.len + 1) |end| { + const span = memory[offset..end]; + for ([_]Probe.Mode{ .clean, .found }) |mode| { + Probe.reset(mode); + const result = core.headerHasCrlf(Probe, span.ptr, span.len); + try std.testing.expectEqual(@as(c_int, 0), result.status); + try std.testing.expectEqual(mode == .found, result.value); + try std.testing.expectEqual(@as(usize, 1), Probe.calls); + try std.testing.expectEqual(@as(?[*]const u8, span.ptr), Probe.received); + try std.testing.expectEqual(span.len, Probe.length); + try std.testing.expectEqualSlices(u8, &before, &memory); + } + } + } +} + +test "header public boundary preserves error classes and rejects their Boolean" { + const memory = [_]u8{ 0, 255, 13 }; + for ([_]Probe.Mode{ .unavailable, .invalid }) |mode| { + for ([_]usize{ 0, memory.len }) |len| { + Probe.reset(mode); + const result = core.headerHasCrlf(Probe, &memory, len); + const expected: c_int = if (mode == .unavailable) -99 else -7; + try std.testing.expectEqual(expected, result.status); + try std.testing.expectEqual(false, result.value); + try std.testing.expectEqual(@as(usize, 1), Probe.calls); + try std.testing.expectEqual(len, Probe.length); + } + } +} + +// The exported C entries cannot take a backend double without linking either +// the Idris archive or the unavailable stub. Observe their forwarding instead: +// each exported entry must be exactly one delegation that passes its own +// `ptr` and `len` unchanged to the shared boundary, with no other statement. +fn entryBody(source: []const u8) error{EntryNotFound}![]const u8 { + const head = "pub export fn proven_header_has_crlf(ptr: ?[*]const u8, len: usize) callconv(.c)"; + const start = std.mem.indexOf(u8, source, head) orelse return error.EntryNotFound; + const open = std.mem.indexOfPos(u8, source, start, "{") orelse return error.EntryNotFound; + const close = std.mem.indexOfPos(u8, source, open, "\n}") orelse return error.EntryNotFound; + return std.mem.trim(u8, source[open + 1 .. close], " \n"); +} + +test "exported header entries forward ptr and len unchanged in a single delegation" { + const standalone = try entryBody(@embedFile("main.zig")); + const refc = try entryBody(@embedFile("main_refc.zig")); + try std.testing.expectEqualStrings( + "return core.headerHasCrlf(@import(\"header_unavailable.zig\"), ptr, len);", + standalone, + ); + try std.testing.expectEqualStrings( + "return core.headerHasCrlf(@import(\"header_refc.zig\"), ptr, len);", + refc, + ); +} diff --git a/scripts/bench-header-boundary.sh b/scripts/bench-header-boundary.sh new file mode 100644 index 00000000..b4620795 --- /dev/null +++ b/scripts/bench-header-boundary.sh @@ -0,0 +1,70 @@ +#!/usr/bin/env bash +# SPDX-License-Identifier: MPL-2.0 +# Copyright (c) 2026 Jonathan D.A. Jewell +set -euo pipefail +[[ $# == 1 && -f $1/libproven.so ]] +library=$(cd "$1" && pwd) +root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd) +out=${EVIDENCE_DIR:-"$root/build/header-evidence/benchmark"} +mkdir -p "$out"; out=$(cd "$out" && pwd) +echo INCOMPLETE > "$out/result.txt" +work=$(mktemp -d) +trap 'status=$?; if ((status)); then echo FAIL > "$out/result.txt"; tail -n 25 "$out"/*.txt >&2; fi; rm -rf "$work"' EXIT +zig=$(command -v "${ZIG:-zig}") +zig=$(cd "$(dirname "$zig")" && pwd)/$(basename "$zig") +idris=$(command -v "${IDRIS2:-idris2}") +idris=$(cd "$(dirname "$idris")" && pwd)/$(basename "$idris") +[[ $("$zig" version) == 0.15.2 ]] +[[ $("$idris" --version) == 'Idris 2, version 0.8.0-b6cbc25d5' ]] +sha256sum "$root/benchmarks/header_boundary.zig" "$root/scripts/bench-header-boundary.sh" \ + "$library/libproven.so" > "$out/inputs.sha256" +cp "$root/benchmarks/header_boundary.zig" "$work/header_boundary.zig" +cp "$library/libproven.so" "$work/libproven.so" +cmp "$root/benchmarks/header_boundary.zig" "$work/header_boundary.zig" +cmp "$library/libproven.so" "$work/libproven.so" +sha256sum -c "$out/inputs.sha256" > "$out/snapshot-recheck.txt" +(cd "$work"; sha256sum header_boundary.zig libproven.so) > "$out/checked-inputs.sha256" +{ + date -u '+UTC %Y-%m-%dT%H:%M:%SZ' + uname -a + "$zig" version + "$idris" --version + if command -v lscpu >/dev/null; then lscpu; fi + printf '%s\n' 'Caller modes vary; all use the same qualified library binary.' \ + 'Timings include per-call correctness guards. Samples only; no regression baseline or threshold.' +} > "$out/environment.txt" +for mode in Debug ReleaseSafe ReleaseFast ReleaseSmall; do + "$zig" build-exe "$work/header_boundary.zig" -lc -L "$work" -lproven -rpath "$work" \ + -O "$mode" -femit-bin="$work/benchmark" > "$out/build-$mode.txt" 2>&1 + timeout -k 5 60 "$work/benchmark" > "$out/$mode.jsonl" 2> "$out/run-$mode.txt" + jq -e -s --arg mode "$mode" ' + length == 15 and all(.[]; + .schema == "proven.header.benchmark/1" and .backend == "actual-exported-refc-abi" and + .mode == $mode and .zig == "0.15.2" and .correctness == "PASS" and + .timed_correctness_guards == true and .warmup_iterations == 32 and + .iterations > 0 and .elapsed_ns > 0 and (.sample >= 0 and .sample < 3) and + (.input_sha256 | test("^[0-9a-f]{64}$")) and + .checksum == (if .expected then .iterations else 0 end)) and + (group_by(.case) | length == 5 and all(.[]; length == 3 and ([.[].sample] | sort) == [0,1,2])) + ' "$out/$mode.jsonl" > "$out/validate-$mode.txt" +done +# A compiled wrong exported implementation must fail correctness before its +# timing rows can be treated as a qualified benchmark. This is a Zig fixture. +cat > "$work/always-clean.zig" <<'ZIG' +const BoolResult = extern struct { status: c_int, value: bool }; +export fn proven_header_has_crlf(_: ?[*]const u8, _: usize) callconv(.c) BoolResult { + return .{ .status = 0, .value = false }; +} +ZIG +"$zig" build-obj "$work/always-clean.zig" -O ReleaseSafe -femit-bin="$work/always-clean.o" > "$out/build-control.txt" 2>&1 +"$zig" build-exe "$work/header_boundary.zig" "$work/always-clean.o" -lc -O ReleaseSafe \ + -femit-bin="$work/wrong-benchmark" > "$out/build-control-caller.txt" 2>&1 +if timeout -k 5 60 "$work/wrong-benchmark" > "$out/reject-always-clean.txt" 2>&1; then + echo 'FAIL benchmark accepted incorrect library' >&2; exit 1 +fi +grep -q 'WrongHeaderResult' "$out/reject-always-clean.txt" +(cd "$work"; sha256sum -c "$out/checked-inputs.sha256") > "$out/checked-input-recheck.txt" +sha256sum -c "$out/inputs.sha256" > "$out/input-recheck.txt" +cp "$work/header_boundary.zig" "$out/" +echo PASS > "$out/result.txt" +echo 'HEADER BENCHMARK PASS: correctness-guarded real library samples; no performance regression baseline claimed' diff --git a/scripts/test-header-boundary-controls.sh b/scripts/test-header-boundary-controls.sh new file mode 100644 index 00000000..61a733d1 --- /dev/null +++ b/scripts/test-header-boundary-controls.sh @@ -0,0 +1,28 @@ +#!/usr/bin/env bash +# SPDX-License-Identifier: MPL-2.0 +# Copyright (c) 2026 Jonathan D.A. Jewell +set -euo pipefail +root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd) +out=${EVIDENCE_DIR:-"$root/build/header-evidence/boundary-controls"} +mkdir -p "$out"; out=$(cd "$out" && pwd) +echo INCOMPLETE > "$out/result.txt" +work=$(mktemp -d) +trap 'status=$?; if ((status)); then echo FAIL > "$out/result.txt"; fi; rm -rf "$work"' EXIT +real_idris=$(command -v "${IDRIS2:-idris2}") +real_idris=$(cd "$(dirname "$real_idris")" && pwd)/$(basename "$real_idris") +cat > "$work/diagnostic-compiler" <<'SH' +#!/usr/bin/env bash +if [[ $1 == --version ]]; then exec "$REAL_IDRIS" "$@"; fi +printf 'Error: planted zero-exit boundary compiler failure\n' +exit 0 +SH +chmod +x "$work/diagnostic-compiler" +mkdir -p "$out/refused" +echo PASS > "$out/refused/result.txt" +if REAL_IDRIS="$real_idris" IDRIS2="$work/diagnostic-compiler" EVIDENCE_DIR="$out/refused" \ + bash "$root/scripts/test-header-boundary.sh" > "$out/reject-diagnostic.txt" 2>&1; then + echo 'FAIL: zero-exit boundary compiler diagnostic accepted' >&2; exit 1 +fi +grep -q 'FAIL: boundary compiler diagnostics' "$out/reject-diagnostic.txt" +[[ $(cat "$out/refused/result.txt") == FAIL ]] +echo PASS > "$out/result.txt" diff --git a/scripts/test-header-boundary.sh b/scripts/test-header-boundary.sh new file mode 100644 index 00000000..90da6157 --- /dev/null +++ b/scripts/test-header-boundary.sh @@ -0,0 +1,75 @@ +#!/usr/bin/env bash +# SPDX-License-Identifier: MPL-2.0 +# Copyright (c) 2026 Jonathan D.A. Jewell +set -euo pipefail +root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd) +out=${EVIDENCE_DIR:-"$root/build/header-evidence/boundary"} +mkdir -p "$out"; out=$(cd "$out" && pwd) +echo INCOMPLETE > "$out/result.txt" +work=$(mktemp -d) +trap 'status=$?; if ((status)); then echo FAIL > "$out/result.txt"; tail -n 30 "$out"/*.txt >&2; fi; rm -rf "$work"' EXIT +idris=$(command -v "${IDRIS2:-idris2}") +idris=$(cd "$(dirname "$idris")" && pwd)/$(basename "$idris") +zig=$(command -v "${ZIG:-zig}") +zig=$(cd "$(dirname "$zig")" && pwd)/$(basename "$zig") +[[ $("$idris" --version) == 'Idris 2, version 0.8.0-b6cbc25d5' ]] +[[ $("$zig" version) == 0.15.2 ]] + +find "$root/ffi/zig/src" -name '*.zig' -type f -exec sha256sum {} + > "$out/inputs.sha256" +sha256sum "$root/ffi/zig/build_standalone.zig" "$root/scripts/test-header-boundary.sh" \ + "$root/src/Proven/FFI/HeaderBoundary.idr" "$root/src/Proven/FFI/HeaderBorrow.idr" \ + "$root/src/Proven/SafeHeader/ByteKernel.idr" >> "$out/inputs.sha256" +mkdir -p "$work/zig" "$work/idris/Proven/FFI" "$work/idris/Proven/SafeHeader" +cp -R "$root/ffi/zig/src" "$work/zig/" +cp "$root/ffi/zig/build_standalone.zig" "$work/zig/" +cp "$root/src/Proven/FFI/"{HeaderBoundary,HeaderBorrow}.idr "$work/idris/Proven/FFI/" +cp "$root/src/Proven/SafeHeader/ByteKernel.idr" "$work/idris/Proven/SafeHeader/" +while IFS= read -r -d '' source; do cmp "$source" "$work/zig/src/${source#"$root/ffi/zig/src/"}"; done \ + < <(find "$root/ffi/zig/src" -name '*.zig' -type f -print0) +cmp "$root/ffi/zig/build_standalone.zig" "$work/zig/build_standalone.zig" +for module in HeaderBoundary HeaderBorrow; do cmp "$root/src/Proven/FFI/$module.idr" "$work/idris/Proven/FFI/$module.idr"; done +cmp "$root/src/Proven/SafeHeader/ByteKernel.idr" "$work/idris/Proven/SafeHeader/ByteKernel.idr" +sha256sum -c "$out/inputs.sha256" > "$out/snapshot-recheck.txt" +(cd "$work"; find zig/src idris -type f \( -name '*.zig' -o -name '*.idr' \) -exec sha256sum {} +; sha256sum zig/build_standalone.zig) > "$out/checked-inputs.sha256" +(cd "$work/idris"; "$idris" --total -Werror --check Proven/FFI/HeaderBoundary.idr) > "$out/idris.txt" 2>&1 +if grep -q '^Error:' "$out/idris.txt"; then echo 'FAIL: boundary compiler diagnostics' >&2; exit 1; fi +(cd "$work/idris"; printf ':m\n:q\n' | "$idris" --no-banner Proven/FFI/HeaderBoundary.idr) > "$out/holes.txt" 2>&1 +grep -q 'No holes' "$out/holes.txt" +if grep -q '^Error:' "$out/holes.txt"; then echo 'FAIL: boundary hole-check diagnostics' >&2; exit 1; fi +cat > "$work/idris/BadSpan.idr" <<'IDRIS' +module BadSpan +import Data.Nat +import Proven.FFI.HeaderBoundary +%default total +bad : Span [] +bad = MkSpan 0 1 LTEZero +IDRIS +(cd "$work/idris"; "$idris" --total -Werror --check BadSpan.idr) > "$out/reject-span.txt" 2>&1 || true +grep -q '^Error:' "$out/reject-span.txt" +grep -q 'BadSpan' "$out/reject-span.txt" +grep -Eiq 'mismatch|constraint|LTE|unify' "$out/reject-span.txt" +for mode in Debug ReleaseSafe ReleaseFast ReleaseSmall; do + (cd "$work/zig"; "$zig" build header-boundary-test --build-file build_standalone.zig -Doptimize="$mode" --summary all) > "$out/native-$mode.txt" 2>&1 +done +cp "$work/zig/src/core.zig" "$work/original-core.zig" +for mutation in extent null_status error_class null_order; do + case "$mutation" in + extent) sed '/^pub fn headerHasCrlf/,/^}/s/header_backend.detect(p\[0\.\.len\])/header_backend.detect(p[0..len - len])/' "$work/original-core.zig" ;; + null_status) sed '/^pub fn headerHasCrlf/,/^}/s/status = PROVEN_ERR_NULL_POINTER/status = PROVEN_OK/' "$work/original-core.zig" ;; + error_class) sed '/^pub fn headerHasCrlf/,/^}/s/) -99 else -7/) -7 else -99/' "$work/original-core.zig" ;; + null_order) awk '{print} /^pub fn headerHasCrlf/ {print " if (ptr == null) _ = header_backend.detect(&.{}) catch false;"}' "$work/original-core.zig" ;; + esac > "$work/zig/src/core.zig" + if cmp -s "$work/original-core.zig" "$work/zig/src/core.zig"; then echo 'FAIL unchanged boundary mutant' >&2; exit 1; fi + (cd "$work/zig"; "$zig" build header-boundary-build --build-file build_standalone.zig -Doptimize=ReleaseSafe --prefix "$work/$mutation") > "$out/build-$mutation.txt" 2>&1 + if "$work/$mutation/bin/header-boundary-tests" > "$out/reject-$mutation.txt" 2>&1; then + echo "FAIL $mutation escaped public-boundary tests" >&2; exit 1 + fi + grep -q 'TestExpectedEqual' "$out/reject-$mutation.txt" + grep -q 'header public boundary' "$out/reject-$mutation.txt" +done +cp "$work/original-core.zig" "$work/zig/src/core.zig" +(cd "$work"; sha256sum -c "$out/checked-inputs.sha256") > "$out/checked-input-recheck.txt" +sha256sum -c "$out/inputs.sha256" > "$out/input-recheck.txt" +cp "$work/zig/src/"{core,main_refc,header_boundary_tests}.zig "$work/idris/Proven/FFI/HeaderBoundary.idr" "$out/" +echo PASS > "$out/result.txt" +echo 'HEADER BOUNDARY PASS: actual entry dispatch, exact bounded spans and rejection controls; live readable machine-span correspondence remains a premise' diff --git a/scripts/test-header-bridge.sh b/scripts/test-header-bridge.sh index cb4ab28b..035f74c5 100644 --- a/scripts/test-header-bridge.sh +++ b/scripts/test-header-bridge.sh @@ -29,6 +29,10 @@ cc -Wall -Wextra -Werror -I "$root/bindings/c/include" "$root/tests/ffi/header_b "$work/c-abi" > "$evidence/c-abi.log" 2>&1 EVIDENCE_DIR="$evidence/ownership" ZIG="$zig" bash "$root/scripts/test-header-borrow.sh" "$work/shared/lib" EVIDENCE_DIR="$evidence/ownership-controls" ZIG="$zig" bash "$root/scripts/test-header-borrow-controls.sh" "$work/shared/lib" +EVIDENCE_DIR="$evidence/boundary" ZIG="$zig" bash "$root/scripts/test-header-boundary.sh" +EVIDENCE_DIR="$evidence/boundary-controls" ZIG="$zig" bash "$root/scripts/test-header-boundary-controls.sh" +EVIDENCE_DIR="$evidence/export-controls" ZIG="$zig" bash "$root/scripts/test-header-export-controls.sh" "$work/bundle" +EVIDENCE_DIR="$evidence/benchmark" ZIG="$zig" bash "$root/scripts/bench-header-boundary.sh" "$work/shared/lib" # Every proven.h function and every library export must have a ledger row, and # the qualified library must define exactly the rows that claim presence. diff --git a/scripts/test-header-export-controls.sh b/scripts/test-header-export-controls.sh new file mode 100644 index 00000000..5447d5c5 --- /dev/null +++ b/scripts/test-header-export-controls.sh @@ -0,0 +1,49 @@ +#!/usr/bin/env bash +# SPDX-License-Identifier: MPL-2.0 +# Copyright (c) 2026 Jonathan D.A. Jewell +set -euo pipefail +[[ $# == 1 && -f $1/result.txt && $(cat "$1/result.txt") == PASS ]] +bundle=$(cd "$1" && pwd) +root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd) +out=${EVIDENCE_DIR:-"$root/build/header-evidence/export-controls"} +mkdir -p "$out"; out=$(cd "$out" && pwd) +echo INCOMPLETE > "$out/result.txt" +work=$(mktemp -d) +trap 'status=$?; if ((status)); then echo FAIL > "$out/result.txt"; tail -n 30 "$out"/*.txt >&2; fi; rm -rf "$work"' EXIT +zig=$(command -v "${ZIG:-zig}") +zig=$(cd "$(dirname "$zig")" && pwd)/$(basename "$zig") +[[ $("$zig" version) == 0.15.2 ]] +find "$root/ffi/zig/src" -name '*.zig' -type f -exec sha256sum {} + > "$out/inputs.sha256" +sha256sum "$root/ffi/zig/build_standalone.zig" "$root/tests/ffi/header_borrow.zig" \ + "$root/scripts/test-header-export-controls.sh" >> "$out/inputs.sha256" +find "$bundle" -type f -exec sha256sum {} + >> "$out/inputs.sha256" +mkdir "$work/zig" +cp -R "$root/ffi/zig/src" "$work/zig/" +cp "$root/ffi/zig/build_standalone.zig" "$work/zig/" +cp "$root/tests/ffi/header_borrow.zig" "$work/header_borrow.zig" +while IFS= read -r -d '' source; do cmp "$source" "$work/zig/src/${source#"$root/ffi/zig/src/"}"; done \ + < <(find "$root/ffi/zig/src" -name '*.zig' -type f -print0) +cmp "$root/ffi/zig/build_standalone.zig" "$work/zig/build_standalone.zig" +cmp "$root/tests/ffi/header_borrow.zig" "$work/header_borrow.zig" +sha256sum -c "$out/inputs.sha256" > "$out/snapshot-recheck.txt" +(cd "$work"; find zig/src -name '*.zig' -type f -exec sha256sum {} +; sha256sum zig/build_standalone.zig header_borrow.zig) > "$out/checked-inputs.sha256" +cp "$work/zig/src/main_refc.zig" "$work/original-main.zig" +for mutation in length pointer null_guard; do + case "$mutation" in + length) sed '/^pub export fn proven_header_has_crlf/,/^}/s/, ptr, len)/, ptr, len - len)/' "$work/original-main.zig" ;; + pointer) sed '/^pub export fn proven_header_has_crlf/,/^}/s/, ptr, len)/, if (ptr) |p| (if (len > 0) p + 1 else p) else null, if (len > 0) len - 1 else 0)/' "$work/original-main.zig" ;; + null_guard) awk '{print} /^pub export fn proven_header_has_crlf/ {print " if (ptr == null) return core.headerHasCrlf(@import(\"header_refc.zig\"), \"\".ptr, 0);"}' "$work/original-main.zig" ;; + esac > "$work/zig/src/main_refc.zig" + if cmp -s "$work/original-main.zig" "$work/zig/src/main_refc.zig"; then echo 'FAIL unchanged export mutant' >&2; exit 1; fi + (cd "$work/zig"; "$zig" build --build-file build_standalone.zig -Dshared=true -Doptimize=ReleaseSafe \ + -Dheader-refc="$bundle" --prefix "$work/$mutation") > "$out/build-$mutation.txt" 2>&1 + "$zig" test "$work/header_borrow.zig" -lc -L "$work/$mutation/lib" -lproven -rpath "$work/$mutation/lib" \ + -O ReleaseSafe --test-no-exec -femit-bin="$work/caller" > "$out/caller-$mutation.txt" 2>&1 + if "$work/caller" > "$out/reject-$mutation.txt" 2>&1; then echo "FAIL $mutation export escaped" >&2; exit 1; fi + grep -q 'TestExpectedEqual' "$out/reject-$mutation.txt" +done +cp "$work/original-main.zig" "$work/zig/src/main_refc.zig" +(cd "$work"; sha256sum -c "$out/checked-inputs.sha256") > "$out/checked-input-recheck.txt" +sha256sum -c "$out/inputs.sha256" > "$out/input-recheck.txt" +echo PASS > "$out/result.txt" +echo 'HEADER EXPORT CONTROLS PASS: compiled actual export pointer, length and null-guard mutations rejected through the real RefC-backed ABI' diff --git a/src/Proven/FFI/HeaderBoundary.idr b/src/Proven/FFI/HeaderBoundary.idr new file mode 100644 index 00000000..580542c8 --- /dev/null +++ b/src/Proven/FFI/HeaderBoundary.idr @@ -0,0 +1,103 @@ +-- SPDX-License-Identifier: MPL-2.0 +-- Copyright (c) 2026 Jonathan D.A. Jewell +module Proven.FFI.HeaderBoundary + +import Data.List +import Data.Nat +import Proven.FFI.HeaderBorrow +import Proven.SafeHeader.ByteKernel + +%default total + +||| A bounded logical snapshot. Constructing this record does not establish +||| that a raw machine pointer addresses live memory or grants a read lease. +||| Pointer correspondence, usize representability and immutable lifetime are +||| separate premises of the native call, interpreted by Atoma's heap profile. +public export +record Span (memory : List Bits8) where + constructor MkSpan + offset : Nat + count : Nat + 0 inBounds : LTE (offset + count) (length memory) + +public export +spanBytes : (memory : List Bits8) -> Span memory -> List Bits8 +spanBytes memory (MkSpan offset count _) = + Data.List.take count (Data.List.drop offset memory) + +takeBoundedLength : (count : Nat) -> (memory : List Bits8) -> + (0 bound : LTE count (length memory)) -> length (Data.List.take count memory) = count +takeBoundedLength Z memory bound = Refl +takeBoundedLength (S count) [] bound impossible +takeBoundedLength (S count) (byte :: rest) (LTESucc bound) = + cong S (takeBoundedLength count rest bound) + +sliceBoundedLength : (offset, count : Nat) -> (memory : List Bits8) -> + (0 bound : LTE (offset + count) (length memory)) -> + length (Data.List.take count (Data.List.drop offset memory)) = count +sliceBoundedLength Z count memory bound = takeBoundedLength count memory bound +sliceBoundedLength (S offset) count [] bound impossible +sliceBoundedLength (S offset) count (byte :: rest) (LTESucc bound) = + sliceBoundedLength offset count rest bound + +public export +spanLength : (memory : List Bits8) -> (span : Span memory) -> + length (spanBytes memory span) = count span +spanLength memory (MkSpan offset count bound) = + sliceBoundedLength offset count memory bound + +public export +data BackendOutcome = Detected Bool | BackendUnavailable | InvalidBackendResult + +||| Logical form of the existing public status/Boolean ABI, without claiming +||| a machine layout theorem for Integer or Bool. +public export +record BoundaryResult where + constructor MkBoundaryResult + status : Integer + value : Bool + +public export +finish : BackendOutcome -> BoundaryResult +finish (Detected value) = MkBoundaryResult 0 value +finish BackendUnavailable = MkBoundaryResult (-99) False +finish InvalidBackendResult = MkBoundaryResult (-7) False + +public export +entry : (memory : List Bits8) -> Maybe (Span memory) -> + (List Bits8 -> BackendOutcome) -> BoundaryResult +entry memory Nothing backend = MkBoundaryResult (-1) False +entry memory (Just span) backend = finish (backend (spanBytes memory span)) + +public export +nullRefuses : (memory : List Bits8) -> (backend : List Bits8 -> BackendOutcome) -> + entry memory Nothing backend = MkBoundaryResult (-1) False +nullRefuses memory backend = Refl + +public export +successPreservesBoolean : (value : Bool) -> + finish (Detected value) = MkBoundaryResult 0 value +successPreservesBoolean value = Refl + +public export +unavailableRefuses : finish BackendUnavailable = MkBoundaryResult (-99) False +unavailableRefuses = Refl + +public export +invalidRefuses : finish InvalidBackendResult = MkBoundaryResult (-7) False +invalidRefuses = Refl + +public export +checkedBackend : List Bits8 -> BackendOutcome +checkedBackend bytes = case checkedScan False bytes of + Just value => Detected value + Nothing => InvalidBackendResult + +||| Composition uses the authoritative Idris byte fold over exactly the span. +||| The source/compiler and foreign-call correspondence remain external. +public export +entryRefinesFold : (memory : List Bits8) -> (span : Span memory) -> + entry memory (Just span) Proven.FFI.HeaderBoundary.checkedBackend = + MkBoundaryResult 0 (scanTyped False (spanBytes memory span)) +entryRefinesFold memory span = + rewrite checkedScanCorrect False (spanBytes memory span) in Refl diff --git a/tests/ffi/header_borrow.zig b/tests/ffi/header_borrow.zig index 9cefaa7b..1188edbe 100644 --- a/tests/ffi/header_borrow.zig +++ b/tests/ffi/header_borrow.zig @@ -13,6 +13,18 @@ test "actual ABI borrows exact spans without modifying caller storage" { try std.testing.expectEqual(len >= 4, result.value); try std.testing.expectEqualSlices(u8, &original, &bytes); } + // Interior pointers and empty subspans cross the real exported ABI too; + // the dispatch-only fixture is not the sole evidence for pointer offsets. + for (0..bytes.len + 1) |offset| { + for (offset..bytes.len + 1) |end| { + const span = bytes[offset..end]; + const result = proven_header_has_crlf(span.ptr, span.len); + const contains_forbidden = (offset <= 3 and end > 3) or (offset <= 4 and end > 4); + try std.testing.expectEqual(@as(c_int, 0), result.status); + try std.testing.expectEqual(contains_forbidden, result.value); + try std.testing.expectEqualSlices(u8, &original, &bytes); + } + } const null_result = proven_header_has_crlf(null, 0); try std.testing.expectEqual(@as(c_int, -1), null_result.status); // Borrow is synchronous: the owner may modify and reuse storage afterwards.