From 09d269281b296b150f379e47750fbdb23746eb13 Mon Sep 17 00:00:00 2001 From: R Date: Tue, 24 Nov 2026 13:58:28 -0300 Subject: [PATCH 1/8] secure: genesis (the DIT guard, erase_secret, constant_time_equal, secret, declassify and constant-time blocks shared by crypto, hash and codecs) webcpp::secure is a new library approved by the owner on 2026-11-24: the side-channel and secret-in-memory primitives, no algorithm, depending on config alone, every name under webcpp::secure. reference/prior holds the guard of config's withdrawn change timing-guard (Windows on ARM64 included, never pushed), its tests, its shared seam and crypto's headers and tests that move. The change's files are those of the design branch's commit 375b9eb. --- README.md | 1 + .../openspec/changes/genesis/.openspec.yaml | 11 + .../secure/openspec/changes/genesis/design.md | 399 ++++++++++++++++++ .../openspec/changes/genesis/proposal.md | 114 +++++ .../changes/genesis/reference/STATUS.md | 30 ++ .../webcpp/config/detail/timing_guard.hpp | 285 +++++++++++++ .../config/test/timing_guard_nesting_test.cpp | 104 +++++ .../config/test/timing_guard_seam_test.cpp | 147 +++++++ .../prior/config/test/timing_guard_test.cpp | 121 ++++++ .../config/test/timing_guard_threads_test.cpp | 72 ++++ .../config/test/timing_guard_windows_test.cpp | 114 +++++ .../webcpp/crypto/constant_time_equal.hpp | 77 ++++ .../webcpp/crypto/detail/declassify.hpp | 48 +++ .../include/webcpp/crypto/detail/wipe.hpp | 49 +++ .../include/webcpp/crypto/erase_secret.hpp | 78 ++++ .../crypto/include/webcpp/crypto/secret.hpp | 146 +++++++ .../crypto/test/constant_time_equal_test.cpp | 68 +++ .../crypto/test/declassify_compile_test.cpp | 30 ++ .../prior/crypto/test/erase_secret_test.cpp | 156 +++++++ .../include/webcpp/test/timing_dit.hpp | 35 ++ .../include/webcpp/test/timing_seam.hpp | 115 +++++ .../changes/genesis/specs/secure/spec.md | 114 +++++ .../secure/openspec/changes/genesis/tasks.md | 42 ++ libraries/secure/openspec/config.yaml | 11 + 24 files changed, 2367 insertions(+) create mode 100644 libraries/secure/openspec/changes/genesis/.openspec.yaml create mode 100644 libraries/secure/openspec/changes/genesis/design.md create mode 100644 libraries/secure/openspec/changes/genesis/proposal.md create mode 100644 libraries/secure/openspec/changes/genesis/reference/STATUS.md create mode 100644 libraries/secure/openspec/changes/genesis/reference/prior/config/include/webcpp/config/detail/timing_guard.hpp create mode 100644 libraries/secure/openspec/changes/genesis/reference/prior/config/test/timing_guard_nesting_test.cpp create mode 100644 libraries/secure/openspec/changes/genesis/reference/prior/config/test/timing_guard_seam_test.cpp create mode 100644 libraries/secure/openspec/changes/genesis/reference/prior/config/test/timing_guard_test.cpp create mode 100644 libraries/secure/openspec/changes/genesis/reference/prior/config/test/timing_guard_threads_test.cpp create mode 100644 libraries/secure/openspec/changes/genesis/reference/prior/config/test/timing_guard_windows_test.cpp create mode 100644 libraries/secure/openspec/changes/genesis/reference/prior/crypto/include/webcpp/crypto/constant_time_equal.hpp create mode 100644 libraries/secure/openspec/changes/genesis/reference/prior/crypto/include/webcpp/crypto/detail/declassify.hpp create mode 100644 libraries/secure/openspec/changes/genesis/reference/prior/crypto/include/webcpp/crypto/detail/wipe.hpp create mode 100644 libraries/secure/openspec/changes/genesis/reference/prior/crypto/include/webcpp/crypto/erase_secret.hpp create mode 100644 libraries/secure/openspec/changes/genesis/reference/prior/crypto/include/webcpp/crypto/secret.hpp create mode 100644 libraries/secure/openspec/changes/genesis/reference/prior/crypto/test/constant_time_equal_test.cpp create mode 100644 libraries/secure/openspec/changes/genesis/reference/prior/crypto/test/declassify_compile_test.cpp create mode 100644 libraries/secure/openspec/changes/genesis/reference/prior/crypto/test/erase_secret_test.cpp create mode 100644 libraries/secure/openspec/changes/genesis/reference/prior/node-test/include/webcpp/test/timing_dit.hpp create mode 100644 libraries/secure/openspec/changes/genesis/reference/prior/node-test/include/webcpp/test/timing_seam.hpp create mode 100644 libraries/secure/openspec/changes/genesis/specs/secure/spec.md create mode 100644 libraries/secure/openspec/changes/genesis/tasks.md create mode 100644 libraries/secure/openspec/config.yaml diff --git a/README.md b/README.md index 79e63df..364e63b 100644 --- a/README.md +++ b/README.md @@ -63,6 +63,7 @@ tag is placed. | lexical | [genesis](libraries/lexical/openspec/changes/archive/2026-10-09-genesis) | lexical: the lexical forms of JSON Schema's string formats | own | implemented | 0.1.0 | 2026-10-09 | [code](https://github.com/webcpporg/lexical/tree/e286ca4) | | lexical | [strategies](libraries/lexical/openspec/changes/strategies) | lexical: one entry point, strategies and Boost.Regex | own | draft | | | | | pratt | [genesis](libraries/pratt/openspec/changes/archive/2026-10-08-genesis) | pratt: a generic Pratt parser engine for C++20, with a decimal calculator | own | implemented | 0.1.0 | 2026-10-08 | [code](https://github.com/webcpporg/pratt/tree/d78451b) | +| secure | [genesis](libraries/secure/openspec/changes/genesis) | secure: the side-channel and secret-in-memory primitives crypto, hash and codecs share (DIT guard, erase, secret, constant-time blocks), no algorithm | own | proposed | | 2026-11-24 | | | trystero | [genesis](libraries/trystero/openspec/changes/archive/2026-10-09-genesis) | trystero: serverless WebRTC rooms, wire compatible with Trystero | port of Trystero 0.26.0 | implemented | 0.1.0 | 2026-10-09 | [code](https://github.com/webcpporg/trystero/tree/160f431) | | trystero | [bounded-json-parse](libraries/trystero/openspec/changes/bounded-json-parse) | trystero: bound the text and the objects a room parses | port of Trystero 0.26.0 | draft | | | | | trystero | [shared-connection](libraries/trystero/openspec/changes/archive/2026-11-14-shared-connection) | trystero: one connection shared by the rooms of an app | port of Trystero 0.26.0 | implemented | 0.1.0 | 2026-10-11 | [code](https://github.com/webcpporg/trystero/tree/e9326e94c06cfa9ffdbd0a8d3c8d72b80b3b9b59) | diff --git a/libraries/secure/openspec/changes/genesis/.openspec.yaml b/libraries/secure/openspec/changes/genesis/.openspec.yaml new file mode 100644 index 0000000..076b19b --- /dev/null +++ b/libraries/secure/openspec/changes/genesis/.openspec.yaml @@ -0,0 +1,11 @@ +schema: spec-driven +created: 2026-11-24 +webcpp: + library: secure + title: "secure: the side-channel and secret-in-memory primitives crypto, hash and codecs share (DIT guard, erase, secret, constant-time blocks), no algorithm" + kind: own + port_of: null + status: proposed + release: null + implementation: null + decided: 2026-11-24 diff --git a/libraries/secure/openspec/changes/genesis/design.md b/libraries/secure/openspec/changes/genesis/design.md new file mode 100644 index 0000000..3793553 --- /dev/null +++ b/libraries/secure/openspec/changes/genesis/design.md @@ -0,0 +1,399 @@ +## Context + +The primitives this library gathers exist today in three places, two of them copies: + +- webcpp::crypto (`libs/crypto`, `main` at `3314a1d`): + - `include/webcpp/crypto/detail/timing.hpp`: `detail::timing_guard`, `cpu_has_dit()`, + `dit_is_set()`, `WEBCPP_CRYPTO_DETAIL_TIMING_COVERED` on arm64 under Apple's systems and Linux, + the seam `WEBCPP_CRYPTO_DETAIL_TIMING_ENTERED(where)` taking a `std::source_location`; held as + the first statement of every public function that runs a backend's code (187 sites in 26 + headers). + - `include/webcpp/crypto/detail/wipe.hpp`: `detail::wipe(void*, std::size_t)` (volatile stores, + then a signal fence) and `detail::wipe_object(T&)` for a C library's plain state. + - `include/webcpp/crypto/erase_secret.hpp`: the public `crypto::erase_secret(range)`, a + contiguous sized range of writable, trivially copyable elements; no pointer and size form. + - `include/webcpp/crypto/constant_time_equal.hpp`: the public `crypto::constant_time_equal` over + two `std::span` and over two `boost::hash2::digest`, BearSSL's + accumulate-then-reduce, under the guard. + - `include/webcpp/crypto/secret.hpp`: the public `crypto::secret` (design D9 of crypto). + - `include/webcpp/crypto/detail/declassify.hpp`: `WEBCPP_CRYPTO_DETAIL_DECLASSIFY(address, + size)`, empty in a program's build, memcheck's or MemorySanitizer's under + `WEBCPP_CRYPTO_DETAIL_CT_VALGRIND` or `WEBCPP_CRYPTO_DETAIL_CT_MSAN`, called at nine verdicts + (BearSSL's and libsodium's tag checks, the P-curves' scalar checks, X25519's all-zero check, + silent payments' label). The marking of secrets lives in the tests + (`test/constant_time/ctgrind_test.cpp`'s `memcheck` and `msan_test.cpp`'s primitives: + `mark_secret`, `mark_public`, `traced`, `verdict`). +- webcpp::hash (`libs/hash`): `include/webcpp/hash/detail/timing.hpp`, the same guard with + `WEBCPP_HASH_*` names and `timing_guard(bool engaged = true)`, a disengaged guard doing nothing, + for functions keyed only by their arguments (28 sites); and its own `detail/wipe.hpp`. +- config's change `timing-guard`, withdrawn on 2026-11-24 before any push (its branch is local: + config `ba72ad4`, hash `43b6732`, crypto `b0c1f4f`, superproject `83c9a31`). It built one guard + with hash's `engaged` flag, added Windows on ARM64, moved crypto and hash onto it, and put a + shared seam recorder (``) and DIT helper + (``) in the superproject's `tools/node-test`. Verified: clang over + config (27 tests), hash (295) and crypto (541), 0 failed; the Windows branch once on the owner's + Windows 11 ARM64 VM, MSVC 14.3 and 14.5, arm64 and x64, debug builds, `cpu_has_dit()` true and + DIT kept across a sleep. Not verified: a release build on the VM, clang-cl ARM64, a CPU without + FEAT_DIT (the probe's filter path), crypto's dudect on Windows ARM64. `reference/prior/` holds + the guard, its tests, the shared seam and crypto's headers and tests that move. +- webcpp::codecs' genesis (approved 2026-11-24) needs the guard (engaged for secret operations + only), a wipe, fixed secret storage and constant-time arithmetic on masks for hex, base32, + base64, bech32, the armor and secret base58. + +The prior art for the blocks: BoringSSL's `crypto/internal.h` (`constant_time_msb_w`, +`constant_time_is_zero_w`, `constant_time_eq_w`, `constant_time_lt_w`, `constant_time_select_w`, +`value_barrier_w`, `CONSTTIME_SECRET` and `CONSTTIME_DECLASSIFY`), libsodium's codecs +(`sodium_bin2hex`, `sodium_bin2base64`: alphabets by range masks), BearSSL's `inner.h` (`EQ`, +`NEQ`, `GT`, `MUX`, `CCOPY`). + +## Goals / Non-Goals + +**Goals:** one home for the side-channel and secret-in-memory primitives every webcpp library +shares; the guard as the withdrawn change built it, Windows on ARM64 included, public; crypto's +erase, comparison and secret type moved with their names and contracts; the declassify marker a +library may call; the constant-time blocks codecs needs, small, tested exhaustively where the +domain allows, and checked on a constant-time lane; every target webcpp builds for. + +**Non-goals:** any cryptographic algorithm (hashes, ciphers, curves stay in hash and crypto); a +wiping allocator or heap secret types (codecs' `secret_string` and `secret_byte_vector` are codecs' +own, over secure's erase); memory locking (`mlock`, `VirtualLock`) or guard pages; x86's DOITM (a +kernel setting); WebAssembly's timing (the engine decides); the migration of crypto and hash, +each a change of its own library. + +**Anti-goals:** a cryptographic algorithm in secure; a dependency on any webcpp library but config; +a name outside `webcpp::secure` or a header outside `` and ``; +an alias left in crypto or hash for a name that moved; a second copy of any primitive anywhere in +webcpp. + +## Owner decisions (2026-11-24, binding) + +1. **A new library, webcpp::secure,** the side-channel and secret-in-memory primitives shared by + crypto, hash and codecs, with no cryptographic algorithm; its own repository `webcpporg/secure`. +2. **Dependencies:** webcpp::config alone (its platform macros). config stays macros only: its + change `timing-guard` is withdrawn. +3. **Names:** the top-level `webcpp` namespace and the `` include root are for + libraries with a repository of their own, so everything is under `webcpp::secure` and + ``. +4. **The guard:** `timing_guard` (DIT on arm64: Apple's systems, Linux and Android, Windows + `_M_ARM64` through `_ReadStatusReg` and `_WriteStatusReg` with `isb`, FEAT_DIT probed once under + structured exception handling; empty elsewhere), `cpu_has_dit()`, `dit_is_set()`, the `engaged` + flag, the nesting rules and the test seam, with `WEBCPP_SECURE_*` macros; a public API of + `webcpp::secure`, not `detail`, since it is the library's purpose. +5. **Moved from crypto with their names:** `erase_secret`, `constant_time_equal` and `secret`; + crypto's go away with no alias, and a follow-up change of crypto moves its callers. +6. **The declassify and constant-time checkers' markers** crypto uses on its constant-time lane, + their public part in secure and the rest as test support. +7. **The constant-time building blocks codecs needs** (select, a table lookup by masking, + constant-time comparisons on bytes), as primitives. +8. **Test support:** secure's own seam and DIT helpers live in secure's `test/support/`; where the + helpers shared by several libraries live waits for the owner's decision on the superproject's + `tools/node-test` and its `webcpp::test` namespace (Open Questions, O1). + +## Decisions + +### D1. The library, its target and its headers + +Namespace `webcpp::secure`, with `secure::constant_time` and `secure::detail`; macros +`WEBCPP_SECURE_*`; include guards `WEBCPP_SECURE__HPP`. ``, +included first by every public header, includes `` first and defines +`WEBCPP_SECURE_NO_EXCEPTIONS` by chapter 6's rule. No function of the library throws, and every +function is `noexcept` (the guard's destructor is implicitly). + +``` +include/webcpp/secure.hpp the convenience header: every header below +include/webcpp/secure/config.hpp +include/webcpp/secure/timing_guard.hpp timing_guard, cpu_has_dit, dit_is_set (D2, D3) +include/webcpp/secure/erase_secret.hpp erase_secret (D4) +include/webcpp/secure/constant_time_equal.hpp constant_time_equal (D5) +include/webcpp/secure/secret.hpp secret (D6) +include/webcpp/secure/declassify.hpp declassify (D7) +include/webcpp/secure/constant_time.hpp constant_time:: blocks (D8) +include/webcpp/secure/detail/wipe.hpp the volatile wipe +``` + +`build.jam` declares one target, `secure`: `include`, `/boost//headers`, +`/webcpp/config//config`, nothing compiled, nothing linked (the Apple, Linux and Windows calls are +the system's C library and compiler intrinsics). `meta/libraries.json` names it with +`"port-of": null`, category "Cryptography". The library's name is none config reserves (`target`, +`has`, `no`, `lib`, `version`, `test`). + +### D2. The guard + +```cpp +namespace webcpp::secure { +[[nodiscard]] bool cpu_has_dit() noexcept; // FEAT_DIT, read once per process; false where not covered +[[nodiscard]] bool dit_is_set() noexcept; // PSTATE.DIT of this thread; false where not covered +class timing_guard { // not copyable, not movable +public: + explicit timing_guard(bool engaged = true) noexcept; // + std::source_location under the seam + ~timing_guard(); +}; +} +// WEBCPP_SECURE_TIMING_COVERED: defined where the guard acts. +// WEBCPP_SECURE_TIMING_ENTERED(where): the seam, defined by a test alone before its first include. +``` + +Behaviour, the two copies' and the withdrawn change's: an engaged guard runs the seam (in a test's +build), then sets DIT if the CPU has it and it is clear, and remembers to clear it; its destructor +clears DIT only if it set it. A disengaged guard does nothing, the seam included. So guards nest +in any order of libraries (crypto inside hash, hash inside crypto, codecs inside either): an inner +guard finds DIT set and leaves it, and a program that set DIT itself (Apple's +`timingsafe_enable_if_supported`) keeps it. DIT is a thread's state; a guard never changes another +thread's. Each write keeps its `memory` clobber (or the intrinsics' ordering on MSVC) and an `isb` +after it; which barrier each write needs (Apple asks for `sb` or `dsb nsh; isb sy` after setting) +stays crypto's open measurement and applies here when made. + +The seam: without `WEBCPP_SECURE_TIMING_ENTERED` the constructor takes no source location, so no +function name or path reaches a program. With it, the constructor's last parameter is +`std::source_location where = std::source_location::current()`, evaluated where the guard is +declared, so `function_name()` is the guarded function (crypto's, hash's, codecs' or secure's own +`constant_time_equal`) and `file_name()` tells the library (`webcpp/crypto/`, `webcpp/hash/`, +`webcpp/codecs/`, `webcpp/secure/`, either separator). + +Public because it is the library's purpose (owner decision 4): a program may hold one around its +own constant-time code. The page says what DIT covers (Arm's list of data-independent +instructions) and what it does not (memory access patterns, branches). + +Rejected: a guard in `secure::detail` (another library may not include a `detail` of secure, and +three of them need it); separate engaged and disengaged types (hash chooses at run time from its +arguments). + +### D3. Coverage by target, and FEAT_DIT on Windows + +| Target | `WEBCPP_SECURE_TIMING_COVERED` | FEAT_DIT detection | Register access | +| --- | --- | --- | --- | +| arm64, Apple's systems | yes | `sysctlbyname("hw.optional.arm.FEAT_DIT")`, once | `mrs`/`msr s3_3_c4_c2_5`, `isb` | +| arm64, Linux and Android | yes | `getauxval(AT_HWCAP) & HWCAP_DIT` (bit 24), once | as above | +| arm64, Windows (`_MSC_VER`, `_M_ARM64`, not `_M_ARM64EC`), MSVC and clang-cl | yes | the probe below | `_ReadStatusReg`, `_WriteStatusReg` of `ARM64_SYSREG(3, 3, 4, 2, 5)`, `__isb(_ARM64_BARRIER_SY)` | +| x86, x86-64, ARM64EC, WebAssembly, anything else | no | none (`false`) | none; the guard is an empty class | + +Windows documents no `IsProcessorFeaturePresent` flag for DIT and no user-mode read of +`ID_AA64PFR0_EL1`. The guard reads the DIT register once per process inside `__try` and +`__except`, in a function of its own holding no object that needs unwinding (C2712): on a CPU +without FEAT_DIT the read raises `STATUS_ILLEGAL_INSTRUCTION` (0xC000001D), which the filter takes +as absent; any other exception continues its search. The result is cached in a function-local +static. It needs `` and ``, not ``, and works with C++ exceptions on +or off. That read is the only DIT instruction executed where FEAT_DIT may be absent. Rejected: the +registry's per-processor `CP 4020` value (undocumented, needs advapi32); leaving Windows on ARM64 +uncovered. + +### D4. `erase_secret` and the wipe + +`secure::erase_secret(Range&&)` is crypto's, moved: a contiguous sized range of non-const, +trivially copyable elements, `size() * sizeof(element)` bytes zeroed from the first element (a +`std::string`'s size, not its capacity), no pointer and size form, and a refused range (const or +not trivially copyable elements) stops the build with a message naming the ranges it takes, now +spelled `webcpp::secure:`. It calls `secure::detail::wipe(void*, std::size_t)`: stores through a +volatile pointer, then `std::atomic_signal_fence(std::memory_order_seq_cst)`. + +A C library's plain state (BearSSL's contexts, which crypto wipes with `detail::wipe_object`) is +erased as a range of one: `erase_secret(std::span(&context, 1))`. Builder's call B1: no second +public name for an object, since a span of one says the same and keeps the contract one function. + +### D5. `constant_time_equal` + +`secure::constant_time_equal(first, second)` takes any two contiguous sized ranges whose elements +are one byte (`std::uint8_t`, `unsigned char`, `char`, `std::byte`), so that a `std::span`, a +`std::array`, a `secret`, a `std::string_view` and a Boost.Hash2 `digest` all work and secure +includes no Boost.Hash2 header. Sizes are public: different sizes compare unequal without reading +the contents. Otherwise every byte is read, the XOR of each pair accumulated with OR in a volatile +local, read once after the loop and reduced to one bit without a branch (BearSSL's tag check, as +crypto's). It holds an engaged guard. Builder's call B2: one generic function over crypto's two +overloads, since crypto's digest overload named Boost.Hash2. + +### D6. `secret` + +`secure::secret` is crypto's `secret`, moved with its interface: `N > 0`; zero-initialised; +move-only, the source wiped on move and the target wiped before it takes new bytes, a self-move +changing nothing; `clone()` the only copy; `bytes()` and the implicit conversion to +`std::span` on an lvalue, deleted on an rvalue so no view dangles; +`writable()` on an lvalue; `size()` and `size_bytes`; wiped on destruction through +`detail::wipe`. The page keeps crypto's warning: the wipe covers the object's own storage, not +copies a move or a `clone` leaves in registers or temporaries. + +### D7. `declassify`, and the checkers' marks as test support + +```cpp +namespace webcpp::secure { +template + requires std::is_trivially_copyable_v && (!std::is_const_v) +void declassify(T& value) noexcept; +} +// WEBCPP_SECURE_CT_VALGRIND or WEBCPP_SECURE_CT_MSAN: defined by a constant-time test build alone. +``` + +Library code calls it on a value derived from secrets that it branches on by design, right before +the branch. In a program's build it does nothing and includes nothing. Under +`WEBCPP_SECURE_CT_VALGRIND` it is `VALGRIND_MAKE_MEM_DEFINED(&value, sizeof value)` (and +`` is included); under `WEBCPP_SECURE_CT_MSAN` it is +`__msan_unpoison(&value, sizeof value)`; both at once stop the build. The value is never const, so +the branch after the mark reads it again rather than a register kept from before (BoringSSL's +practice, crypto's tip). Builder's call B3: a function template, not a macro, since it is a public +name of the library and needs no address and size from its caller. + +The other half, marking a secret (`VALGRIND_MAKE_MEM_UNDEFINED`, `__msan_poison`), reading the +checker's shadow (`VALGRIND_GET_VBITS`) and checking a verdict, only a test does: it is test +support (D9), from crypto's `memcheck` and MemorySanitizer primitives. A constant-time build of +crypto or codecs defines `WEBCPP_SECURE_CT_VALGRIND` or `WEBCPP_SECURE_CT_MSAN`, so that their +verdicts and secure's are marked alike. + +### D8. The constant-time building blocks + +``, namespace `webcpp::secure::constant_time`, every function +`constexpr` where the language allows, `noexcept`, branch-free and index-free on its data: + +```cpp +namespace webcpp::secure::constant_time { +template U value_barrier(U value) noexcept; // opaque to the optimiser +template U mask_from_bit(U bit) noexcept; // 0 or 1 -> 0 or ~0 +template U is_zero_mask(U value) noexcept; // ~0 when value == 0 +template U is_equal_mask(U first, U second) noexcept; +template U is_less_mask(U first, U second) noexcept; // unsigned +template U is_in_range_mask(U value, U low, U high) noexcept; // low <= value <= high +template U select(U mask, U when_set, U when_clear) noexcept; +template +Element lookup(std::span table, std::size_t index) noexcept; // reads every entry +void select_bytes(std::uint8_t mask, std::span destination, + std::span when_set, + std::span when_clear) noexcept; // equal sizes +std::uint8_t equal_mask(std::span first, std::span second) noexcept; +std::uint8_t is_zero_mask(std::span bytes) noexcept; +std::uint8_t less_mask(std::span first, std::span second) noexcept; // big-endian +} +``` + +- `std::unsigned_integral` excludes `bool`; a mask is all zeros or all ones of its type, never a + `bool`, so that callers combine masks without converting to a branchable value. Only + `constant_time_equal` returns a `bool`, after its reduction (D5), and a caller that must branch + on a mask calls `declassify` first. +- `value_barrier` is an empty `asm volatile` with the value in a register on GCC and clang + (BoringSSL's `value_barrier_w`) and a volatile round trip on MSVC; `mask_from_bit`, `select` and + `lookup` pass their mask through it, so the optimiser cannot turn a mask back into a branch or a + conditional move it may later turn into a branch. +- `lookup` reads every entry of the table in order and keeps the one whose index equals `index` + by `is_equal_mask` and `select`; its cost is the table's size. An index past the table yields a + value-initialised `Element` (no entry selected), so it never reads out of bounds. `Element` is + an unsigned integral type. +- The byte comparisons read every byte of both sequences; their sizes are public and must be + equal (a precondition, checked by `BOOST_ASSERT` in a debug build; unequal sizes give a zero + mask without reading). `less_mask` compares as big-endian unsigned numbers (a scalar against a + group order, a value against a bound), carrying the borrow through every byte. +- What codecs uses: `is_in_range_mask` and `select` compute an alphabet's character from a 4, 5 or + 6-bit value and back (libsodium's method), `lookup` serves base58's and bech32's alphabets and + bech32's generator, `select_bytes` and `less_mask` serve secret base58's limb arithmetic, and + the masks accumulate a decode's verdict. + +Builder's call B4: these names, BoringSSL's operations spelled out (`is_less_mask` for +`constant_time_lt_w`), in a sub-namespace so that `secure::constant_time::select` reads as what it +is. Builder's call B5: no signed variants and no `msb`; callers that need them are none today. + +### D9. Test support + +secure's tests need a seam recorder (counting guards entered, keeping the first's +`function_name()`, filtering by `file_name()`), a helper that sets DIT by hand (`force_dit`, to +test "a program that set DIT keeps it") and the checkers' marks (D7). They live in secure's own +`test/support/`: `timing_seam.hpp`, `timing_dit.hpp`, `constant_time_marks.hpp`, in namespace +`webcpp::secure::test`, ported from the withdrawn branch's `tools/node-test` headers and crypto's +lane. crypto, hash and codecs need the same three for their own guards and lanes: whether they +include secure's (making secure's `test/support/` the shared one), keep copies, or include a shared +location in the superproject depends on the owner's pending decision about `tools/node-test` +(renamed, or a library of its own). Until then secure writes only its own; the follow-up changes of +crypto, hash and codecs read the decision (O1). secure's tests keep using `tools/node-test`'s +`` as every library's do. + +### D10. Tests + +- **The guard:** `timing_guard_test` (DIT set inside, as found after; a guard that finds DIT set + leaves it set; a disengaged guard does nothing; `cpu_has_dit()` stable), + `timing_guard_nesting_test` (three levels, every order of engaged and disengaged), + `timing_guard_seam_test` (the seam's `function_name()` and `file_name()`, `timing_guard{true}`, + nothing fired by a disengaged guard, nothing named in a build without the seam), + `timing_guard_threads_test` (another thread's DIT unchanged, natively where the build has + threads), `timing_guard_windows_test` (D3, on the Windows ARM64 lane), each header compiled first + and alone; on a target not covered, `std::is_empty_v` and both functions + `false`. Ported from `reference/prior/config/test/`. +- **Moved from crypto:** `erase_secret_test` (every byte zeroed and none around, the refused ranges, + a buffer erased before its scope ends reads zero at `-O2` with full inlining), + `constant_time_equal_test` (equal, every single-byte difference, sizes, empty, a digest, a + `secret`, a `std::string_view`, the guard entered through the seam), `declassify_compile_test` + (every header compiles with `WEBCPP_SECURE_CT_VALGRIND`, and with `WEBCPP_SECURE_CT_MSAN` under + clang), and a `secret_test` from crypto's tests of `secret` (moves, self-move, clone, deleted + rvalue views, storage zero after destruction and after a move, read through placement storage). +- **The blocks:** every function against a plain reference, exhaustively over every pair (and + triple for `is_in_range_mask`) of `std::uint8_t`, at random over `std::uint16_t`, + `std::uint32_t` and `std::uint64_t` including their edges; `lookup` at every index and past the + end; the byte comparisons over random sequences and their edges; `constexpr` evaluation where + declared. +- **Allocation:** a counting `operator new` sees zero allocations in every function. +- **Constant time:** the own lane `constant-time` (`test/constant_time/`): memcheck with the + operands marked undefined (ctgrind) over every block, `constant_time_equal` and `secret`'s + moves, MemorySanitizer where crypto runs it, dudect natively with its A/A control over + `constant_time_equal`, `lookup`, `select_bytes` and `less_mask`, and a planted leak (a `select` + written with a branch, a `lookup` that indexes) that must fail on each checker. + +### D11. Lanes, documentation, measurements + +Every test runs on native (clang and gcc 15), wasip2, wasip3 and Emscripten, each with its +`_no_exceptions` twin; MSVC 14.3 and 14.5 (x64 and arm64) and Apple clang as the other libraries; +the Windows ARM64 lane on the owner's VM for the guard (D3), in a release build too, which the +withdrawn change did not run; the own lane `constant-time`; the lint. The page (`doc/`): what +secure is and is not, the guard (coverage table, nesting, engaged, the seam), erasing, `secret`, +`constant_time_equal`, `declassify`, the blocks with their limits (what DIT and masks cover and what +the compiler may still do), and the changelog. One measurement: the guard's cost on release builds +(engaged with DIT clear, engaged with DIT set, disengaged) on an idle machine, since the withdrawn +branch's figure was taken under load. + +## Builder's calls + +Settled while reading the genesis as a builder would; the plan may change them without returning +to the owner. + +- **B1:** no public erase of an object; a span of one (D4). +- **B2:** `constant_time_equal` is one function over byte ranges, naming no Boost.Hash2 type (D5). +- **B3:** `declassify` is a function template, and its switches are `WEBCPP_SECURE_CT_VALGRIND` + and `WEBCPP_SECURE_CT_MSAN` (D7). +- **B4:** the blocks' names and the sub-namespace `constant_time` (D8). +- **B5:** no signed blocks and no `msb` (D8). +- **B6:** one seam, the library told by `file_name()` (D2), as the withdrawn change's B1. +- **B7:** FEAT_DIT on Windows by an SEH-guarded read of the register (D3), as the withdrawn + change's B2. +- **B8:** the convenience header `` includes every header; none brings a heavy + dependency (D1). + +## Risks / Trade-offs + +- [hash and crypto keep their copies until their follow-up changes land] -> both changes are + ordered right after secure; until then the copies behave alike, as today, and crypto's + `timing_hash_interop_test` keeps them in step. +- [hash gains a dependency] -> secure is header-only and depends on config alone, the dependency + hash already has; hash's "depends on no other webcpp library" becomes "on config and secure", in + its follow-up. +- [The optimiser turns a mask into a branch] -> `value_barrier` on every mask a block makes, and + the constant-time lane (memcheck and MemorySanitizer see a branch on a marked value) on every + compiler that lane runs; dudect natively. +- [A Windows release changes the illegal-instruction behaviour] -> the probe fails closed (no DIT, + an empty guard's effect); the Windows lane's test fails if a CPU known to have DIT reads absent. +- [The probe's absent path is untested] -> no machine without FEAT_DIT runs Windows on ARM64 here; + the filter is small and reviewed, and the page says so. +- [`lookup` costs the table's size] -> codecs' tables are at most 64 entries; a caller with a + larger public table indexes it directly. + +## Migration Plan + +Nothing to migrate in secure: it is new. The owner creates `webcpporg/secure` and adds the +submodule; the library is built on its own branch and the superproject's (pointer, +`CODING-GUIDELINES.md` chapter 17's entry, the index page), verified on every local lane, and merged +with one CI at the end. Then, each a change of its own library: hash (its guard and wipe on +secure's, its `engaged` calls unchanged in meaning), crypto (every guard, wipe, erase, comparison, +secret and declassify on secure's; its six headers deleted with no alias; `timing_hash_interop_test` +replaced by a test that nests a guarded hash call in a guarded crypto call; dudect and benches on +`secure::cpu_has_dit()`), and codecs, built on secure from the start. The withdrawn branch's +commits are the worked example of moving every guard site. + +## Open Questions + +- **O1 (owner, pending):** where the test support shared by several libraries' tests lives: the + seam recorder, the DIT helper and the constant-time checkers' marks. secure writes its own in + `test/support/` (D9); whether crypto, hash and codecs include secure's, keep copies, or include + them from the superproject depends on the owner's decision on `tools/node-test` and its + `webcpp::test` namespace (renamed, or a library of its own). diff --git a/libraries/secure/openspec/changes/genesis/proposal.md b/libraries/secure/openspec/changes/genesis/proposal.md new file mode 100644 index 0000000..8d5a904 --- /dev/null +++ b/libraries/secure/openspec/changes/genesis/proposal.md @@ -0,0 +1,114 @@ +## Why + +Three webcpp libraries handle secrets, and each either holds its own copy of the same small +primitives or would have to reach into another library's internals to get them: + +- webcpp::crypto holds the DIT guard (`include/webcpp/crypto/detail/timing.hpp`), the volatile wipe + (`detail/wipe.hpp`), the public `crypto::erase_secret`, `crypto::constant_time_equal` and + `crypto::secret`, and the constant-time lane's declassify marker (`detail/declassify.hpp`). +- webcpp::hash holds a second copy of the guard (`include/webcpp/hash/detail/timing.hpp`, with an + `engaged` flag) and a second wipe (`detail/wipe.hpp`), because it depends on no other webcpp + library and crypto's `detail` is not its to include; a test of crypto keeps the two guards in step. +- webcpp::codecs, whose genesis the owner approved on 2026-11-24, needs the guard, a wipe, a secret + type and constant-time selection and lookup for its secret encodings, and would have made a third + copy of each. + +config's change `timing-guard` (2026-11-24) moved the guard alone into webcpp::config. It was built +and verified natively, the Windows on ARM64 branch once on the owner's Windows 11 ARM64 VM, then +withdrawn before any push: on 2026-11-24 the owner decided instead that these primitives are a +library of their own, webcpp::secure, and that config stays macros only. + +## What Changes + +- **New library `webcpp::secure`**, of webcpp's own design, header-only C++20, + `/webcpp/secure//secure`, repository `webcpporg/secure` (the owner creates it), submodule + `libs/secure`, BSL-1.0. It holds no cryptographic algorithm: only the side-channel and + secret-in-memory primitives that crypto, hash and codecs share. It depends on Boost's headers and + `/webcpp/config//config` (the platform macros) alone. Every name is in `webcpp::secure` and every + header under `` (the owner's rule: the top-level namespace and include root are + for libraries with a repository of their own). +- **``**, public, since it is the library's purpose: + `secure::timing_guard` (RAII, `explicit timing_guard(bool engaged = true)`, not copyable or + movable), `secure::cpu_has_dit()`, `secure::dit_is_set()`, the macro + `WEBCPP_SECURE_TIMING_COVERED` where the guard acts, and the test seam + `WEBCPP_SECURE_TIMING_ENTERED(where)`. It sets arm64's DIT for its scope when the CPU has FEAT_DIT + and DIT is clear, and clears it on exit only when it set it, so guards nest across libraries and + a program that set DIT keeps it. Covered: arm64 under Apple's systems, Linux and Android, and + Windows (`_M_ARM64`, not ARM64EC, through `_ReadStatusReg`, `_WriteStatusReg` and `__isb`, with + FEAT_DIT probed once under structured exception handling); an empty class elsewhere. +- **``**: `secure::erase_secret(range)`, moved from crypto with its + name and contract, over secure's volatile wipe. +- **``**: `secure::constant_time_equal(first, second)`, + moved from crypto with its name, now over any two contiguous ranges of bytes (a span, an array, a + `secret`, a Boost.Hash2 digest) so that secure names no Boost.Hash2 type; it holds the guard. +- **``**: `secure::secret`, moved from crypto unchanged in behaviour: + `N` owned bytes, wiped on destruction and on move, copied only by `clone()`, viewed through + `bytes()`, `writable()` and an lvalue's implicit span. +- **``**: `secure::declassify(object)`, the marker library code + calls on a value derived from secrets that it branches on by design (a tag's verdict): nothing in + a program's build, memcheck's `VALGRIND_MAKE_MEM_DEFINED` when a constant-time test build defines + `WEBCPP_SECURE_CT_VALGRIND`, MemorySanitizer's `__msan_unpoison` under `WEBCPP_SECURE_CT_MSAN`. + The marking of secrets and the reading of the checkers' shadow, which only tests do, are test + support, not public. +- **``**, namespace `secure::constant_time`: the building blocks + codecs needs, as primitives: `value_barrier`, masks from a bit and from comparisons of unsigned + values (`mask_from_bit`, `is_zero_mask`, `is_equal_mask`, `is_less_mask`, + `is_in_range_mask`), `select` by mask, `select_bytes` (a conditional copy), `lookup` (a table + read whole, the entry chosen by masks), and comparisons of byte sequences returning masks + (`equal_mask`, `is_zero_mask` of bytes, `less_mask`, big-endian). +- **``**, the convenience header, and ``. +- **Tests**: the guard's (`timing_guard_test`, `_nesting_`, `_seam_`, `_threads_`, `_windows_`, + header-alone), crypto's `erase_secret_test`, `constant_time_equal_test` and + `declassify_compile_test` moved, `secret_test`, the constant-time blocks against a plain + reference (every 8-bit pair, random wider ones), the allocation test, and the own lane + `constant-time` (memcheck, MemorySanitizer, dudect, each with a planted leak that must fail). The + seam recorder and the DIT helper live in secure's own `test/support/`; where the helpers shared by + several libraries' tests live is open, pending the owner's decision on the superproject's + `tools/node-test` (design, Open Questions). +- **Documentation**: the library's page, the guard's coverage table, how to erase, the secret type, + the constant-time blocks with their limits, and the changelog. + +Not in this change, and stated as its consumers: webcpp::crypto's change that moves every caller to +secure and deletes `crypto::erase_secret`, `crypto::constant_time_equal`, `crypto::secret`, +`detail/timing.hpp`, `detail/wipe.hpp` and `detail/declassify.hpp` with no alias; webcpp::hash's +change that moves its guard and wipe to secure (hash then depends on secure); webcpp::codecs' genesis +uses secure from its first line (amended the same day). + +## Capabilities + +### New Capabilities + +- `secure`: webcpp::secure, the DIT timing guard, `erase_secret`, `constant_time_equal`, + `secret`, the declassify marker, the constant-time building blocks, with their build, tests, + lanes and documentation. + +### Modified Capabilities + +None. + +## Impact + +- **Kind:** own (`"port-of": null`): webcpp's own design, moved from webcpp::crypto and + webcpp::hash and from config's withdrawn change `timing-guard`; the constant-time blocks follow + BoringSSL's `constant_time_*` and libsodium's arithmetic. Repository `webcpporg/secure` (not + created; the owner creates it), checked out as the submodule `libs/secure`, BSL-1.0, "Copyright + (c) 2026 WebCpp.org". +- **Implementation:** nothing is built in secure's name. The prior code is in `reference/prior/`: + the guard as config's withdrawn branch built it (Windows on ARM64 included) with its tests, the + shared seam of that branch, and crypto's headers and tests that move. To build: the library's + repository, `build.jam`, `include/webcpp/secure.hpp`, `include/webcpp/secure/*.hpp`, tests, the + constant-time lane, `doc/`, the superproject's pointer, `CODING-GUIDELINES.md` chapter 17's entry + and the index page. +- **Dependencies:** Boost 1.92's headers (Core's `lightweight_test` in tests) and + `/webcpp/config//config`. For the constant-time lane: valgrind, MemorySanitizer and dudect as + webcpp::crypto's lane uses them. secure depends on no other webcpp library; hash, crypto and + codecs depend on it. +- **Status:** approved by the owner on 2026-11-24 (`decided`); it stays `proposed` in the + metadata until `reference/plan.md` carries the plan's code, which `tools/proposals.py` requires + of an `accepted` proposal, and then becomes `accepted`. +- **Other proposals:** replaces `libraries/config`'s change `timing-guard`, withdrawn the same day + (archived as `2026-11-24-timing-guard`). `libraries/codecs`'s genesis uses secure's guard, erase, + secret and constant-time blocks (its owner decision 14). Follow-up changes, none of them part of + this genesis, after secure: `libraries/hash` (its guard and wipe on secure's) and + `libraries/crypto` (every caller on secure's names, its copies deleted with no alias, its + `data-independent-timing` requirements read with secure's guard and seam). diff --git a/libraries/secure/openspec/changes/genesis/reference/STATUS.md b/libraries/secure/openspec/changes/genesis/reference/STATUS.md new file mode 100644 index 0000000..4360b20 --- /dev/null +++ b/libraries/secure/openspec/changes/genesis/reference/STATUS.md @@ -0,0 +1,30 @@ +# webcpp::secure: where the implementation stands, and what to start from + +Written 2026-11-24, with the genesis. Nothing is built in secure's name: there is no repository +`webcpporg/secure` yet (the owner creates it). `prior/` holds the code an implementer ports, exact +copies of files committed elsewhere, none of them renamed yet: + +| `prior/` | Copied from | What it is | +| --- | --- | --- | +| `config/include/webcpp/config/detail/timing_guard.hpp` | webcpporg/config, branch `config/timing-guard` at `ba72ad4` (local, never pushed) | The guard of config's withdrawn change `timing-guard`: crypto's guard with hash's `engaged` flag, the one seam, Windows on ARM64 (`_ReadStatusReg`, `_WriteStatusReg`, `__isb`, the SEH probe). Named `webcpp::config::detail` and `WEBCPP_CONFIG_DETAIL_*`; becomes `webcpp::secure` and `WEBCPP_SECURE_*` (design D2, D3). | +| `config/test/timing_guard_*_test.cpp` | the same commit | Its tests: plain, nesting, seam, threads, Windows. | +| `node-test/include/webcpp/test/timing_seam.hpp`, `timing_dit.hpp` | the superproject webcpporg/webcpp, branch `config/timing-guard` at `83c9a31` (local) | The seam recorder and the DIT helper that branch shared in `tools/node-test`. secure ports them into its own `test/support/` (design D9); the shared place is open (O1). | +| `crypto/include/webcpp/crypto/{erase_secret,constant_time_equal,secret}.hpp`, `detail/{wipe,declassify}.hpp` | webcpporg/crypto `main` at `3314a1d` | The public names that move to secure with no alias (design D4 to D7). | +| `crypto/test/{erase_secret,constant_time_equal,declassify_compile}_test.cpp` | the same commit | Their tests, which move with them. | + +## The withdrawn change's verification, which the port inherits + +- Natively (clang, this Mac): config 27 tests, hash 295, crypto 541 passed, 0 failed, with every + guard site of hash (28) and crypto (187 in 26 headers) moved onto the shared guard. +- The Windows on ARM64 branch, once, on the owner's Windows 11 ARM64 VM: MSVC 14.3 and 14.5, arm64 + and x64, debug builds; config's tests and example passed with 0 known and 0 new failures on each + of the four lanes; on arm64 `cpu_has_dit()` was true and DIT stayed set across sleeps inside a + guard. +- Not run: a release build on the VM, clang-cl ARM64, a CPU without FEAT_DIT (the probe's filter + path), crypto's dudect on Windows ARM64, gcc 15, WASI, Emscripten and the constant-time lane for + the last tasks of that branch. Its measurement of the guard's cost was taken under load and is + not reused (design D11). + +The withdrawn branch's commits (config `ba72ad4`, hash `43b6732`, crypto `b0c1f4f`, superproject +`83c9a31`) are a worked example of moving every guard site of hash and crypto by a rename, for +their follow-up changes. diff --git a/libraries/secure/openspec/changes/genesis/reference/prior/config/include/webcpp/config/detail/timing_guard.hpp b/libraries/secure/openspec/changes/genesis/reference/prior/config/include/webcpp/config/detail/timing_guard.hpp new file mode 100644 index 0000000..cccb996 --- /dev/null +++ b/libraries/secure/openspec/changes/genesis/reference/prior/config/include/webcpp/config/detail/timing_guard.hpp @@ -0,0 +1,285 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +#ifndef WEBCPP_CONFIG_DETAIL_TIMING_GUARD_HPP +#define WEBCPP_CONFIG_DETAIL_TIMING_GUARD_HPP + +#include + +/* + * timing_guard sets 64-bit ARM's DIT (Data Independent Timing) bit, PSTATE.DIT, for the scope of + * one secret computation and restores the thread's state after it. With DIT set, the instructions + * Arm lists take a time independent of their data; Apple requires it of constant-time code on + * Apple silicon, and none of the C libraries webcpp calls sets it. It is the one guard of webcpp's + * libraries: every function of crypto, hash or codecs that computes on a secret holds one as its + * first statement, and none keeps a copy. It is config's internal header, named as every + * library's internals are, which every webcpp library may include and a program's interface never + * names; does not include it. + * + * Some functions are keyed only by their arguments (a BLAKE2b digest of a call that passes a key), + * and an unkeyed call computes on public data and must not pay for DIT: such a function constructs + * the guard with `engaged` false when the call is not keyed. A disengaged guard sets nothing, + * clears nothing and runs no seam, on every target. + * + * The guard applies on arm64 under macOS, iOS, Linux and Android, where the system says whether + * the CPU has FEAT_DIT, and on Windows on ARM64 built by MSVC or clang-cl, where one read of the + * register under structured exception handling says it (probe_dit, below). Everywhere else (x86, + * ARM64EC, WebAssembly, where the engine decides) it is an empty class that executes no + * instruction. + */ +#if defined(__aarch64__) && (defined(__APPLE__) || defined(__linux__)) +/** Defined where timing_guard sets DIT: arm64 under an Apple system or Linux, Android included. */ +#define WEBCPP_CONFIG_DETAIL_TIMING_COVERED 1 +#include +#include +#ifdef __APPLE__ +#include +#else +#include +#endif +#elif defined(_MSC_VER) && defined(_M_ARM64) && !defined(_M_ARM64EC) +/** Defined where timing_guard sets DIT: Windows on ARM64, MSVC and clang-cl, not ARM64EC. */ +#define WEBCPP_CONFIG_DETAIL_TIMING_COVERED 1 +#include +#include +#include +#include +#endif + +/* + * WEBCPP_CONFIG_DETAIL_TIMING_ENTERED(where), the seam, is defined by a test alone, before its + * first include, to record the guards a call enters, so that a guarded function that forgets its + * guard fails on every lane, also where DIT does not apply and also when it calls another guarded + * function. Then timing_guard's constructor takes the std::source_location of the guard's + * declaration, whose function_name() is the function that holds it and whose file_name() tells + * which library declares it (webcpp/crypto/, webcpp/hash/, webcpp/codecs/), and runs the seam with + * it first, on every target, when the guard is engaged. Nothing in a program's build: without the + * seam the constructor takes no location, so that no function's name or header's path reaches a + * program, whether the constructor is inlined or not. + */ +#ifdef WEBCPP_CONFIG_DETAIL_TIMING_ENTERED +#include +#endif + +namespace webcpp::config::detail { + +#ifdef WEBCPP_CONFIG_DETAIL_TIMING_COVERED +/** DIT's bit in the value of the register s3_3_c4_c2_5, bit 24 as in PSTATE. */ +inline constexpr std::uint64_t dit_bit = std::uint64_t{1} << 24U; + +#ifdef _MSC_VER +/** DIT's register for `_ReadStatusReg` and `_WriteStatusReg`: `ARM64_SYSREG(3, 3, 4, 2, 5)`. */ +inline constexpr int dit_register = (1 << 14) | (3 << 11) | (4 << 7) | (2 << 3) | 5; +#ifdef ARM64_SYSREG +static_assert(dit_register == ARM64_SYSREG(3, 3, 4, 2, 5), "dit_register is DIT's encoding"); +#endif + +/** The full-system option of `isb`, `_ARM64_BARRIER_SY`. */ +inline constexpr unsigned int isb_full_system = 0xFU; +#ifdef _ARM64_BARRIER_SY +static_assert(isb_full_system == _ARM64_BARRIER_SY, "isb_full_system is isb sy"); +#endif + +/** The code of the exception an undefined instruction raises, `STATUS_ILLEGAL_INSTRUCTION`. */ +inline constexpr unsigned long status_illegal_instruction = 0xC000001DUL; +#endif + +/** + * Writes the DIT register, then executes `isb`. + * + * The register is named by its encoding (op0 3, op1 3, CRn 4, CRm 2, op2 5), which every + * assembler takes, with or without an architecture flag. Apple's "Writing ARM64 code for Apple + * platforms" ("Enable DIT for constant-time cryptographic operations") asks for a speculation + * barrier after turning DIT on, so that the timing of the instructions after it reflects the new + * state: `sb` where the CPU has FEAT_SB, else `dsb nsh` then `isb sy`; it asks for none after + * turning DIT off. The `isb` here, after both writes, is not that barrier: which barrier each + * write needs is the open measurement of crypto's change data-independent-timing. + * + * MSVC takes no inline assembly on ARM64, and clang-cl takes the same intrinsics, so that one + * spelling serves both: `_WriteStatusReg` writes the register and `__isb` executes `isb sy`, + * between two `std::atomic_signal_fence(seq_cst)`, which stand for the asm's `memory` clobber. + * + * @param dit_value `dit_bit` to set DIT, 0 to clear it. + */ +inline void write_dit(std::uint64_t dit_value) noexcept { +#ifdef _MSC_VER + std::atomic_signal_fence(std::memory_order_seq_cst); + _WriteStatusReg(dit_register, static_cast<__int64>(dit_value)); + __isb(isb_full_system); + std::atomic_signal_fence(std::memory_order_seq_cst); +#else + __asm__ volatile("msr s3_3_c4_c2_5, %0\n\tisb" : : "r"(dit_value) : "memory"); +#endif +} + +#ifdef _MSC_VER +/** + * Whether the CPU has FEAT_DIT, by reading the DIT register once under structured exception + * handling: Windows documents no processor feature flag for DIT and no user-mode read of + * ID_AA64PFR0_EL1, and on a CPU without FEAT_DIT the read is undefined and raises + * STATUS_ILLEGAL_INSTRUCTION, which the filter takes as "absent"; any other exception continues + * its search. A function of its own holding no object that needs unwinding, which `__try` refuses + * beside one (C2712); structured exception handling is not C++'s, so it works with exceptions on + * or off. The value read is kept in a volatile, so that the read is never dropped. + * + * @return Whether the read succeeded. + */ +inline bool probe_dit() noexcept { + __try { + std::uint64_t volatile const state = + static_cast(_ReadStatusReg(dit_register)); + static_cast(state); + return true; + } __except (GetExceptionCode() == status_illegal_instruction ? EXCEPTION_EXECUTE_HANDLER + : EXCEPTION_CONTINUE_SEARCH) { + return false; + } +} +#endif +#endif + +/** + * Whether the CPU has DIT, read once per process. + * + * `hw.optional.arm.FEAT_DIT` on Apple's systems, where a value that cannot be read counts as + * absent; on Windows, probe_dit's one read of the register under structured exception handling, + * an illegal instruction meaning absent; `HWCAP_DIT` (bit 24 of `AT_HWCAP`) on Linux. Executing + * DIT's instructions on a CPU without it traps, so nothing else reads or writes the register + * unless this is true. + * + * @return Whether the CPU has FEAT_DIT; `false` on every target the guard does not cover. + */ +[[nodiscard]] inline bool cpu_has_dit() noexcept { +#if defined(WEBCPP_CONFIG_DETAIL_TIMING_COVERED) && defined(__APPLE__) + static bool const has_dit = [] { + int dit_feature = 0; + std::size_t byte_count = sizeof dit_feature; + return sysctlbyname("hw.optional.arm.FEAT_DIT", &dit_feature, &byte_count, nullptr, 0) == + 0 && + dit_feature != 0; + }(); + return has_dit; +#elif defined(WEBCPP_CONFIG_DETAIL_TIMING_COVERED) && defined(_MSC_VER) + static bool const has_dit = probe_dit(); + return has_dit; +#elif defined(WEBCPP_CONFIG_DETAIL_TIMING_COVERED) + constexpr unsigned long hwcap_dit = 1UL << 24U; // HWCAP_DIT, asm/hwcap.h + static bool const has_dit = (getauxval(AT_HWCAP) & hwcap_dit) != 0; + return has_dit; +#else + return false; +#endif +} + +/** + * Whether DIT is set for the calling thread. + * + * @return PSTATE.DIT, read with `mrs` (`_ReadStatusReg` on MSVC and clang-cl), where the CPU has + * DIT on a target the guard covers; `false` elsewhere, without executing `mrs`. + */ +[[nodiscard]] inline bool dit_is_set() noexcept { +#ifdef WEBCPP_CONFIG_DETAIL_TIMING_COVERED + if (!cpu_has_dit()) { + return false; + } +#ifdef _MSC_VER + std::uint64_t const saved_state = static_cast(_ReadStatusReg(dit_register)); +#else + std::uint64_t saved_state = 0; + __asm__ volatile("mrs %0, s3_3_c4_c2_5" : "=r"(saved_state) : : "memory"); +#endif + return (saved_state & dit_bit) != 0; +#else + return false; +#endif +} + +/** + * Sets DIT for its scope where the CPU has it, and leaves the thread's DIT as it found it. + * + * Construction, when engaged, finds DIT clear, sets it and remembers to clear it; the destructor + * clears it then only. A guard that finds DIT set does nothing and leaves it set: the program set + * it itself (as Apple's `timingsafe_enable_if_supported` does), or an outer guard did, of the same + * library or of another, so that guards nest in any order of libraries and a thread whose program + * asked for DIT keeps it after every call. DIT is a thread's own state, so a guard never changes + * another thread's. The writes' `memory` clobber orders them against memory accesses and calls + * (the backends' out-of-line C calls, a volatile accumulator), not against arithmetic on + * registers alone, which the compiler may move across them: the same limit as every program that + * sets DIT. + */ +class timing_guard { +public: +#ifdef WEBCPP_CONFIG_DETAIL_TIMING_ENTERED + /** + * Where `engaged`, runs the seam, then sets DIT where the CPU has it and it is clear: a test's + * build alone. + * + * @param engaged Whether the call computes on a secret; false makes the guard do nothing, the + * seam included. + * @param where Where the guard is declared, the default: the seam's argument alone. + */ + explicit timing_guard(bool engaged = true, + std::source_location where = std::source_location::current()) noexcept { + if (!engaged) { + return; + } + WEBCPP_CONFIG_DETAIL_TIMING_ENTERED(where); + enter(); + } +#else + /** + * Where `engaged`, sets DIT where the CPU has it and it is clear. + * + * @param engaged Whether the call computes on a secret; false makes the guard do nothing. + */ + explicit timing_guard(bool engaged = true) noexcept { + if (engaged) { + enter(); + } + } +#endif + + /** Clears DIT when this guard set it. */ + ~timing_guard() { +#ifdef WEBCPP_CONFIG_DETAIL_TIMING_COVERED + if (armed_) { + write_dit(0); + } +#endif + } + + /** Not copyable: the state it restores is the scope's. */ + timing_guard(timing_guard const&) = delete; + + /** Not assignable. */ + timing_guard& operator=(timing_guard const&) = delete; + + /** Not movable: the state it restores is the scope's. */ + timing_guard(timing_guard&&) = delete; + + /** Not move-assignable. */ + timing_guard& operator=(timing_guard&&) = delete; + +private: + /** Sets DIT where the CPU has it and it is clear, and remembers to clear it. */ + void enter() noexcept { +#ifdef WEBCPP_CONFIG_DETAIL_TIMING_COVERED + if (cpu_has_dit() && !dit_is_set()) { + write_dit(dit_bit); + armed_ = true; + } +#endif + } + +#ifdef WEBCPP_CONFIG_DETAIL_TIMING_COVERED + /** Whether this guard set DIT, and so clears it. */ + bool armed_ = false; +#endif +}; + +} // namespace webcpp::config::detail + +#endif // WEBCPP_CONFIG_DETAIL_TIMING_GUARD_HPP diff --git a/libraries/secure/openspec/changes/genesis/reference/prior/config/test/timing_guard_nesting_test.cpp b/libraries/secure/openspec/changes/genesis/reference/prior/config/test/timing_guard_nesting_test.cpp new file mode 100644 index 0000000..6e4995a --- /dev/null +++ b/libraries/secure/openspec/changes/genesis/reference/prior/config/test/timing_guard_nesting_test.cpp @@ -0,0 +1,104 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// Guards nest, as one library's guarded function calls another's (crypto inside hash, hash inside +// crypto, codecs inside either): the guard is one class, so the nesting is the class with itself. +// Three levels in every order of engaged and disengaged guards, from DIT clear and from DIT set: +// inside each level DIT is set when it was set before or when any guard at or above that level is +// engaged (on a CPU with DIT); after each level it is as inside the level above; after the +// outermost, as before. Then the spec's scenario: three engaged guards with a disengaged one +// between them. + +#include +#include +#include + +#include + +namespace { + +using webcpp::config::detail::cpu_has_dit; +using webcpp::config::detail::dit_is_set; +using webcpp::config::detail::timing_guard; +using webcpp::test::force_dit; + +/** + * Three guards nested, engaged as `pattern`'s bits say (bit 0 the outermost, bit 2 the innermost), + * from DIT set or clear. + */ +void nest(unsigned pattern, bool initially_set) { + force_dit(initially_set); + bool const offered = cpu_has_dit(); + bool const before = initially_set && offered; + bool const outer_engaged = (pattern & 1U) != 0; + bool const middle_engaged = (pattern & 2U) != 0; + bool const inner_engaged = (pattern & 4U) != 0; + auto const expected = [before, offered](bool any_engaged) { + return before || (offered && any_engaged); + }; + BOOST_TEST_EQ(dit_is_set(), before); + { + timing_guard const outer{outer_engaged}; + BOOST_TEST_EQ(dit_is_set(), expected(outer_engaged)); + { + timing_guard const middle{middle_engaged}; + BOOST_TEST_EQ(dit_is_set(), expected(outer_engaged || middle_engaged)); + { + timing_guard const inner{inner_engaged}; + BOOST_TEST_EQ(dit_is_set(), + expected(outer_engaged || middle_engaged || inner_engaged)); + } + BOOST_TEST_EQ(dit_is_set(), expected(outer_engaged || middle_engaged)); + } + BOOST_TEST_EQ(dit_is_set(), expected(outer_engaged)); + } + BOOST_TEST_EQ(dit_is_set(), before); + force_dit(false); +} + +// Every order of engaged and disengaged guards over three levels, from clear and from set. +void every_order() { + for (unsigned pattern = 0; pattern < 8; ++pattern) { + nest(pattern, false); + nest(pattern, true); + } +} + +// The spec's scenario: codecs' guard, a disengaged one (an unkeyed hash call), hash's, crypto's, +// from clear on a CPU with DIT: set inside every level, still set after each inner guard ends, +// clear after the outermost. +void three_libraries_with_a_disengaged_guard_between() { + force_dit(false); + bool const offered = cpu_has_dit(); + { + timing_guard const codecs; + BOOST_TEST_EQ(dit_is_set(), offered); + { + timing_guard const unkeyed{false}; + BOOST_TEST_EQ(dit_is_set(), offered); + { + timing_guard const hash; + BOOST_TEST_EQ(dit_is_set(), offered); + { + timing_guard const crypto; + BOOST_TEST_EQ(dit_is_set(), offered); + } + BOOST_TEST_EQ(dit_is_set(), offered); + } + BOOST_TEST_EQ(dit_is_set(), offered); + } + BOOST_TEST_EQ(dit_is_set(), offered); + } + BOOST_TEST(!dit_is_set()); +} + +} // namespace + +int main() { + every_order(); + three_libraries_with_a_disengaged_guard_between(); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/libraries/secure/openspec/changes/genesis/reference/prior/config/test/timing_guard_seam_test.cpp b/libraries/secure/openspec/changes/genesis/reference/prior/config/test/timing_guard_seam_test.cpp new file mode 100644 index 0000000..9639ff4 --- /dev/null +++ b/libraries/secure/openspec/changes/genesis/reference/prior/config/test/timing_guard_seam_test.cpp @@ -0,0 +1,147 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// The seam of webcpp::config::detail::timing_guard, WEBCPP_CONFIG_DETAIL_TIMING_ENTERED, defined +// here before the first include as a library's test defines it: every engaged guard runs it once, +// with the std::source_location of the guard's declaration, before DIT is touched, on every target; +// a disengaged guard never runs it. The location's function_name() names the function that holds +// the guard and its file_name() the file that declares it, which is how a library's coverage test +// tells its own guards from another library's. Without the seam the constructor takes no +// location: timing_guard_test checks that. + +#include +#include + +namespace webcpp::test { +namespace { + +/** Records one engaged guard's entry; defined below, once the guard's header is included. */ +void timing_entered(std::source_location const& where) noexcept; + +} // namespace +} // namespace webcpp::test + +/** The seam: records the entry into a guard declared at `where`. */ +#define WEBCPP_CONFIG_DETAIL_TIMING_ENTERED(where) (::webcpp::test::timing_entered(where)) + +#include +#include +#include + +#include + +#include +#include + +namespace webcpp::test { +namespace { + +/** The seam's runs on this thread. */ +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables): the seam's record +thread_local std::size_t entries = 0; + +/** Where the last guard the seam saw is declared. */ +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables): the seam's record +thread_local std::source_location last_entry{}; + +/** Whether DIT was set when the seam last ran. */ +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables): the seam's record +thread_local bool dit_at_seam = false; + +void timing_entered(std::source_location const& where) noexcept { + ++entries; + last_entry = where; + dit_at_seam = webcpp::config::detail::dit_is_set(); +} + +} // namespace +} // namespace webcpp::test + +namespace { + +using webcpp::config::detail::cpu_has_dit; +using webcpp::config::detail::dit_is_set; +using webcpp::config::detail::timing_guard; +using webcpp::test::force_dit; + +static_assert(std::is_nothrow_constructible_v, + "with the seam, the constructor takes the guard's location after engaged"); + +namespace seam_probe { + +/** Holds an engaged guard, as a library's guarded function does. */ +void guarded_function() { + timing_guard const guard; +} + +/** Holds a guard engaged explicitly, as a function keyed by its arguments does for a keyed call. */ +void engaged_function() { + timing_guard const guard{true}; +} + +/** Holds a disengaged guard, as a function keyed by its arguments does for an unkeyed call. */ +void disengaged_function() { + timing_guard const guard{false}; +} + +} // namespace seam_probe + +// An engaged guard, made either way, runs the seam exactly once, at its construction. +void engaged_guard_runs_the_seam_once() { + std::size_t const before = webcpp::test::entries; + { + timing_guard const guard; + BOOST_TEST_EQ(webcpp::test::entries, before + 1); + } + BOOST_TEST_EQ(webcpp::test::entries, before + 1); + { + timing_guard const guard{true}; + } + BOOST_TEST_EQ(webcpp::test::entries, before + 2); +} + +// A disengaged guard runs no seam. +void disengaged_guard_runs_no_seam() { + std::size_t const before = webcpp::test::entries; + seam_probe::disengaged_function(); + BOOST_TEST_EQ(webcpp::test::entries, before); +} + +// The seam's location names the function that holds the guard, and the file that declares it, +// for a guard made either way: timing_guard{} and timing_guard{true}. +void seam_names_function_and_file() { + seam_probe::guarded_function(); + std::string_view function = webcpp::test::last_entry.function_name(); + std::string_view file = webcpp::test::last_entry.file_name(); + BOOST_TEST(function.find("seam_probe::guarded_function") != std::string_view::npos); + BOOST_TEST(file.ends_with("timing_guard_seam_test.cpp")); + seam_probe::engaged_function(); + function = webcpp::test::last_entry.function_name(); + file = webcpp::test::last_entry.file_name(); + BOOST_TEST(function.find("seam_probe::engaged_function") != std::string_view::npos); + BOOST_TEST(file.ends_with("timing_guard_seam_test.cpp")); +} + +// The seam runs before DIT is touched: from clear, it finds DIT clear; then the guard sets it. +void seam_runs_before_dit() { + force_dit(false); + { + timing_guard const guard; + BOOST_TEST(!webcpp::test::dit_at_seam); + BOOST_TEST_EQ(dit_is_set(), cpu_has_dit()); + } + BOOST_TEST(!dit_is_set()); +} + +} // namespace + +int main() { + engaged_guard_runs_the_seam_once(); + disengaged_guard_runs_no_seam(); + seam_names_function_and_file(); + seam_runs_before_dit(); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/libraries/secure/openspec/changes/genesis/reference/prior/config/test/timing_guard_test.cpp b/libraries/secure/openspec/changes/genesis/reference/prior/config/test/timing_guard_test.cpp new file mode 100644 index 0000000..f59860d --- /dev/null +++ b/libraries/secure/openspec/changes/genesis/reference/prior/config/test/timing_guard_test.cpp @@ -0,0 +1,121 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// webcpp::config::detail::timing_guard, config's data-independent-timing guard, without the seam: +// an engaged guard (timing_guard{} or timing_guard{true}) sets DIT for its scope where the CPU has +// it and clears it after when it found it clear; a guard that finds DIT set, as a program that set +// it itself, leaves it set; a disengaged guard (timing_guard{false}) does nothing; cpu_has_dit() +// answers the same at every call. Without the seam the constructor takes a bool and no +// std::source_location, so that no function's name or header's path reaches a program. On a +// target the guard does not cover, it is an empty class and both functions answer false. + +#include +#include +#include + +#include + +#include +#include + +namespace { + +using webcpp::config::detail::cpu_has_dit; +using webcpp::config::detail::dit_is_set; +using webcpp::config::detail::timing_guard; +using webcpp::test::force_dit; + +static_assert(!std::is_copy_constructible_v && + !std::is_copy_assignable_v, + "a guard is not copyable: the state it restores is its scope's"); +static_assert(!std::is_move_constructible_v && + !std::is_move_assignable_v, + "a guard is not movable: the state it restores is its scope's"); +static_assert(std::is_nothrow_default_constructible_v && + std::is_nothrow_constructible_v, + "a guard is made from nothing or from engaged, and never throws"); +static_assert(!std::is_convertible_v, "the constructor is explicit"); +static_assert(!std::is_constructible_v && + !std::is_constructible_v, + "without the seam, a guard takes no source_location"); +#ifndef WEBCPP_CONFIG_DETAIL_TIMING_COVERED +static_assert(std::is_empty_v, "where the guard does not act, it is an empty class"); +#endif + +// Where the guard does not act, both functions answer false. +void uncovered_answers_false() { +#ifndef WEBCPP_CONFIG_DETAIL_TIMING_COVERED + BOOST_TEST(!cpu_has_dit()); + BOOST_TEST(!dit_is_set()); +#endif +} + +// cpu_has_dit() is read once per process: every call answers as the first. +void cpu_answer_is_stable() { + bool const first = cpu_has_dit(); + for (int call = 0; call < 3; ++call) { + BOOST_TEST_EQ(cpu_has_dit(), first); + } +} + +// From clear: set inside an engaged guard, made either way, and clear after it. +void engaged_guard_sets_and_clears() { + force_dit(false); + BOOST_TEST(!dit_is_set()); + { + // tag::guard[] + webcpp::config::detail::timing_guard const + guard; // DIT set from here to the end of the scope + // end::guard[] + BOOST_TEST_EQ(dit_is_set(), cpu_has_dit()); + } + BOOST_TEST(!dit_is_set()); + { + timing_guard const guard{true}; + BOOST_TEST_EQ(dit_is_set(), cpu_has_dit()); + } + BOOST_TEST(!dit_is_set()); +} + +// From set, as a program sets it: still set inside and after a guard (spec: a program that set +// DIT keeps it). +void program_set_dit_is_kept() { + force_dit(true); + BOOST_TEST_EQ(dit_is_set(), cpu_has_dit()); + { + timing_guard const guard; + BOOST_TEST_EQ(dit_is_set(), cpu_has_dit()); + } + BOOST_TEST_EQ(dit_is_set(), cpu_has_dit()); + force_dit(false); + BOOST_TEST(!dit_is_set()); +} + +// A disengaged guard leaves DIT as it found it, clear or set. +void disengaged_guard_does_nothing() { + for (bool const initially_set : {false, true}) { + force_dit(initially_set); + bool const before = dit_is_set(); + BOOST_TEST_EQ(before, initially_set && cpu_has_dit()); + { + timing_guard const guard{false}; + BOOST_TEST_EQ(dit_is_set(), before); + } + BOOST_TEST_EQ(dit_is_set(), before); + } + force_dit(false); +} + +} // namespace + +int main() { + uncovered_answers_false(); + cpu_answer_is_stable(); + engaged_guard_sets_and_clears(); + program_set_dit_is_kept(); + disengaged_guard_does_nothing(); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/libraries/secure/openspec/changes/genesis/reference/prior/config/test/timing_guard_threads_test.cpp b/libraries/secure/openspec/changes/genesis/reference/prior/config/test/timing_guard_threads_test.cpp new file mode 100644 index 0000000..65e444f --- /dev/null +++ b/libraries/secure/openspec/changes/genesis/reference/prior/config/test/timing_guard_threads_test.cpp @@ -0,0 +1,72 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// DIT is a thread's own state, and a guard never changes another thread's: while a guard holds DIT +// on this thread, another thread reads it clear; while another thread holds a guard, this thread +// reads it clear. Each other thread is started before the guard it reads against, so that it +// cannot inherit the state at its creation (Linux's clone copies PSTATE). Built natively, with +// threads. + +#include +#include +#include + +#include + +#include +#include +#include + +namespace { + +using webcpp::config::detail::cpu_has_dit; +using webcpp::config::detail::dit_is_set; +using webcpp::config::detail::timing_guard; +using webcpp::test::force_dit; + +// A guard on this thread leaves another thread's DIT clear. +void other_thread_untouched() { + force_dit(false); + std::promise guard_entered; + std::promise other_reading; + std::thread other([entered = guard_entered.get_future(), &other_reading]() mutable { + entered.wait(); + other_reading.set_value(dit_is_set()); + }); + { + timing_guard const guard; + guard_entered.set_value(); + BOOST_TEST(!other_reading.get_future().get()); + BOOST_TEST_EQ(dit_is_set(), cpu_has_dit()); + } + other.join(); + BOOST_TEST(!dit_is_set()); +} + +// A guard on another thread leaves this thread's DIT clear, while it holds it and after. +void this_thread_untouched() { + force_dit(false); + std::promise other_guarded; + std::promise release; + std::thread other([&other_guarded, released = release.get_future()]() mutable { + timing_guard const guard; + other_guarded.set_value(); + released.wait(); + }); + other_guarded.get_future().wait(); + BOOST_TEST(!dit_is_set()); + release.set_value(); + other.join(); + BOOST_TEST(!dit_is_set()); +} + +} // namespace + +int main() { + other_thread_untouched(); + this_thread_untouched(); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/libraries/secure/openspec/changes/genesis/reference/prior/config/test/timing_guard_windows_test.cpp b/libraries/secure/openspec/changes/genesis/reference/prior/config/test/timing_guard_windows_test.cpp new file mode 100644 index 0000000..7b60a0e --- /dev/null +++ b/libraries/secure/openspec/changes/genesis/reference/prior/config/test/timing_guard_windows_test.cpp @@ -0,0 +1,114 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// webcpp::config::detail::timing_guard on Windows on ARM64 (_M_ARM64, not ARM64EC), where FEAT_DIT +// is read by one read of the register under structured exception handling: on the Windows 11 ARM64 +// machine of the Windows ARM64 lane, whose CPU has FEAT_DIT (every Armv8.4 CPU does), cpu_has_dit() +// is true; DIT is set inside a guard, still set after the thread sleeps inside it (Windows keeps +// PSTATE across a context switch), and clear after it; a guard that finds DIT set leaves it set. +// Built on every target config runs: on one the guard does not cover (Windows x64 among them) the +// guard is an empty class and both functions answer false, even after a program's attempt to set +// DIT; on arm64 under an Apple system or Linux it checks only that a guard restores a clear DIT, +// and timing_guard_test checks the rest there. + +#include +#include +#include + +#include + +#include + +#if defined(_MSC_VER) && defined(_M_ARM64) && !defined(_M_ARM64EC) +#define WEBCPP_TEST_TIMING_WINDOWS_ARM64 1 +#include +#include +#endif + +namespace { + +using webcpp::config::detail::cpu_has_dit; +using webcpp::config::detail::dit_is_set; +using webcpp::config::detail::timing_guard; +using webcpp::test::force_dit; + +#ifdef WEBCPP_TEST_TIMING_WINDOWS_ARM64 +// The CPU has FEAT_DIT, and the probe answers the same at every call. +bool cpu_has_dit_here() { + bool const offered = cpu_has_dit(); + BOOST_TEST(offered); + BOOST_TEST_EQ(cpu_has_dit(), offered); + return offered; +} + +// From clear: set inside a guard, still set after each of ten sleeps inside it, clear after it. +void guard_survives_sleeps() { + force_dit(false); + BOOST_TEST(!dit_is_set()); + { + timing_guard const guard; + BOOST_TEST(dit_is_set()); + for (int round = 0; round < 10; ++round) { + std::this_thread::sleep_for(std::chrono::milliseconds(20)); + BOOST_TEST(dit_is_set()); + } + } + BOOST_TEST(!dit_is_set()); +} + +// From set, as a program sets it: still set after a guard; a disengaged guard changes nothing. +void program_set_dit_is_kept() { + force_dit(true); + { + timing_guard const guard; + BOOST_TEST(dit_is_set()); + } + BOOST_TEST(dit_is_set()); + force_dit(false); + { + timing_guard const guard{false}; + BOOST_TEST(!dit_is_set()); + } + BOOST_TEST(!dit_is_set()); +} +#elif defined(WEBCPP_CONFIG_DETAIL_TIMING_COVERED) +// arm64 under an Apple system or Linux: a guard entered from clear leaves DIT clear (the full +// checks are timing_guard_test's; this program's subject is Windows). +void guard_restores_clear_dit() { + force_dit(false); + { + timing_guard const guard; + BOOST_TEST_EQ(dit_is_set(), cpu_has_dit()); + } + BOOST_TEST(!dit_is_set()); +} +#else +static_assert(std::is_empty_v, "where the guard does not act, it is empty"); + +// Where the guard does not act, both functions answer false, also after force_dit(true), which +// does nothing there. +void uncovered_answers_false() { + force_dit(true); + BOOST_TEST(!cpu_has_dit()); + BOOST_TEST(!dit_is_set()); +} +#endif + +} // namespace + +int main() { +#ifdef WEBCPP_TEST_TIMING_WINDOWS_ARM64 + if (cpu_has_dit_here()) { + guard_survives_sleeps(); + program_set_dit_is_kept(); + } +#elif defined(WEBCPP_CONFIG_DETAIL_TIMING_COVERED) + guard_restores_clear_dit(); +#else + uncovered_answers_false(); +#endif + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/libraries/secure/openspec/changes/genesis/reference/prior/crypto/include/webcpp/crypto/constant_time_equal.hpp b/libraries/secure/openspec/changes/genesis/reference/prior/crypto/include/webcpp/crypto/constant_time_equal.hpp new file mode 100644 index 0000000..233dec6 --- /dev/null +++ b/libraries/secure/openspec/changes/genesis/reference/prior/crypto/include/webcpp/crypto/constant_time_equal.hpp @@ -0,0 +1,77 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +/** + `constant_time_equal`, the constant-time comparison of tags and MACs, Boost.Hash2's included. +*/ +#ifndef WEBCPP_CRYPTO_CONSTANT_TIME_EQUAL_HPP +#define WEBCPP_CRYPTO_CONSTANT_TIME_EQUAL_HPP + +#include + +#include + +#include + +#include +#include +#include + +namespace webcpp::crypto { + +/** + * Whether two byte sequences are equal, in a time that does not depend on their contents. + * + * Every byte is read, and no branch or index depends on one: the XOR of each pair is + * accumulated with OR in a volatile local, read once after the loop, and reduced to one bit + * without a branch, as BearSSL's tag check does. Sizes are public: spans of different sizes + * compare unequal without reading their contents. On 64-bit ARM the comparison runs with DIT + * set where the CPU has it, and leaves the thread's DIT as it found it. + * + * @param first_operand The first sequence, a tag or a MAC. + * @param second_operand The second. + * @return Whether they have the same size and the same bytes. + */ +[[nodiscard]] inline bool constant_time_equal( + std::span first_operand, + std::span second_operand) noexcept { + detail::timing_guard const timing_scope; + if (first_operand.size() != second_operand.size()) { + return false; + } + unsigned volatile accumulated_difference = 0; + for (std::size_t byte_index = 0; byte_index < first_operand.size(); ++byte_index) { + accumulated_difference = + accumulated_difference | + static_cast(first_operand[byte_index] ^ second_operand[byte_index]); + } + unsigned const total_difference = accumulated_difference; + // all is at most 255: all - 1 wraps to the type's maximum only when all is 0. + return (((total_difference - 1U) >> 8U) & 1U) != 0; +} + +/** + * Whether two digests are equal, in a time that does not depend on their contents. + * + * Boost.Hash2's own `operator==` is `memcmp`, which is not constant time: a MAC is checked + * with this one. + * + * @tparam N The digests' size in bytes. + * @param first_operand The first digest. + * @param second_operand The second. + * @return Whether every byte is equal. + */ +template +[[nodiscard]] bool constant_time_equal(boost::hash2::digest const& first_operand, + boost::hash2::digest const& second_operand) noexcept { + detail::timing_guard const timing_scope; + return constant_time_equal(std::span(first_operand.data(), N), + std::span(second_operand.data(), N)); +} + +} // namespace webcpp::crypto + +#endif // WEBCPP_CRYPTO_CONSTANT_TIME_EQUAL_HPP diff --git a/libraries/secure/openspec/changes/genesis/reference/prior/crypto/include/webcpp/crypto/detail/declassify.hpp b/libraries/secure/openspec/changes/genesis/reference/prior/crypto/include/webcpp/crypto/detail/declassify.hpp new file mode 100644 index 0000000..127ce72 --- /dev/null +++ b/libraries/secure/openspec/changes/genesis/reference/prior/crypto/include/webcpp/crypto/detail/declassify.hpp @@ -0,0 +1,48 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +#ifndef WEBCPP_CRYPTO_DETAIL_DECLASSIFY_HPP +#define WEBCPP_CRYPTO_DETAIL_DECLASSIFY_HPP + +#include + +/* + * WEBCPP_CRYPTO_DETAIL_DECLASSIFY marks a value derived from secrets as public, where webcpp's code + * branches on it by design: the verdict of a tag's check. Nothing in a program's build; a + * constant-time test defines WEBCPP_CRYPTO_DETAIL_CT_VALGRIND or WEBCPP_CRYPTO_DETAIL_CT_MSAN, and + * the mark is then Valgrind's or MemorySanitizer's, so that the checker reports every other branch + * on a secret and not this one. + * + * Tip: the object marked is never const, so the branch that follows reads it again after the + * mark instead of a register the compiler kept from before it (BoringSSL's practice). + */ +#ifdef WEBCPP_CRYPTO_DETAIL_CT_VALGRIND +#include +/** + * Marks `size` bytes at `address` as public, for Valgrind. + * @param address The first byte. + * @param size The number of bytes. + */ +#define WEBCPP_CRYPTO_DETAIL_DECLASSIFY(address, size) \ + static_cast(VALGRIND_MAKE_MEM_DEFINED((address), (size))) +#elif defined(WEBCPP_CRYPTO_DETAIL_CT_MSAN) +#include +/** + * Marks `size` bytes at `address` as public, for MemorySanitizer. + * @param address The first byte. + * @param size The number of bytes. + */ +#define WEBCPP_CRYPTO_DETAIL_DECLASSIFY(address, size) __msan_unpoison((address), (size)) +#else +/** + * Marks `size` bytes at `address` as public: nothing in a program's build. + * @param address The first byte. + * @param size The number of bytes. + */ +#define WEBCPP_CRYPTO_DETAIL_DECLASSIFY(address, size) static_cast(0) +#endif + +#endif // WEBCPP_CRYPTO_DETAIL_DECLASSIFY_HPP diff --git a/libraries/secure/openspec/changes/genesis/reference/prior/crypto/include/webcpp/crypto/detail/wipe.hpp b/libraries/secure/openspec/changes/genesis/reference/prior/crypto/include/webcpp/crypto/detail/wipe.hpp new file mode 100644 index 0000000..d737746 --- /dev/null +++ b/libraries/secure/openspec/changes/genesis/reference/prior/crypto/include/webcpp/crypto/detail/wipe.hpp @@ -0,0 +1,49 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +#ifndef WEBCPP_CRYPTO_DETAIL_WIPE_HPP +#define WEBCPP_CRYPTO_DETAIL_WIPE_HPP + +#include + +#include +#include +#include + +namespace webcpp::crypto::detail { + +/** + * Zeroes `byte_count` bytes at `wiped_data` with stores the optimiser cannot drop. + * + * Tip: a `memset` before an object dies is a dead store a compiler may remove; stores through + * a volatile pointer, then a signal fence, are kept. + * + * @param wiped_data The first byte, or null when `byte_count` is 0. + * @param byte_count How many bytes. + */ +inline void wipe(void* wiped_data, std::size_t byte_count) noexcept { + auto* const wiped_bytes = static_cast(wiped_data); + for (std::size_t byte_index = 0; byte_index < byte_count; ++byte_index) { + wiped_bytes[byte_index] = 0; + } + std::atomic_signal_fence(std::memory_order_seq_cst); +} + +/** + * Zeroes an object's bytes, as @ref wipe does. + * + * @tparam T A trivially copyable type, a C library's key schedule or context. + * @param wiped_object The object. + */ +template +void wipe_object(T& wiped_object) noexcept { + static_assert(std::is_trivially_copyable_v, "only a C library's plain state is wiped"); + wipe(&wiped_object, sizeof wiped_object); +} + +} // namespace webcpp::crypto::detail + +#endif // WEBCPP_CRYPTO_DETAIL_WIPE_HPP diff --git a/libraries/secure/openspec/changes/genesis/reference/prior/crypto/include/webcpp/crypto/erase_secret.hpp b/libraries/secure/openspec/changes/genesis/reference/prior/crypto/include/webcpp/crypto/erase_secret.hpp new file mode 100644 index 0000000..4015df3 --- /dev/null +++ b/libraries/secure/openspec/changes/genesis/reference/prior/crypto/include/webcpp/crypto/erase_secret.hpp @@ -0,0 +1,78 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +/** + `erase_secret`, which zeroes a buffer the program owns, a password, a key or a plaintext, with + stores the optimiser keeps. + + A `memset` of a buffer that is not read again is a dead store, which a compiler may remove: + the secret then stays in memory after the program is done with it. `erase_secret` writes + through a volatile pointer, then a signal fence, as `secret` does when it dies. + + @see "Erasing a secret from a buffer", in the guide. +*/ +#ifndef WEBCPP_CRYPTO_ERASE_SECRET_HPP +#define WEBCPP_CRYPTO_ERASE_SECRET_HPP + +#include + +#include +#include + +#include +#include + +namespace webcpp::crypto { + +namespace detail { + +/** A contiguous sized range whose elements the program may write and copy as bytes. */ +template +concept erasable_range = + std::ranges::contiguous_range && std::ranges::sized_range && + (!std::is_const_v>>) && + std::is_trivially_copyable_v>; + +} // namespace detail + +/** + * Zeroes every byte of a buffer the program owns, with stores the optimiser keeps. + * + * It erases `size() * sizeof(element)` bytes from the range's first element: a `std::string`'s + * size, not its capacity, and nothing a reallocation left behind. It calls no backend. + * + * @tparam Range A contiguous sized range of non-const, trivially copyable elements: a + * `std::vector`, a `std::string`, a `std::array`, a `std::span`, a + * C array. + * @param erased_range The buffer. + */ +template + requires detail::erasable_range +void erase_secret(Range&& erased_range) noexcept { + detail::wipe(std::ranges::data(erased_range), + std::ranges::size(erased_range) * sizeof(std::ranges::range_value_t)); +} + +/** + * A contiguous sized range of const or non-trivially-copyable elements: it stops the build with + * a message naming the ranges `erase_secret` takes. + * + * @tparam Range The range refused. + */ +template + requires std::ranges::contiguous_range && std::ranges::sized_range && + (!detail::erasable_range) +void erase_secret(Range&& /*refused_range*/) noexcept { + static_assert(detail::dependent_false, + "webcpp::crypto: erase_secret zeroes a buffer the program may write, of " + "trivially copyable elements: a std::vector, a std::string, a " + "std::array, a std::span; this range's elements are const or not " + "trivially copyable."); +} + +} // namespace webcpp::crypto + +#endif // WEBCPP_CRYPTO_ERASE_SECRET_HPP diff --git a/libraries/secure/openspec/changes/genesis/reference/prior/crypto/include/webcpp/crypto/secret.hpp b/libraries/secure/openspec/changes/genesis/reference/prior/crypto/include/webcpp/crypto/secret.hpp new file mode 100644 index 0000000..740783d --- /dev/null +++ b/libraries/secure/openspec/changes/genesis/reference/prior/crypto/include/webcpp/crypto/secret.hpp @@ -0,0 +1,146 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +/** A secret output of webcpp::crypto, which wipes itself (design D9). */ +#ifndef WEBCPP_CRYPTO_SECRET_HPP +#define WEBCPP_CRYPTO_SECRET_HPP + +#include + +#include + +#include +#include +#include +#include + +namespace webcpp::crypto { + +/** + `N` secret bytes: a shared secret, a session key, a converted secret key. + + They are wiped by volatile stores when the object is destroyed or moved from; a copy is made + only by `clone`. + + The wipe covers the object's own storage only: a move or a `clone` may leave copies of the bytes in + registers or temporaries, which the library does not reach. + + @tparam N The number of bytes. +*/ +template +class secret { + static_assert(N > 0, "webcpp::crypto: a secret of no bytes holds nothing."); + +public: + /** The number of bytes. */ + static constexpr std::size_t size_bytes = N; + + /** Zero bytes. */ + secret() noexcept = default; + + /** + Takes the bytes of `moved_secret`, which is wiped. + + @param moved_secret The secret to take the bytes of. + */ + secret(secret&& moved_secret) noexcept : bytes_(moved_secret.bytes_) { + detail::wipe_object(moved_secret.bytes_); + } + + /** + Wipes these bytes, then takes the bytes of `moved_secret`, which is wiped; a move to itself + changes nothing. + + @param moved_secret The secret to take the bytes of. + @return This secret. + */ + secret& operator=(secret&& moved_secret) noexcept { + if (this != &moved_secret) { + detail::wipe_object(bytes_); + bytes_ = moved_secret.bytes_; + detail::wipe_object(moved_secret.bytes_); + } + return *this; + } + + /** Not copyable: a copy is asked for by name, with `clone`. */ + secret(secret const&) = delete; + /** Not copyable: a copy is asked for by name, with `clone`. */ + secret& operator=(secret const&) = delete; + + /** Wipes the bytes. */ + ~secret() { detail::wipe_object(bytes_); } + + /** + A copy of the bytes, which the caller then owns. + + @return A secret of the same bytes. + */ + [[nodiscard]] secret clone() const noexcept { + secret secret_copy; + secret_copy.bytes_ = bytes_; + return secret_copy; + } + + /** + The bytes, to read. + + @return A view of the bytes. + */ + [[nodiscard]] std::span bytes() const& noexcept { return bytes_; } + + /** + Not available on a secret that is about to be destroyed: the view would dangle. + + @return Nothing. + */ + [[nodiscard]] std::span bytes() const&& = delete; + + /** + The bytes, for the library's engines to write. + + @return A writable view of the bytes. + */ + [[nodiscard]] std::span writable() & noexcept { return bytes_; } + + /** + Not available on a secret that is about to be destroyed: the view would dangle. + + @return Nothing. + */ + std::span writable() && = delete; + + /** + The bytes, as a span of fixed size. + + @return A view of the bytes. + */ + // Implicit, as the spec asks, so that a secret is passed where a function takes the span of + // its bytes: misc-explicit-constructor is silenced for it. + // NOLINTNEXTLINE(misc-explicit-constructor) + operator std::span() const& noexcept { return bytes_; } + + /** + Not available on a secret that is about to be destroyed: the view would dangle. + + @return Nothing. + */ + operator std::span() const&& = delete; + + /** + The number of bytes. + + @return `N`. + */ + static constexpr std::size_t size() noexcept { return N; } + +private: + std::array bytes_{}; +}; + +} // namespace webcpp::crypto + +#endif // WEBCPP_CRYPTO_SECRET_HPP diff --git a/libraries/secure/openspec/changes/genesis/reference/prior/crypto/test/constant_time_equal_test.cpp b/libraries/secure/openspec/changes/genesis/reference/prior/crypto/test/constant_time_equal_test.cpp new file mode 100644 index 0000000..b6ed402 --- /dev/null +++ b/libraries/secure/openspec/changes/genesis/reference/prior/crypto/test/constant_time_equal_test.cpp @@ -0,0 +1,68 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// constant_time_equal compares two digests, a digest and an array, or two spans, and tells them +// apart by any byte; spans of different sizes are unequal, and two empty spans are equal. + +#include +#include + +#include +#include +#include +#include + +#include +#include +#include +#include + +namespace crypto = webcpp::crypto; + +int main() { + boost::hash2::digest<16> a{}; + boost::hash2::digest<16> b{}; + BOOST_TEST(crypto::constant_time_equal(a, b)); + for (std::size_t i = 0; i < a.size(); ++i) { + for (unsigned bit = 0; bit < 8; ++bit) { + b = a; + b.data()[i] ^= static_cast(1U << bit); + BOOST_TEST(!crypto::constant_time_equal(a, b)); + } + } + std::array const array{}; + BOOST_TEST(crypto::constant_time_equal(a, array)); + std::array const shorter{}; + BOOST_TEST(!crypto::constant_time_equal(a, shorter)); + BOOST_TEST(crypto::constant_time_equal(std::span(), + std::span())); + + // Spans of one size: equal ones, and ones that differ in any byte (the first, the last). + std::array const eight{1, 2, 3, 4, 5, 6, 7, 8}; + auto different_first = eight; + different_first.front() ^= 0x80U; + auto different_last = eight; + different_last.back() ^= 0x01U; + BOOST_TEST(crypto::constant_time_equal(std::span(eight), std::span(eight))); + BOOST_TEST(!crypto::constant_time_equal(std::span(eight), + std::span(different_first))); + BOOST_TEST(!crypto::constant_time_equal(std::span(eight), + std::span(different_last))); + // Two 32-byte digests (a SHA-256 tag's size) that differ in the last byte only. + boost::hash2::digest<32> const first_digest{}; + boost::hash2::digest<32> second_digest{}; + BOOST_TEST(crypto::constant_time_equal(first_digest, second_digest)); + second_digest.data()[31] = 1; + BOOST_TEST(!crypto::constant_time_equal(first_digest, second_digest)); + + // Hash2's MAC, which constant_time_equal serves too: two results of one key and message agree. + boost::hash2::hmac_sha2_256 first(reinterpret_cast("key"), 3); + boost::hash2::hmac_sha2_256 second(reinterpret_cast("key"), 3); + first.update("message", 7); + second.update("message", 7); + BOOST_TEST(crypto::constant_time_equal(first.result(), second.result())); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/libraries/secure/openspec/changes/genesis/reference/prior/crypto/test/declassify_compile_test.cpp b/libraries/secure/openspec/changes/genesis/reference/prior/crypto/test/declassify_compile_test.cpp new file mode 100644 index 0000000..d5a0fcd --- /dev/null +++ b/libraries/secure/openspec/changes/genesis/reference/prior/crypto/test/declassify_compile_test.cpp @@ -0,0 +1,30 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// Every header that marks a verdict public for the constant-time checks +// (WEBCPP_CRYPTO_DETAIL_DECLASSIFY) compiles with the marks on, as the constant-time lane's +// memcheck programs build them (WEBCPP_CRYPTO_DETAIL_CT_VALGRIND), on every lane: Valgrind's +// header is a stand-in that reads the address and the size (support/valgrind_stub). Outside that +// lane the macro expands to nothing, so a mark that names a local no longer there compiles +// everywhere else; here it stops the build. + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef WEBCPP_CRYPTO_DETAIL_CT_VALGRIND +#error "the test compiles the marks of the memcheck build: define WEBCPP_CRYPTO_DETAIL_CT_VALGRIND" +#endif + +int main() { + return 0; +} diff --git a/libraries/secure/openspec/changes/genesis/reference/prior/crypto/test/erase_secret_test.cpp b/libraries/secure/openspec/changes/genesis/reference/prior/crypto/test/erase_secret_test.cpp new file mode 100644 index 0000000..976f081 --- /dev/null +++ b/libraries/secure/openspec/changes/genesis/reference/prior/crypto/test/erase_secret_test.cpp @@ -0,0 +1,156 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// crypto::erase_secret zeroes every byte of a contiguous range the program may write, and none +// around it; it takes no range that is not contiguous, and no pointer with a size; and a buffer +// erased just before its scope ends is zero in its storage afterwards, read at -O2 with every +// call inlined (the Jamfile's speed full), where a store the optimiser +// may drop is the case. + +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +namespace crypto = webcpp::crypto; + +// Written through a concept, so that a range with no viable overload reads as false instead of +// stopping the build (a requires-expression outside a template is a hard error). +template +concept erasable = + requires(Range&& erased_range) { crypto::erase_secret(std::forward(erased_range)); }; + +static_assert(erasable&>); +static_assert(erasable>); +static_assert(!erasable&>); +static_assert(!erasable&>); + +// Whether erase_secret takes a pointer and a size, the overload it has none of: a range carries +// its own size (design D10). +template +concept erasable_by_pointer_and_size = requires(Pointer erased_data, std::size_t byte_count) { + crypto::erase_secret(erased_data, byte_count); +}; + +static_assert(!erasable_by_pointer_and_size); +static_assert(!erasable_by_pointer_and_size); +static_assert(!erasable_by_pointer_and_size); +static_assert(noexcept(crypto::erase_secret(std::declval&>()))); + +// A function the optimiser cannot see into, so that what it is handed is read from memory. +#if defined(_MSC_VER) && !defined(__clang__) +#define WEBCPP_TEST_NOINLINE __declspec(noinline) +#else +#define WEBCPP_TEST_NOINLINE __attribute__((noinline)) +#endif + +// Whether every byte at `where` is zero, read through a volatile pointer in a function that is +// never inlined: a store that was dropped before the call is found here. It may be handed the +// address of an object that is gone (the point of the scope's check), so it is exempt from the +// sanitizers that would stop that read. +#if defined(__clang__) || defined(__GNUC__) +__attribute__((no_sanitize("address"))) +#endif +WEBCPP_TEST_NOINLINE bool memory_is_zero(void const* where, std::size_t count) { + auto const volatile* const bytes = static_cast(where); + for (std::size_t i = 0; i < count; ++i) { + if (bytes[i] != 0) { + return false; + } + } + return true; +} + +// A buffer in a scope of its own, which a call the optimiser cannot see into is handed, is +// erased as the scope's last statement; its storage, in this frame, is read after the scope. An +// erasure that is a dead store (a plain write to an object about to die) is dropped by the +// optimiser and the bytes remain. +WEBCPP_TEST_NOINLINE bool erasure_before_scope_end_stays() { + std::uint8_t const* where = nullptr; + constexpr std::size_t count = 32; + { + std::array password{}; + for (std::size_t i = 0; i < count; ++i) { + password[i] = static_cast(i + 1); + } + where = password.data(); + if (memory_is_zero(where, count)) { + return false; + } + crypto::erase_secret(password); + } + return memory_is_zero(where, count); +} + +} // namespace + +int main() { + // A vector of bytes. + std::vector key(32, 0xa5); + crypto::erase_secret(key); + BOOST_TEST_EQ(key.size(), 32U); + BOOST_TEST(memory_is_zero(key.data(), key.size())); + + // A string: its size() bytes, its terminator kept, its size unchanged. + // tag::erase[] + std::string password(200, '\0'); + password = "correct horse battery staple"; // read into a buffer reserved beforehand + // ... the password is checked or hashed ... + webcpp::crypto::erase_secret(password); + // end::erase[] + BOOST_TEST_EQ(password.size(), 28U); + BOOST_TEST(memory_is_zero(password.data(), password.size())); + BOOST_TEST_EQ(password[password.size()], '\0'); + + // An array of 33 bytes, a compressed public key's size. + std::array point{}; + point.fill(0x5a); + crypto::erase_secret(point); + BOOST_TEST(memory_is_zero(point.data(), point.size())); + + // A span of std::byte over part of a stack buffer: the bytes around it are untouched. + std::array framed{}; + framed.fill(std::byte{0xc3}); + crypto::erase_secret(std::span(framed).subspan(1, 16)); + BOOST_TEST(framed.front() == std::byte{0xc3}); + BOOST_TEST(framed.back() == std::byte{0xc3}); + BOOST_TEST(memory_is_zero(framed.data() + 1, 16)); + + // A C array, which erase_secret takes as a program may hold one. + // NOLINTNEXTLINE(modernize-avoid-c-arrays): the C array is what this case erases + unsigned char raw[16]; + for (auto& byte : raw) { + byte = 0x77; + } + crypto::erase_secret(raw); + BOOST_TEST(memory_is_zero(raw, sizeof raw)); + + // A vector of words: size() * sizeof(element) bytes. + std::vector words(8, 0xdeadbeefU); + crypto::erase_secret(words); + BOOST_TEST(memory_is_zero(words.data(), words.size() * sizeof(std::uint32_t))); + + // An empty vector: nothing to erase. + std::vector empty; + crypto::erase_secret(empty); + BOOST_TEST(empty.empty()); + + // A buffer erased as its scope ends is zero afterwards, at -O2 with every call inlined. + BOOST_TEST(erasure_before_scope_end_stays()); + + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/libraries/secure/openspec/changes/genesis/reference/prior/node-test/include/webcpp/test/timing_dit.hpp b/libraries/secure/openspec/changes/genesis/reference/prior/node-test/include/webcpp/test/timing_dit.hpp new file mode 100644 index 0000000..620cc50 --- /dev/null +++ b/libraries/secure/openspec/changes/genesis/reference/prior/node-test/include/webcpp/test/timing_dit.hpp @@ -0,0 +1,35 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// A test's control of the thread's DIT, for config's tests and every library's: force_dit sets or +// clears it, as a program can, so that a check starts from a known state. A test that defines the +// seam of webcpp::config::detail::timing_guard () includes it before +// this header, which includes the guard's. + +#ifndef WEBCPP_TEST_TIMING_DIT_HPP +#define WEBCPP_TEST_TIMING_DIT_HPP + +#include + +namespace webcpp::test { + +/** + * Sets or clears DIT for this thread, as a program can; only where the CPU has DIT, since the + * instruction traps on a CPU without it, and nothing where the guard does not act. + * + * @param set Whether to set DIT. + */ +inline void force_dit([[maybe_unused]] bool set) noexcept { +#ifdef WEBCPP_CONFIG_DETAIL_TIMING_COVERED + if (webcpp::config::detail::cpu_has_dit()) { + webcpp::config::detail::write_dit(set ? webcpp::config::detail::dit_bit : 0); + } +#endif +} + +} // namespace webcpp::test + +#endif // WEBCPP_TEST_TIMING_DIT_HPP diff --git a/libraries/secure/openspec/changes/genesis/reference/prior/node-test/include/webcpp/test/timing_seam.hpp b/libraries/secure/openspec/changes/genesis/reference/prior/node-test/include/webcpp/test/timing_seam.hpp new file mode 100644 index 0000000..350b3f5 --- /dev/null +++ b/libraries/secure/openspec/changes/genesis/reference/prior/node-test/include/webcpp/test/timing_seam.hpp @@ -0,0 +1,115 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// The seam of webcpp::config::detail::timing_guard, config's guard, recorded for a library's tests: +// a library's test/support/timing_seam.hpp defines WEBCPP_TEST_TIMING_LIBRARY, the library's +// directory name ("crypto", "hash"), then includes this header, and a test includes that support +// header before any webcpp header, so that the seam is defined before +// is first read and every engaged guard a call enters is +// counted, on every target, also where DIT does not apply. A guard is the library's own when one of +// the library's headers declares it: its source_location's file_name() holds +// include/webcpp//, with `/` or `\` around each word (MSVC writes backslashes, and joins +// an include directory to a header's path with either); the include root keeps a checkout whose +// own folders read webcpp// from counting a test file's guard. timing_entries counts the +// library's own guards and timing_all_entries every guard: another library's, which a call may +// enter inside its own, and a test's own. timing_first_entry and timing_last_entry keep the +// function of the first guard since a reset and of the last, which a library's checks read. + +#ifndef WEBCPP_TEST_TIMING_SEAM_HPP +#define WEBCPP_TEST_TIMING_SEAM_HPP + +#ifdef WEBCPP_CONFIG_DETAIL_TIMING_GUARD_HPP +#error " must be included before any webcpp header" +#endif + +#ifndef WEBCPP_TEST_TIMING_LIBRARY +#error "define WEBCPP_TEST_TIMING_LIBRARY, the library whose guards timing_entries counts" +#endif + +#include +#include +#include + +namespace webcpp::test { + +/** Every timing guard this thread entered: the library's, another's, a test's. */ +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables): the seam's counter +inline thread_local std::size_t timing_all_entries = 0; + +/** The timing guards of the library's headers this thread has entered. */ +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables): the seam's counter +inline thread_local std::size_t timing_entries = 0; + +/** + * The `function_name()` of the first guard, of any file, this thread entered since it was last + * reset to null: the function that holds that guard, as the compiler spells it. + */ +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables): the seam's record +inline thread_local char const* timing_first_entry = nullptr; + +/** The `function_name()` of the last guard, of any file, this thread entered. */ +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables): the seam's record +inline thread_local char const* timing_last_entry = nullptr; + +/** The library whose guards timing_entries counts, WEBCPP_TEST_TIMING_LIBRARY. */ +inline constexpr std::string_view timing_library = WEBCPP_TEST_TIMING_LIBRARY; + +/** Whether `character` separates a path's components, on any system webcpp builds on. */ +constexpr bool path_separator(char character) noexcept { + return character == '/' || character == '\\'; +} + +/** + * Whether a path names a file under a library's include directory: the components `include`, + * `webcpp` and `library`, in that order, each followed by a separator, `/` or `\` in any mix, and + * `include` the path's first component or after a separator. + * + * @param path A `file_name()`. + * @param library The library's directory name. + * @return Whether the path is under `include/webcpp//`. + */ +constexpr bool path_in_library(std::string_view path, std::string_view library) noexcept { + constexpr std::string_view include_root = "include"; + constexpr std::string_view root = "webcpp"; + for (std::size_t at = path.find(include_root); at != std::string_view::npos; + at = path.find(include_root, at + 1)) { + std::size_t const root_at = at + include_root.size() + 1; + std::size_t const library_at = root_at + root.size() + 1; + std::size_t const after = library_at + library.size(); + if ((at == 0 || path_separator(path[at - 1])) && after < path.size() && + path_separator(path[root_at - 1]) && path.substr(root_at, root.size()) == root && + path_separator(path[library_at - 1]) && + path.substr(library_at, library.size()) == library && path_separator(path[after])) { + return true; + } + } + return false; +} + +/** + * Records the entry into a webcpp::config::detail::timing_guard: counts it, as the library's when + * its file is under the library's include directory, and keeps its function as the first since + * timing_first_entry was reset and as the last. + * + * @param where Where the guard is declared. + */ +inline void timing_entered(std::source_location const& where) noexcept { + ++timing_all_entries; + if (path_in_library(where.file_name(), timing_library)) { + ++timing_entries; + } + if (timing_first_entry == nullptr) { + timing_first_entry = where.function_name(); + } + timing_last_entry = where.function_name(); +} + +} // namespace webcpp::test + +/** Records the entry into a webcpp::config::detail::timing_guard declared at `where`. */ +#define WEBCPP_CONFIG_DETAIL_TIMING_ENTERED(where) (::webcpp::test::timing_entered(where)) + +#endif // WEBCPP_TEST_TIMING_SEAM_HPP diff --git a/libraries/secure/openspec/changes/genesis/specs/secure/spec.md b/libraries/secure/openspec/changes/genesis/specs/secure/spec.md new file mode 100644 index 0000000..d77188e --- /dev/null +++ b/libraries/secure/openspec/changes/genesis/specs/secure/spec.md @@ -0,0 +1,114 @@ +## ADDED Requirements + +### Requirement: Library: header-only, names, headers and dependencies +The library SHALL be header-only C++20 in namespace `webcpp::secure` (with `webcpp::secure::constant_time` and `webcpp::secure::detail`), with public headers `` and ``, macros prefixed `WEBCPP_SECURE_` and include guards `WEBCPP_SECURE__HPP`, and MUST declare no name outside `webcpp::secure`. Every public header MUST include `` first, which includes `` first and defines `WEBCPP_SECURE_NO_EXCEPTIONS` exactly when `WEBCPP_HAS_EXCEPTIONS` is not defined or a developer defines it. `build.jam` MUST declare the target `/webcpp/secure//secure` with the headers, Boost's headers and `/webcpp/config//config` alone, building and linking nothing. The library MUST include no header of another webcpp library but config's, and MUST hold no cryptographic algorithm. Every function MUST be `noexcept` and none SHALL throw. + +#### Scenario: A program that erases a buffer builds nothing +- **WHEN** a Jamfile reads `exe app : app.cpp /webcpp/secure//secure ;` and `app.cpp` includes ``, holds a `secure::timing_guard`, compares two buffers with `secure::constant_time_equal` and erases one with `secure::erase_secret` +- **THEN** it builds and runs on native, wasip2, wasip3 and Emscripten, with exceptions on and off, and no library is compiled for secure + +#### Scenario: Each header compiles first and alone +- **WHEN** each public header of the library is included first and alone in a translation unit +- **THEN** it compiles, and `WEBCPP_VERSION` is defined after it + +### Requirement: Timing guard: DIT for a scope, nesting across libraries +`` SHALL declare `secure::timing_guard`, `secure::cpu_has_dit()` and `secure::dit_is_set()`, public names of the library and the only DIT guard of webcpp. An engaged guard (`timing_guard{}` or `timing_guard{true}`) MUST set PSTATE.DIT for its scope when the CPU has FEAT_DIT and DIT is clear, and clear it on destruction only when it set it; a guard that finds DIT set MUST leave it set; a disengaged guard (`timing_guard{false}`) MUST do nothing. Each write of DIT MUST be followed by an `isb`. The guard MUST NOT be copyable or movable, MUST NOT change another thread's DIT, and MUST NOT execute a DIT instruction on a CPU without FEAT_DIT but the one probe Windows needs. `cpu_has_dit()` MUST be read once per process. + +#### Scenario: Guards nest +- **WHEN** a test constructs three engaged guards nested, as codecs inside crypto inside hash would, with a disengaged one between them, on a CPU with DIT and DIT clear +- **THEN** DIT is set inside every level, still set after each inner guard ends, and clear after the outermost ends + +#### Scenario: A program that set DIT keeps it +- **WHEN** a thread sets DIT itself and then constructs and destroys an engaged guard +- **THEN** DIT is set after the guard ends + +#### Scenario: Another thread is untouched +- **WHEN** one thread holds an engaged guard while another thread, with DIT clear, reads `dit_is_set()` +- **THEN** the other thread reads false, natively where the build has threads + +### Requirement: Timing guard: the targets it covers +The guard SHALL act, and `WEBCPP_SECURE_TIMING_COVERED` SHALL be defined, on arm64 under Apple's systems (FEAT_DIT from `sysctlbyname("hw.optional.arm.FEAT_DIT")`), under Linux and Android (`HWCAP_DIT` of `AT_HWCAP`), and under Windows with `_MSC_VER`, `_M_ARM64` and not `_M_ARM64EC` (the register through `_ReadStatusReg` and `_WriteStatusReg` and `__isb`, FEAT_DIT from one read of the register under structured exception handling, `STATUS_ILLEGAL_INSTRUCTION` meaning absent, other exceptions passed on). On every other target the guard MUST be an empty class that executes no instruction, and `cpu_has_dit()` and `dit_is_set()` MUST return false. + +#### Scenario: Windows on ARM64 +- **WHEN** `timing_guard_windows_test` runs on the Windows 11 ARM64 lane with MSVC 14.3 and 14.5, debug and release, with exceptions on and off +- **THEN** `cpu_has_dit()` is true on that CPU, DIT is set inside a guard, still set after the thread sleeps inside it, and clear after it + +#### Scenario: WebAssembly and x86 +- **WHEN** the guard's tests run on wasip2, wasip3, Emscripten and x86-64 +- **THEN** `std::is_empty_v` holds and both functions return false + +### Requirement: Timing guard: one seam for the tests +A macro `WEBCPP_SECURE_TIMING_ENTERED(where)`, defined by a test alone before its first include, SHALL be run with a `std::source_location` of the guard's declaration on every engaged guard's construction, before DIT is touched, on every target; a disengaged guard MUST NOT run it. Without the macro the constructor MUST take no source location, so that no function name or path reaches a program. The location's `function_name()` MUST name the function that declares the guard and its `file_name()` MUST let a test tell one library's guards from another's. + +#### Scenario: The seam names the guarded function +- **WHEN** a test with the seam defined calls a function of its own that declares an engaged guard, then one that declares a disengaged guard +- **THEN** the seam records one entry, whose `function_name()` is the first function's, and none for the second + +#### Scenario: Nothing reaches a program +- **WHEN** a translation unit without the seam constructs a guard +- **THEN** `` is not included by the guard's header and the constructor takes only `engaged` + +### Requirement: Memory: erase_secret +`` SHALL declare `secure::erase_secret(range)`, which zeroes `size() * sizeof(element)` bytes from the first element of a contiguous sized range of non-const, trivially copyable elements, with volatile stores followed by a signal fence that the optimiser keeps, and touches no byte around them. A range of const or not trivially copyable elements MUST stop the build with a message naming the ranges it takes; a range that is not contiguous, and a pointer with a size, MUST NOT be accepted. + +#### Scenario: A buffer erased before its scope ends +- **WHEN** a test erases a stack buffer as its last use before its scope ends, built at `-O2` with full inlining, and reads that storage afterwards through the test's placement storage +- **THEN** every byte reads zero, on every lane + +#### Scenario: A refused range +- **WHEN** a test asks whether `erase_secret` accepts a `std::list&`, a `std::vector&` and a `std::span` +- **THEN** it accepts none of them, and accepts a `std::vector&`, a `std::string&`, a `std::span` and a span of one C library context + +### Requirement: Memory: secret +`` SHALL declare `secure::secret` for `N > 0`: `N` bytes held in place, zero-initialised, move-only (the source wiped after a move, the target wiped before it takes new bytes, a self-move changing nothing), copied only by `clone()`, read through `bytes()` and an implicit conversion to `std::span` on an lvalue, written through `writable()` on an lvalue, with those views deleted on an rvalue, `size()` and `size_bytes` equal to `N`, and its storage wiped on destruction as `erase_secret` wipes. + +#### Scenario: Destroyed and moved-from storage reads zero +- **WHEN** a test constructs a `secret<32>` in placement storage, writes it, moves it into another and destroys both +- **THEN** the moved-from storage reads zero after the move and both storages read zero after destruction + +#### Scenario: No view of a temporary +- **WHEN** a test asks whether `bytes()`, `writable()` or the span conversion are callable on an rvalue `secret<16>` +- **THEN** none is + +### Requirement: Comparison: constant_time_equal +`` SHALL declare `secure::constant_time_equal(first, second)` for any two contiguous sized ranges of one-byte elements (`std::uint8_t`, `unsigned char`, `char`, `std::byte`), returning whether they have the same size and the same bytes. Sequences of different sizes MUST compare unequal without reading their contents; otherwise every byte MUST be read, with no branch and no index that depends on a byte, and the result reduced to one bit without a branch. It MUST hold an engaged guard, and MUST NOT include a Boost.Hash2 header. + +#### Scenario: Every single-byte difference +- **WHEN** a test compares a 32-byte sequence with each copy of it that differs in one bit, and with itself, as spans, arrays, a `secret<32>`, a `std::string_view` and a Boost.Hash2 `digest<32>` +- **THEN** only the identical ones compare equal, and the seam records the guard in `constant_time_equal` + +### Requirement: Constant-time checks: declassify +`` SHALL declare `secure::declassify(value)` for a non-const, trivially copyable object, which does nothing and includes nothing in a program's build, marks the object's bytes defined for memcheck (`VALGRIND_MAKE_MEM_DEFINED`) when `WEBCPP_SECURE_CT_VALGRIND` is defined, and unpoisons them for MemorySanitizer (`__msan_unpoison`) when `WEBCPP_SECURE_CT_MSAN` is defined; defining both MUST stop the build. Marking a value secret and reading a checker's shadow MUST NOT be public names of the library: they are its test support. + +#### Scenario: The marks compile in a checker's build +- **WHEN** `declassify_compile_test` includes every header of the library with `WEBCPP_SECURE_CT_VALGRIND` defined, and under clang with `WEBCPP_SECURE_CT_MSAN` defined +- **THEN** it compiles and runs, and a branch on a declassified verdict is not reported by the checker while a branch on an undeclassified one is + +### Requirement: Constant-time blocks +`` SHALL declare, in `secure::constant_time`, `value_barrier`, `mask_from_bit`, `is_zero_mask`, `is_equal_mask`, `is_less_mask`, `is_in_range_mask` and `select` over any unsigned integral type but `bool`, `lookup` over a table of unsigned integral entries, and `select_bytes`, `equal_mask`, `is_zero_mask` and `less_mask` (big-endian) over byte sequences. A mask MUST be all zeros or all ones of its type. No block MUST branch on, or index memory by, a value it receives but a public size; `lookup` MUST read every entry of its table and yield a value-initialised entry for an index past it; every mask a block makes MUST pass through `value_barrier`. Each block MUST equal a plain reference implementation on every input. + +#### Scenario: Exhaustive over bytes +- **WHEN** the blocks' test runs every pair of `std::uint8_t` (every triple for `is_in_range_mask`) and random values of 16, 32 and 64 bits with their edges against the plain reference +- **THEN** every result is equal, on every lane + +#### Scenario: memcheck sees no secret-dependent access +- **WHEN** the constant-time lane marks the operands undefined and runs every block, `constant_time_equal` and `secret`'s moves under memcheck, and under MemorySanitizer where crypto runs it +- **THEN** no conditional jump and no address depends on them, while the planted branching `select` and indexing `lookup` are reported + +#### Scenario: dudect judges +- **WHEN** dudect measures `constant_time_equal`, `lookup`, `select_bytes` and `less_mask` with two classes of input natively +- **THEN** each case's |t| stays below the threshold, its A/A control too, and the planted leak exceeds it + +### Requirement: Tests and lanes +Every test of the library SHALL run on native (clang and gcc 15), wasip2, wasip3 and Emscripten with its `_no_exceptions` twin, and on MSVC 14.3 and 14.5 and Apple clang as the other libraries; the guard's tests MUST also run on the Windows ARM64 lane; a counting `operator new` MUST see no allocation in any function of the library. The seam recorder, the DIT helper and the checkers' marks that secure's tests use MUST live in secure's own `test/support/`. + +#### Scenario: No heap +- **WHEN** `allocation_test` replaces every form of `operator new` with a counter and calls every function of the library +- **THEN** the counter is zero after every call, on every target + +### Requirement: Documentation +The library SHALL have its page under `libs/secure/doc/`, built by `b2 doc`: what secure is and is not (no algorithm), the guard (its coverage table, nesting, `engaged`, the seam), `erase_secret`, `secret`, `constant_time_equal`, `declassify`, the constant-time blocks with their limits, the guard's measured cost from release builds, and the changelog, every example built and run in the lanes. + +#### Scenario: The page builds +- **WHEN** `b2 doc` runs in the superproject +- **THEN** secure's page is produced with every section above, and its examples' expected outputs match their runs diff --git a/libraries/secure/openspec/changes/genesis/tasks.md b/libraries/secure/openspec/changes/genesis/tasks.md new file mode 100644 index 0000000..596543b --- /dev/null +++ b/libraries/secure/openspec/changes/genesis/tasks.md @@ -0,0 +1,42 @@ +# Tasks + +Each task writes its tests first; the library builds and its tests pass on every local lane at the +end of every task. A plan with code goes in `reference/plan.md` when the proposal is accepted. The +owner's gates come first: the repository `webcpporg/secure` and the submodule `libs/secure` +(chapter 10's checklist, items 1 and 2); until then the library is a local repository at +`libs/secure`. The prior code to port is in `reference/prior/` (`reference/STATUS.md`). + +## 1. The library's skeleton + +- [ ] 1.1 The repository's files (chapter 10's checklist, items 3 to 7): `meta/libraries.json` with `"port-of": null`, `build.jam` with `secure` (D1), `LICENSE_1_0.txt`, `README.md`, `AGENTS.md`, `.gitattributes`, `.gitignore`, `.github/workflows/ci.yml`, `test/Jamfile`, `example/Jamfile`, `doc/Jamfile` and `doc/changelog.adoc`; the index page's entry +- [ ] 1.2 `config.hpp` and its test three ways (exceptions, `WEBCPP_NO_EXCEPTIONS`, `WEBCPP_SECURE_NO_EXCEPTIONS`); `CODING-GUIDELINES.md` chapter 17's entry (D1) + +## 2. The guard + +- [ ] 2.1 `timing_guard.hpp` on Apple's systems and Linux, ported from `reference/prior/config/include/` with `WEBCPP_SECURE_*` names in `webcpp::secure`; secure's `test/support/timing_seam.hpp` and `timing_dit.hpp`; `timing_guard_test`, `_nesting_`, `_seam_`, `_threads_` and the header-alone test (D2, D9, D10) +- [ ] 2.2 Windows on ARM64: the intrinsics, the SEH probe, `timing_guard_windows_test`, run on the Windows ARM64 lane with MSVC 14.3 and 14.5, debug and release (D3, D11) + +## 3. Memory and comparison + +- [ ] 3.1 `detail/wipe.hpp` and `erase_secret.hpp`, moved from crypto with `erase_secret_test` (D4) +- [ ] 3.2 `secret.hpp`, moved from crypto, with `secret_test` (D6) +- [ ] 3.3 `constant_time_equal.hpp` over byte ranges, with `constant_time_equal_test` and its seam check (D5) +- [ ] 3.4 `declassify.hpp`, secure's `test/support/constant_time_marks.hpp`, `declassify_compile_test` (D7, D9) + +## 4. The constant-time blocks + +- [ ] 4.1 `constant_time.hpp`: `value_barrier`, the masks, `select`, `lookup`, `select_bytes` and the byte comparisons, with the exhaustive and random tests against a plain reference (D8, D10) +- [ ] 4.2 The allocation test over every function; the convenience header and its test (D1, D10) + +## 5. The constant-time lane + +- [ ] 5.1 The lane `constant-time`: memcheck with the operands undefined, MemorySanitizer where crypto runs it, dudect with its A/A control, the planted branching `select` and indexing `lookup` that must fail (D10) + +## 6. The documentation and the delivery + +- [ ] 6.1 The page: what secure is, the guard, erase, `secret`, `constant_time_equal`, `declassify`, the blocks and their limits, the changelog; every example built and run; the guard's cost measured on release builds on an idle machine (D11) +- [ ] 6.2 Full local verification on every lane (native clang and gcc 15, MSVC 14.3 and 14.5, the Windows ARM64 lane, wasip2, wasip3, Emscripten, the constant-time lane, the Linux lint), exceptions on and off; the review; pull requests the owner merges; one CI at the end + +Not tasks of this genesis, each a change of its own library after secure: hash's guard and wipe on +secure's; crypto's callers on secure's names, its copies deleted with no alias; and the place of +the shared test support, once the owner decides (design O1). diff --git a/libraries/secure/openspec/config.yaml b/libraries/secure/openspec/config.yaml new file mode 100644 index 0000000..d370c42 --- /dev/null +++ b/libraries/secure/openspec/config.yaml @@ -0,0 +1,11 @@ +schema: spec-driven + +context: | + This repository holds the OpenSpec proposals of webcpp (github.com/webcpporg), + a superproject of header-only C++20 libraries for native, WASI (wasip2, + wasip3) and Emscripten targets, each library a repository of its own under + libs/, licensed BSL-1.0, "Copyright (c) 2026 WebCpp.org". + The superproject's CODING-GUIDELINES.md holds the rules every library follows + and the decisions of webcpp's design; its AGENTS.md says how to work in the tree. + Everything is written in English; never the em dash, use a plain dash. + This root holds the proposals of the library webcpp::secure: its genesis and its changes. From 677c35624c40fcde3b03bd6bb12d786aaa4c2e6a Mon Sep 17 00:00:00 2001 From: R Date: Tue, 24 Nov 2026 14:19:47 -0300 Subject: [PATCH 2/8] secure: genesis plan (reference/plan.md), accepted; hash's and crypto's migrations folded into the delivery, O1 decided, the wipe's test seam (B9) The plan builds webcpp::secure in nine tasks from reference/prior, then moves hash and crypto onto it, then registers it in the superproject, with the delivery as the controller's checklist. The owner's decisions of 2026-11-24 are recorded: O1 decided (each library keeps its own test support), the migrations of hash and crypto are tasks of this delivery (tasks.md sections 7 and 8). Builder's call B9 moves hash's wipe test seam to secure; the spec gains it and the requirement "One copy in webcpp". --- README.md | 2 +- .../openspec/changes/genesis/.openspec.yaml | 2 +- .../secure/openspec/changes/genesis/design.md | 70 +- .../openspec/changes/genesis/proposal.md | 30 +- .../changes/genesis/reference/STATUS.md | 9 +- .../changes/genesis/reference/plan.md | 1134 +++++++++++++++++ .../changes/genesis/specs/secure/spec.md | 17 +- .../secure/openspec/changes/genesis/tasks.md | 59 +- 8 files changed, 1253 insertions(+), 70 deletions(-) create mode 100644 libraries/secure/openspec/changes/genesis/reference/plan.md diff --git a/README.md b/README.md index 364e63b..8e96474 100644 --- a/README.md +++ b/README.md @@ -63,7 +63,7 @@ tag is placed. | lexical | [genesis](libraries/lexical/openspec/changes/archive/2026-10-09-genesis) | lexical: the lexical forms of JSON Schema's string formats | own | implemented | 0.1.0 | 2026-10-09 | [code](https://github.com/webcpporg/lexical/tree/e286ca4) | | lexical | [strategies](libraries/lexical/openspec/changes/strategies) | lexical: one entry point, strategies and Boost.Regex | own | draft | | | | | pratt | [genesis](libraries/pratt/openspec/changes/archive/2026-10-08-genesis) | pratt: a generic Pratt parser engine for C++20, with a decimal calculator | own | implemented | 0.1.0 | 2026-10-08 | [code](https://github.com/webcpporg/pratt/tree/d78451b) | -| secure | [genesis](libraries/secure/openspec/changes/genesis) | secure: the side-channel and secret-in-memory primitives crypto, hash and codecs share (DIT guard, erase, secret, constant-time blocks), no algorithm | own | proposed | | 2026-11-24 | | +| secure | [genesis](libraries/secure/openspec/changes/genesis) | secure: the side-channel and secret-in-memory primitives crypto, hash and codecs share (DIT guard, erase, secret, constant-time blocks), no algorithm | own | accepted | | 2026-11-24 | | | trystero | [genesis](libraries/trystero/openspec/changes/archive/2026-10-09-genesis) | trystero: serverless WebRTC rooms, wire compatible with Trystero | port of Trystero 0.26.0 | implemented | 0.1.0 | 2026-10-09 | [code](https://github.com/webcpporg/trystero/tree/160f431) | | trystero | [bounded-json-parse](libraries/trystero/openspec/changes/bounded-json-parse) | trystero: bound the text and the objects a room parses | port of Trystero 0.26.0 | draft | | | | | trystero | [shared-connection](libraries/trystero/openspec/changes/archive/2026-11-14-shared-connection) | trystero: one connection shared by the rooms of an app | port of Trystero 0.26.0 | implemented | 0.1.0 | 2026-10-11 | [code](https://github.com/webcpporg/trystero/tree/e9326e94c06cfa9ffdbd0a8d3c8d72b80b3b9b59) | diff --git a/libraries/secure/openspec/changes/genesis/.openspec.yaml b/libraries/secure/openspec/changes/genesis/.openspec.yaml index 076b19b..79160ff 100644 --- a/libraries/secure/openspec/changes/genesis/.openspec.yaml +++ b/libraries/secure/openspec/changes/genesis/.openspec.yaml @@ -5,7 +5,7 @@ webcpp: title: "secure: the side-channel and secret-in-memory primitives crypto, hash and codecs share (DIT guard, erase, secret, constant-time blocks), no algorithm" kind: own port_of: null - status: proposed + status: accepted release: null implementation: null decided: 2026-11-24 diff --git a/libraries/secure/openspec/changes/genesis/design.md b/libraries/secure/openspec/changes/genesis/design.md index 3793553..b35609f 100644 --- a/libraries/secure/openspec/changes/genesis/design.md +++ b/libraries/secure/openspec/changes/genesis/design.md @@ -57,8 +57,8 @@ domain allows, and checked on a constant-time lane; every target webcpp builds f **Non-goals:** any cryptographic algorithm (hashes, ciphers, curves stay in hash and crypto); a wiping allocator or heap secret types (codecs' `secret_string` and `secret_byte_vector` are codecs' own, over secure's erase); memory locking (`mlock`, `VirtualLock`) or guard pages; x86's DOITM (a -kernel setting); WebAssembly's timing (the engine decides); the migration of crypto and hash, -each a change of its own library. +kernel setting); WebAssembly's timing (the engine decides); codecs' use of secure, which is +codecs' genesis's. **Anti-goals:** a cryptographic algorithm in secure; a dependency on any webcpp library but config; a name outside `webcpp::secure` or a header outside `` and ``; @@ -85,9 +85,12 @@ webcpp. their public part in secure and the rest as test support. 7. **The constant-time building blocks codecs needs** (select, a table lookup by masking, constant-time comparisons on bytes), as primitives. -8. **Test support:** secure's own seam and DIT helpers live in secure's `test/support/`; where the - helpers shared by several libraries live waits for the owner's decision on the superproject's - `tools/node-test` and its `webcpp::test` namespace (Open Questions, O1). +8. **Test support:** secure's own seam and DIT helpers live in secure's `test/support/`; the + helpers shared by several libraries' tests stay in each library's own `test/support/` (O1, + decided 2026-11-24). +9. **The migrations are in this delivery** (2026-11-24): hash's guard and wipe, then crypto's every + caller, move to secure after secure's own tasks, hash first since crypto depends on hash; the + genesis had named them follow-up changes. ## Decisions @@ -190,6 +193,13 @@ A C library's plain state (BearSSL's contexts, which crypto wipes with `detail:: erased as a range of one: `erase_secret(std::span(&context, 1))`. Builder's call B1: no second public name for an object, since a span of one says the same and keeps the contract one function. +The wipe has a test seam, hash's `WEBCPP_HASH_DETAIL_TEST_WIPE_RECORD` moved (builder's call B9): +a program built with `WEBCPP_SECURE_TEST_WIPE_RECORD` defined (by its Jamfile, so that every +translation unit agrees) defines `void webcpp::secure::test::wipe_record(void const*, std::size_t) +noexcept`, which `detail::wipe` declares under the macro and calls once its bytes are zero, with +what it zeroed; without the macro nothing is declared or called. hash's tests that check a wipe +(of a keyed hmac, a block, a C library's context) read it, as they read hash's own seam today. + ### D5. `constant_time_equal` `secure::constant_time_equal(first, second)` takes any two contiguous sized ranges whose elements @@ -294,12 +304,12 @@ secure's tests need a seam recorder (counting guards entered, keeping the first' test "a program that set DIT keeps it") and the checkers' marks (D7). They live in secure's own `test/support/`: `timing_seam.hpp`, `timing_dit.hpp`, `constant_time_marks.hpp`, in namespace `webcpp::secure::test`, ported from the withdrawn branch's `tools/node-test` headers and crypto's -lane. crypto, hash and codecs need the same three for their own guards and lanes: whether they -include secure's (making secure's `test/support/` the shared one), keep copies, or include a shared -location in the superproject depends on the owner's pending decision about `tools/node-test` -(renamed, or a library of its own). Until then secure writes only its own; the follow-up changes of -crypto, hash and codecs read the decision (O1). secure's tests keep using `tools/node-test`'s -`` as every library's do. +lane. crypto, hash and codecs need the same three for their own guards and lanes: each keeps or +gains its own copies in its own `test/support/` (O1, decided 2026-11-24): hash keeps its seam +recorder and DIT helper, crypto keeps its seam recorder and its checkers' marks and gains a DIT +helper, each recorder pointed at secure's seam and counting its own library's guards by +`file_name()`. secure's tests keep using `tools/node-test`'s `` as +every library's do. ### D10. Tests @@ -359,15 +369,18 @@ to the owner. change's B2. - **B8:** the convenience header `` includes every header; none brings a heavy dependency (D1). +- **B9:** the wipe's test seam `WEBCPP_SECURE_TEST_WIPE_RECORD` and + `secure::test::wipe_record`, hash's seam moved, so that hash's tests of its wipes keep their + evidence once hash's `detail/wipe.hpp` is gone (D4). ## Risks / Trade-offs -- [hash and crypto keep their copies until their follow-up changes land] -> both changes are - ordered right after secure; until then the copies behave alike, as today, and crypto's - `timing_hash_interop_test` keeps them in step. +- [hash and crypto keep their copies until their migrations land] -> both migrations are tasks of + this delivery, right after secure's own; until each lands the copies behave alike, as today, and + crypto's `timing_hash_interop_test` keeps them in step until hash's migration deletes it. - [hash gains a dependency] -> secure is header-only and depends on config alone, the dependency hash already has; hash's "depends on no other webcpp library" becomes "on config and secure", in - its follow-up. + its migration. - [The optimiser turns a mask into a branch] -> `value_barrier` on every mask a block makes, and the constant-time lane (memcheck and MemorySanitizer see a branch on a marked value) on every compiler that lane runs; dudect natively. @@ -380,20 +393,21 @@ to the owner. ## Migration Plan -Nothing to migrate in secure: it is new. The owner creates `webcpporg/secure` and adds the +Nothing to migrate in secure: it is new. The owner created `webcpporg/secure` and added the submodule; the library is built on its own branch and the superproject's (pointer, -`CODING-GUIDELINES.md` chapter 17's entry, the index page), verified on every local lane, and merged -with one CI at the end. Then, each a change of its own library: hash (its guard and wipe on -secure's, its `engaged` calls unchanged in meaning), crypto (every guard, wipe, erase, comparison, -secret and declassify on secure's; its six headers deleted with no alias; `timing_hash_interop_test` -replaced by a test that nests a guarded hash call in a guarded crypto call; dudect and benches on -`secure::cpu_has_dit()`), and codecs, built on secure from the start. The withdrawn branch's -commits are the worked example of moving every guard site. +`CODING-GUIDELINES.md` chapter 17's entry, the index page). Then, in the same delivery (owner +decision 9): hash (its guard and wipe on secure's, its `engaged` calls unchanged in meaning, its +wipe seam on secure's, B9), then crypto (every guard, wipe, erase, comparison, secret and +declassify on secure's; its six headers deleted with no alias; `timing_hash_interop_test` replaced +by a test that nests a guarded hash call in a guarded crypto call; dudect and benches on +`secure::cpu_has_dit()`). Everything is verified on every local lane and merged with one CI at the +end; codecs is built on secure from the start. The withdrawn branch's commits are the worked +example of moving every guard site. ## Open Questions -- **O1 (owner, pending):** where the test support shared by several libraries' tests lives: the - seam recorder, the DIT helper and the constant-time checkers' marks. secure writes its own in - `test/support/` (D9); whether crypto, hash and codecs include secure's, keep copies, or include - them from the superproject depends on the owner's decision on `tools/node-test` and its - `webcpp::test` namespace (renamed, or a library of its own). +- **O1 (decided by the owner, 2026-11-24):** where the test support shared by several libraries' + tests lives: the seam recorder, the DIT helper and the constant-time checkers' marks. They stay + in each library's own `test/support/` for now: secure's in secure's (D9), and hash and crypto + keep or gain their own copies in theirs. Not in `tools/node-test`, and no `webcpp::core` library + is made for them. diff --git a/libraries/secure/openspec/changes/genesis/proposal.md b/libraries/secure/openspec/changes/genesis/proposal.md index 8d5a904..d193813 100644 --- a/libraries/secure/openspec/changes/genesis/proposal.md +++ b/libraries/secure/openspec/changes/genesis/proposal.md @@ -62,17 +62,18 @@ library of their own, webcpp::secure, and that config stays macros only. `declassify_compile_test` moved, `secret_test`, the constant-time blocks against a plain reference (every 8-bit pair, random wider ones), the allocation test, and the own lane `constant-time` (memcheck, MemorySanitizer, dudect, each with a planted leak that must fail). The - seam recorder and the DIT helper live in secure's own `test/support/`; where the helpers shared by - several libraries' tests live is open, pending the owner's decision on the superproject's - `tools/node-test` (design, Open Questions). + seam recorder, the DIT helper and the checkers' marks live in secure's own `test/support/`, and + hash and crypto keep or gain their own copies in theirs (design O1, decided 2026-11-24). - **Documentation**: the library's page, the guard's coverage table, how to erase, the secret type, the constant-time blocks with their limits, and the changelog. -Not in this change, and stated as its consumers: webcpp::crypto's change that moves every caller to -secure and deletes `crypto::erase_secret`, `crypto::constant_time_equal`, `crypto::secret`, -`detail/timing.hpp`, `detail/wipe.hpp` and `detail/declassify.hpp` with no alias; webcpp::hash's -change that moves its guard and wipe to secure (hash then depends on secure); webcpp::codecs' genesis -uses secure from its first line (amended the same day). +Not in this change: webcpp::codecs' genesis, which uses secure from its first line (amended the +same day). The migrations of hash and crypto, which this paragraph first named as their own +follow-up changes, the owner folded into the same delivery on 2026-11-24, after secure's own tasks +(tasks.md sections 7 and 8): webcpp::hash's guard and wipe move to secure and hash's copies are +deleted (hash then depends on secure), then webcpp::crypto's every caller moves to secure and +`crypto::erase_secret`, `crypto::constant_time_equal`, `crypto::secret`, `detail/timing.hpp`, +`detail/wipe.hpp` and `detail/declassify.hpp` are deleted with no alias. ## Capabilities @@ -98,17 +99,18 @@ None. shared seam of that branch, and crypto's headers and tests that move. To build: the library's repository, `build.jam`, `include/webcpp/secure.hpp`, `include/webcpp/secure/*.hpp`, tests, the constant-time lane, `doc/`, the superproject's pointer, `CODING-GUIDELINES.md` chapter 17's entry - and the index page. + and the index page; then hash and crypto moved onto it. - **Dependencies:** Boost 1.92's headers (Core's `lightweight_test` in tests) and `/webcpp/config//config`. For the constant-time lane: valgrind, MemorySanitizer and dudect as webcpp::crypto's lane uses them. secure depends on no other webcpp library; hash, crypto and codecs depend on it. -- **Status:** approved by the owner on 2026-11-24 (`decided`); it stays `proposed` in the - metadata until `reference/plan.md` carries the plan's code, which `tools/proposals.py` requires - of an `accepted` proposal, and then becomes `accepted`. +- **Status:** approved by the owner on 2026-11-24 (`decided`), and `accepted` the same day once + `reference/plan.md` carried the plan's code, which `tools/proposals.py` requires of an + `accepted` proposal. - **Other proposals:** replaces `libraries/config`'s change `timing-guard`, withdrawn the same day (archived as `2026-11-24-timing-guard`). `libraries/codecs`'s genesis uses secure's guard, erase, - secret and constant-time blocks (its owner decision 14). Follow-up changes, none of them part of - this genesis, after secure: `libraries/hash` (its guard and wipe on secure's) and + secret and constant-time blocks (its owner decision 14). hash's and crypto's migrations, which + the genesis first named follow-up changes, are part of this delivery by the owner's decision of + 2026-11-24 (tasks.md sections 7 and 8): `libraries/hash` (its guard and wipe on secure's) and `libraries/crypto` (every caller on secure's names, its copies deleted with no alias, its `data-independent-timing` requirements read with secure's guard and seam). diff --git a/libraries/secure/openspec/changes/genesis/reference/STATUS.md b/libraries/secure/openspec/changes/genesis/reference/STATUS.md index 4360b20..1d47b02 100644 --- a/libraries/secure/openspec/changes/genesis/reference/STATUS.md +++ b/libraries/secure/openspec/changes/genesis/reference/STATUS.md @@ -1,8 +1,8 @@ # webcpp::secure: where the implementation stands, and what to start from -Written 2026-11-24, with the genesis. Nothing is built in secure's name: there is no repository -`webcpporg/secure` yet (the owner creates it). `prior/` holds the code an implementer ports, exact -copies of files committed elsewhere, none of them renamed yet: +Written 2026-11-24, with the genesis. Nothing is built in secure's name yet. The owner created the +repository `webcpporg/secure` on 2026-11-24 and its submodule `libs/secure`. `prior/` holds the code +an implementer ports, exact copies of files committed elsewhere, none of them renamed yet: | `prior/` | Copied from | What it is | | --- | --- | --- | @@ -27,4 +27,5 @@ copies of files committed elsewhere, none of them renamed yet: The withdrawn branch's commits (config `ba72ad4`, hash `43b6732`, crypto `b0c1f4f`, superproject `83c9a31`) are a worked example of moving every guard site of hash and crypto by a rename, for -their follow-up changes. +their migrations, which the owner folded into this delivery on 2026-11-24 (tasks.md sections 7 +and 8). The plan is `plan.md`, beside this file. diff --git a/libraries/secure/openspec/changes/genesis/reference/plan.md b/libraries/secure/openspec/changes/genesis/reference/plan.md new file mode 100644 index 0000000..2248749 --- /dev/null +++ b/libraries/secure/openspec/changes/genesis/reference/plan.md @@ -0,0 +1,1134 @@ +# secure Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** webcpp::secure, a header-only library holding webcpp's DIT guard, `erase_secret`, +`secret`, `constant_time_equal`, `declassify` and the constant-time building blocks, built, +tested on every lane and documented; then webcpp::hash and webcpp::crypto moved onto it with no copy +and no alias left. + +**Architecture:** the prior code (`reference/prior/`) is ported by mechanical renames into +`libs/secure` (namespace `webcpp::secure`, headers ``, macros +`WEBCPP_SECURE_*`); new code is the generic `constant_time_equal`, the function `declassify`, the +blocks of `constant_time.hpp`, the wipe's test seam (B9) and the constant-time lane. hash migrates +first (crypto depends on hash), then crypto, each keeping its own test support (O1). The +superproject registers the library and its lane; the controller verifies every lane and delivers. + +**Tech Stack:** C++20 header-only, b2 5.5.3, Boost 1.92 (Core's LightweightTest), clang (Apple), +gcc 15, wasi-sdk 34 (wasip2, wasip3), Emscripten 6.0.11, MSVC 14.3 and 14.5 (x64 and arm64 on the +owner's Windows 11 ARM64 VM), Valgrind and clang 18's MemorySanitizer (Linux container), dudect +(crypto's harness, copied), Python tools of the superproject. + +**Spec:** this change, `libraries/secure/openspec/changes/genesis/` of webcpporg/proposals: +`proposal.md`, `design.md` (D1 to D11, B1 to B9, owner decisions 1 to 9, O1 decided, all binding), +`specs/secure/spec.md` (binding), `tasks.md`. Read design.md and spec.md before any task. + +**Paths:** `$W` is the owner's workspace directory, the folder that holds `heavy.sh`, +`msvc-lane/`, `linux-lint/` and this stream's folder `secure/` (a plan in the proposals repository +names no machine path). `$S` is `$W/secure/webcpp`, the superproject worktree on branch +`secure/genesis`; its `libs/secure`, `libs/hash` and `libs/crypto` are each on branch +`secure/genesis` of their repository (bases: secure `e5870a1`, hash `030e757`, crypto `3314a1d`, +superproject `dccffd7` plus `b1972f8`, the submodule). Every command runs from `$S`. Never create +another worktree or tree; never touch `libs/config` or hkdf-pieces' folders. + +**The worked example:** the withdrawn change `timing-guard`, local branches `config/timing-guard` +in `$W/timing-guard/webcpp` (read with `git -C ... show/diff`): config `ba72ad4` (the guard and its +tests, the Jamfile lines), hash `445a403` and `1e0ddf5` (every guard site, its own seam support, +regenerated pages), crypto `c02020d` and `89c3d84` (every guard site, its own seam support, +`timing_nested_hash_test`, dudect, benches) and `4f62e73`'s `timing_nested_hash_test.cpp` (DIT read +inside hkdf through `dit_probe`), superproject `6b39403`, `ae4ef95`, `6e689cb`, `d4206ea` (tools and +guidelines). Its later commits that moved the support into `tools/node-test` (`baf4de3`, +`4f62e73`'s support part, `4803ecd`, `3fd46d6`) are NOT followed (O1), but their +include-anchored `path_in_library` is (below). + +**Commands:** `B2` means +`env -u CPATH -u CPLUS_INCLUDE_PATH -u C_INCLUDE_PATH b2 --user-config=.local/user-config.jam` +(as `$W/hkdf-pieces/lanes/run.sh` runs it). Lanes in this plan: +- native: `B2 toolset=clang `; `B2 toolset=gcc-15 ` +- wasip2: `B2 toolset=clang-wasip2 testing.launcher=tools/boost/asio-wasip2/run.sh ` +- wasip3: `B2 toolset=clang-wasip3 testing.launcher=tools/boost/asio-wasip3/run.sh ` +- Emscripten: `B2 toolset=emscripten ` +- MSVC: `$W/heavy.sh secure $W/msvc-lane/run-lane.sh <14.3|14.5> --tree $W/secure/lane-tree [--arch arm64] -- [variant=release]`, read with `$W/msvc-lane/summarize.sh <14.3|14.5> ` (`new failures:` empty). Commit, then `$W/secure/refresh-tree.sh`, before a run: the lane tree is built from committed heads. +- A whole library from scratch (`b2 -a` over `libs//test libs//example`), the full lints and the MSVC lane are heavy: only through `$W/heavy.sh secure `. + +**The lint step of every task (owner decision):** before reporting DONE, commit, then run +`$W/secure/lint.sh $W/secure/lint-task.log ` +(it refreshes the lane tree itself); fix every finding of one run in the task's own commit +(`: ... lint fix`), run once more; a task reaches review lint-clean. Format C++ first with +`.local/wasi-sdk/bin/clang-format -i `. Deleted files are not passed. + +## Global Constraints + +- English in files; never the em dash character, use "-"; commit messages with no trailer at all + (no Co-Authored-By); never hand-edit CHANGELOG.md or generated files (regenerate with their + generators); "Copyright (c) 2026 WebCpp.org" BSL-1.0 headers; heavy work only through heavy.sh; + implementers run the Linux lint on everything their task touched before DONE; flaky tests and lint + warnings are defects to fix; measurements only on release builds on an idle machine; never contact + upstream projects; merge origin/main into branches, never rebase; no GitHub CI runs (any push's + runs get cancelled). +- Commit subjects in each repository's style: `secure: ...`, `hash: ...`, `crypto: ...`; + superproject `build: ...`, `ci: ...`, `tools: ...`, `guidelines: ...`, and for gitlinks + `libs/secure, libs/hash, libs/crypto: the gitlinks at (, , )`. Never + `git add -A` or `git add libs` in the superproject. +- Names, verbatim from the spec: namespace `webcpp::secure` (with `secure::constant_time`, + `secure::detail`, and `secure::test` for test support and the wipe seam), headers + `` and ``, + ``; include guards `WEBCPP_SECURE__HPP`; macros + `WEBCPP_SECURE_NO_EXCEPTIONS`, `WEBCPP_SECURE_TIMING_COVERED`, `WEBCPP_SECURE_TIMING_ENTERED(where)`, + `WEBCPP_SECURE_CT_VALGRIND`, `WEBCPP_SECURE_CT_MSAN`, `WEBCPP_SECURE_TEST_WIPE_RECORD`; target + `/webcpp/secure//secure`. No name outside `webcpp::secure`; no header of another webcpp library + but config's; no algorithm; every function `noexcept`, none throws. +- The guard's behaviour is the prior header's, unchanged (D2, D3): engaged runs the seam (a test's + build) then sets DIT when the CPU has it and it is clear, clears on destruction only if it set + it; disengaged does nothing, seam included; `isb` after each write; not copyable, not movable; + no DIT instruction without `cpu_has_dit()` but the Windows probe's one read; coverage + `defined(__aarch64__) && (defined(__APPLE__) || defined(__linux__))` and + `defined(_MSC_VER) && defined(_M_ARM64) && !defined(_M_ARM64EC)`; elsewhere an empty class and + both functions `false`. +- Owner decisions: config stays macros only; crypto's `erase_secret`, `constant_time_equal`, + `secret`, wipe and declassify move with NO alias; crypto's and hash's `detail/timing.hpp` and + `detail/wipe.hpp` are deleted; test helpers stay in each library's own `test/support/` (O1), never + `tools/node-test`, no `webcpp::core`; hex helpers stay where they are. +- Generated files, each written by its generator and checked: + - hash: `doc/generated/*`, `doc/backends.adoc`, `doc/measurements.adoc`, `doc/llms.txt` by + `python3 tools/hash/doc_tables.py --write` (check `--check`); `doc/performance.adoc` by + `python3 libs/hash/bench/collect.py --render-only --data libs/hash/doc/measurements.throughput.json --page libs/hash/doc/performance.adoc`. + - crypto: `doc/generated/*`, `doc/llms.txt` and `build.jam`'s defaults block by + `python3 libs/crypto/doc/tables/generate.py --root .` (check `--check`) from + `doc/tables/crypto.json`; `doc/performance.adoc` by + `python3 libs/crypto/bench/collect.py --render-only --data libs/crypto/doc/performance.json --page libs/crypto/doc/performance.adoc`. + - secure: `doc/performance.adoc` by `python3 libs/secure/bench/collect.py` (Task 9). + - Each library's `doc/changelog.adoc` is hand-written (`AGENTS.md` chapter 5: one line per change, + past-tense verb, under "Unreleased"). +- Every test runs with exceptions on and off (`secure-run`, `secure-compile`, `hash-run`, + `crypto-run`). A test that defines a seam includes it before any webcpp header, in every + translation unit of its program (the guard's constructor depends on the macro: ODR). +- The owner's VM: never shut it down, suspend or reconfigure it; `$W/msvc-lane/known-failures.txt` + is never edited. + +## Review Focus + +1. **Integer promotion in the blocks on MSVC at `/W4 /WX` and on 8- and 16-bit types.** `~value`, + `U(0) - bit` and shifts of `std::uint8_t` promote to `int`: a block that forgets a + `static_cast` returns a wrong mask for `uint8_t` or warns C4146/C4244 on MSVC. Task 6's + exhaustive 8-bit test and its 16-bit edges catch the value; Task 6 builds `constant_time_test` + on both MSVC versions, x64 and arm64. +2. **The optimiser turning a mask back into a branch.** clang and gcc at `-O2`/`-Os` may if-convert + and then branch. Task 8's memcheck programs run at `release` and again at + `space` (`ctgrind_space`), natively on clang 18 (the lane) and gcc 15 (Task 8's + extra run), each with the planted branching `select` that must be reported. +3. **`constant_time_equal` on a temporary, on `char` with the high bit set, and on unequal + sizes.** A `std::string_view` of bytes 0x80 to 0xFF (signed `char`), a temporary `secret<32>` + (bound to `const&`, viewed through `bytes()` for the call), a `std::byte` array, and a 31- versus + 32-byte pair (false, no byte read: checked with a sequence whose `data()` is null and size 31). +4. **`lookup` past the end and narrow `Element`s.** `is_equal_mask` over `std::size_t` narrowed to + `std::uint8_t` must stay all ones; an index of `N`, `N + 1` and `SIZE_MAX` yields `Element{}`; + a table of `std::dynamic_extent` and of one entry; Task 6 pins all of them. +5. **MSVC spells `file_name()` with backslashes.** Each library's seam recorder counts its own + guards with `path_in_library`, anchored on `include/webcpp//`, either separator; Task 2 + pins it for secure on the spellings of clang, GCC and MSVC and on near misses + (`include/webcpp/securex/`, `myinclude/webcpp/secure/`, `libs/secure/test/`); Tasks 10 and 11 + pin hash's and crypto's. + +## The renames (Tasks 2 to 5 apply them to `reference/prior/`) + +P1. Paths: `` -> ``; +`` (in the guard) -> ``; +`` -> ``; `` -> +`` for `erase_secret`, `constant_time_equal`, `secret`; `detail/wipe.hpp` -> +``; crypto's `` -> +``; tests' `` -> +`"support/timing_dit.hpp"` and `` -> `"support/timing_seam.hpp"`. +P2. Macros: `WEBCPP_CONFIG_DETAIL_TIMING_GUARD_HPP` -> `WEBCPP_SECURE_TIMING_GUARD_HPP`; +`WEBCPP_CONFIG_DETAIL_TIMING_COVERED` -> `WEBCPP_SECURE_TIMING_COVERED`; +`WEBCPP_CONFIG_DETAIL_TIMING_ENTERED` -> `WEBCPP_SECURE_TIMING_ENTERED`; `WEBCPP_CRYPTO__HPP` -> +`WEBCPP_SECURE__HPP`; test guards `WEBCPP_TEST_TIMING_{SEAM,DIT}_HPP` -> +`WEBCPP_TEST_SECURE_SUPPORT_TIMING_{SEAM,DIT}_HPP`; `WEBCPP_TEST_TIMING_LIBRARY` is dropped +(secure's recorder holds `timing_library = "secure"`). +P3. Namespaces: `webcpp::config::detail::{timing_guard, cpu_has_dit, dit_is_set}` -> +`webcpp::secure::{...}`; `webcpp::config::detail::{dit_bit, write_dit, dit_register, +isb_full_system, status_illegal_instruction, probe_dit}` -> `webcpp::secure::detail::{...}` (inside +`webcpp::secure` the guard calls them as `detail::`); `webcpp::crypto` -> `webcpp::secure`; +`webcpp::crypto::detail` -> `webcpp::secure::detail`; tests' `webcpp::test` (the recorder, the DIT +helper) -> `webcpp::secure::test`. +P4. Text: refusal messages `"webcpp::crypto: ..."` -> `"webcpp::secure: ..."`; comments "config's +guard", "config's internal header" -> "secure's guard", "the public header of webcpp::secure"; the +guard header's paragraph "It is config's internal header ... does not include it." becomes "It is +public: crypto, hash and codecs hold it, and a program may hold one around its own constant-time +code."; crypto's `detail::timing_guard const timing_scope;` -> `timing_guard const timing_scope;`; +`detail::wipe_object(bytes_)` -> `detail::wipe(bytes_.data(), bytes_.size())` (secure has no +`wipe_object`, B1); crypto's `detail::dependent_false` is defined in `erase_secret.hpp`'s +`secure::detail` (`template inline constexpr bool dependent_false = false;`). +P5. Tests: `config-run`/`crypto-run` -> `secure-run`; `config-compile` -> `secure-compile`; crypto's +`$(OPTIMISED)` is copied as is. + +--- + +### Task 1: The library's skeleton and configuration + +Model tier: standard (multi-file, conventions). Covers tasks.md 1.1, 1.2. + +**Files:** +- Create (libs/secure): `meta/libraries.json`, `build.jam`, `AGENTS.md`, + `include/webcpp/secure.hpp`, `include/webcpp/secure/config.hpp`, `test/Jamfile`, + `test/config_test.cpp`, `test/.clang-tidy`, `example/Jamfile`, `example/.clang-tidy`, + `doc/Jamfile`, `doc/secure.adoc`, `doc/changelog.adoc` +- Modify (libs/secure): `README.md` (how to build and test inside the superproject, where its page + is published; it keeps "being built" until Task 9) +- Copy: `test/.clang-tidy` and `example/.clang-tidy` from libs/hash (the same reasons apply) + +**Interfaces:** +- Produces: target `/webcpp/secure//secure`; `` (include guard + `WEBCPP_SECURE_CONFIG_HPP`, includes `` first, defines + `WEBCPP_SECURE_NO_EXCEPTIONS` when `WEBCPP_HAS_EXCEPTIONS` is undefined or a developer defines it; + under `__MRDOCS__` the documented define-then-undef of xactor's `config.hpp`); test rules + `secure-run` and `secure-compile` (each also as `_no_exceptions` with + `off`). + +- [ ] **Step 1: Write the failing test.** `test/config_test.cpp` is hash's skeleton + `config_test.cpp` (`git -C libs/hash show 59db86a:test/config_test.cpp`) with `HASH` -> `SECURE`, + `hash` -> `secure`, and without the `WEBASSEMBLY` and tag checks (secure has neither); it also + checks `#ifndef WEBCPP_VERSION #error ...`. `test/Jamfile`: + +```jam +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/secure//secure ; + +import webcpp ; + +webcpp.targets native wasip2 wasip3 emscripten ; + +# Every program that runs, runs with exceptions on and off, and every check +# that compiles, compiles both ways: the second has the suffix _no_exceptions +# and is built with exception-handling=off. +rule secure-run ( name : sources + : requirements * : targets * ) +{ + webcpp.run $(name) : $(sources) : $(requirements) : $(targets) ; + webcpp.run $(name)_no_exceptions : $(sources) + : $(requirements) off : $(targets) ; +} +rule secure-compile ( name : sources + : requirements * : targets * ) +{ + webcpp.compile $(name) : $(sources) : $(requirements) : $(targets) ; + webcpp.compile $(name)_no_exceptions : $(sources) + : $(requirements) off : $(targets) ; +} + +webcpp.headers-alone secure : ../include ; + +# config.hpp defines WEBCPP_SECURE_NO_EXCEPTIONS exactly when webcpp has no +# exceptions, keeps it when a developer defines it, and defines it when +# WEBCPP_NO_EXCEPTIONS is. +webcpp.compile config : config_test.cpp ; +webcpp.compile config_no_exceptions : config_test.cpp : off ; +webcpp.compile config_all_off : config_test.cpp + : WEBCPP_NO_EXCEPTIONS WEBCPP_TEST_SECURE_ALL_OFF ; +webcpp.compile config_developer_defined : config_test.cpp + : WEBCPP_SECURE_NO_EXCEPTIONS WEBCPP_TEST_SECURE_DEVELOPER_DEFINED ; +``` + +- [ ] **Step 2: Run it, expect failure.** `B2 toolset=clang libs/secure/test//config` fails: + `/webcpp/secure//secure` does not exist. + +- [ ] **Step 3: Write the skeleton.** `build.jam`: hash's at `59db86a` with `hash` -> `secure`, its + comment "secure: the side-channel and secret-in-memory primitives webcpp's libraries share; a + program names /webcpp/secure//secure: `exe app : app.cpp /webcpp/secure//secure ;`", the alias + `alias secure : : : : include /boost//headers /webcpp/config//config ;` + between `# tag::secure[]` and `# end::secure[]`. `meta/libraries.json`: key and name `secure`, + authors and maintainers as hash's, `"description": "The side-channel and secret-in-memory primitives webcpp's libraries share: the DIT timing guard, erase_secret, secret, constant_time_equal, declassify and constant-time building blocks, no algorithm."`, + `"category": ["Cryptography"]`, `"cxxstd": "20"`, `"port-of": null`. `config.hpp`: xactor's + (`libs/xactor/include/webcpp/xactor/config.hpp`) with `XACTOR` -> `SECURE`, its doc comment + saying secure raises no exception and every function is `noexcept`. `secure.hpp`: the + convenience header, includes `config.hpp` (each later task adds its header). `example/Jamfile` + and `doc/Jamfile`: hash's skeleton's with `secure` (`webcpp.doc secure : secure.adoc ;`, + `webcpp.reference secure ;`). `doc/secure.adoc`: hash's skeleton page's frame (title "secure: + side-channel and secret-in-memory primitives for {cpp}", the reference section, the changelog + include), one paragraph of what secure is and is not. `doc/changelog.adoc`: hash's skeleton's + form, "Unreleased" with "Added webcpp::secure's skeleton and configuration." `AGENTS.md`: hash's + skeleton's form: what secure is (own, no algorithm, the primitives crypto, hash and codecs + share), cautions (tests through `secure-run`; a test that defines a seam includes it first; + `detail` is not API: another library's header never includes it, test code may call + `secure::detail::write_dit`, ruling R1). + +- [ ] **Step 4: Run.** `B2 toolset=clang libs/secure/test libs/secure/example`, + `B2 toolset=gcc-15 libs/secure/test`, `B2 toolset=clang-wasip2 testing.launcher=tools/boost/asio-wasip2/run.sh libs/secure/test`, + `B2 toolset=emscripten libs/secure/test`, `B2 libs/secure/doc doc` (secure's page and the index, + which lists secure from `meta/libraries.json`). Expected: pass. + +- [ ] **Step 5: Commit, lint.** secure: `secure: the library's skeleton, its configuration and the test rules secure-run and secure-compile`. Lint step with every file created. + +--- + +### Task 2: The guard, its test support and its tests + +Model tier: cheap (complete renames of prior code). Covers tasks.md 2.1 (the Windows branch is +ported here with the rest and verified in Task 3). + +**Files:** +- Create: `include/webcpp/secure/timing_guard.hpp` from + `reference/prior/config/include/webcpp/config/detail/timing_guard.hpp` by P1 to P4, Windows + branch included +- Create: `test/support/timing_seam.hpp` from `reference/prior/node-test/include/webcpp/test/timing_seam.hpp`, + `test/support/timing_dit.hpp` from `.../timing_dit.hpp`, by P1 to P3 +- Create: `test/timing_seam_support_test.cpp` (Step 1) +- Create: `test/timing_guard_{,nesting_,seam_,threads_,windows_}test.cpp` from + `reference/prior/config/test/` by P1 to P5; `test/timing_guard_header_test.cpp` from + `git -C $W/timing-guard/webcpp/libs/config show ba72ad4:test/timing_guard_header_test.cpp` by the + same renames (it checks `WEBCPP_SECURE_TIMING_GUARD_HPP`, `WEBCPP_VERSION`, and the coverage + conditions above, Windows included) +- Modify: `test/Jamfile`, `include/webcpp/secure.hpp` + +**Interfaces:** +- Produces (every later task uses exactly these): + +```cpp +// +// WEBCPP_SECURE_TIMING_COVERED defined (to 1) where the guard acts +// WEBCPP_SECURE_TIMING_ENTERED(where) the seam, defined by a test alone before its first include +namespace webcpp::secure { +[[nodiscard]] inline bool cpu_has_dit() noexcept; +[[nodiscard]] inline bool dit_is_set() noexcept; +class timing_guard { +public: + explicit timing_guard(bool engaged = true) noexcept; // without the seam + explicit timing_guard(bool engaged = true, + std::source_location where = std::source_location::current()) noexcept; // with it + ~timing_guard(); // copy and move deleted +}; +namespace detail { // where WEBCPP_SECURE_TIMING_COVERED; test code may call them (R1) +inline constexpr std::uint64_t dit_bit = std::uint64_t{1} << 24U; +inline void write_dit(std::uint64_t dit_value) noexcept; +} +} +// test/support/timing_seam.hpp, namespace webcpp::secure::test: timing_all_entries, +// timing_entries (secure's own guards), timing_first_entry, timing_last_entry, +// timing_library = "secure", path_separator, path_in_library (anchored on include/webcpp//), +// timing_entered(std::source_location const&), and +// #define WEBCPP_SECURE_TIMING_ENTERED(where) (::webcpp::secure::test::timing_entered(where)) +// test/support/timing_dit.hpp: webcpp::secure::test::force_dit(bool) noexcept +``` + +- [ ] **Step 1: Write the failing tests.** Port the six tests and the two support headers. The + recorder's `#error` checks `WEBCPP_SECURE_TIMING_GUARD_HPP` ("must be included before any webcpp + header"); the `WEBCPP_TEST_TIMING_LIBRARY` check goes. `timing_guard_seam_test.cpp` keeps its own + seam, as the prior's. A new `test/timing_seam_support_test.cpp` includes + `"support/timing_seam.hpp"` first and checks the recorder itself: a guard declared in the test + raises `timing_all_entries` by one and `timing_entries` by none (the test's file is not under + `include/webcpp/secure/`), `timing_first_entry` names the test's function; and + `path_in_library_spellings()`, `path_in_library(path, "secure")` true for + `/w/libs/secure/include/webcpp/secure/timing_guard.hpp`, `../include/webcpp/secure/x.hpp`, + `include/webcpp/secure/x.hpp`, `C:\t\a\libs\secure\include\webcpp\secure\x.hpp`, + `C:\t\a\include\webcpp/secure\detail\wipe.hpp`; false for `/w/libs/secure/test/x_test.cpp`, + `/w/include/webcpp/securex/x.hpp`, `/w/myinclude/webcpp/secure/x.hpp`, + `/w/include/webcpp/crypto/x.hpp`, `/w/include/webcpp/secure`. `test/Jamfile` gains (texts of the + prior Jamfile's comments with secure's names): + +```jam +secure-compile timing_guard_header : timing_guard_header_test.cpp ; +secure-run timing_guard : timing_guard_test.cpp ; +secure-run timing_guard_nesting : timing_guard_nesting_test.cpp ; +secure-run timing_guard_seam : timing_guard_seam_test.cpp ; +secure-run timing_guard_threads : timing_guard_threads_test.cpp + : multi : native ; +secure-run timing_guard_windows : timing_guard_windows_test.cpp ; +# The test support's recorder: what it counts, and which paths are secure's. +secure-run timing_seam_support : timing_seam_support_test.cpp ; +``` + +- [ ] **Step 2: Run, expect failure.** `B2 toolset=clang libs/secure/test//timing_guard_header`: + fails, `` not found. + +- [ ] **Step 3: Port the header** by P1 to P4; `secure.hpp` includes it. + +- [ ] **Step 4: Run.** `B2 toolset=clang libs/secure/test`, `B2 toolset=gcc-15 libs/secure/test`, + wasip2, wasip3 and Emscripten lanes over `libs/secure/test`. Expected: pass; on this Mac + (arm64, FEAT_DIT) the covered path runs; on WebAssembly `std::is_empty_v`. + Then the grep `grep -rnE 'CONFIG_DETAIL|config::detail|webcpp/test/timing' libs/secure` prints + nothing. + +- [ ] **Step 5: Commit, lint.** `secure: timing_guard, cpu_has_dit and dit_is_set, the DIT guard moved from config's withdrawn change, with its seam, its test support and its tests`. Lint step. + +--- + +### Task 3: Windows on ARM64 + +Model tier: standard (VM runs, judgment on failures). Covers tasks.md 2.2. + +**Files:** none planned; a fix, if a run fails, goes to `timing_guard.hpp` or a test, with its +reason in the commit. + +- [ ] **Step 1: The lanes, debug.** After `$W/secure/refresh-tree.sh`, each of: + +```bash +H="$W/heavy.sh secure"; L=$W/msvc-lane/run-lane.sh; T=$W/secure/lane-tree +$H $L 14.3 --tree $T --arch arm64 -- libs/secure/test +$H $L 14.5 --tree $T --arch arm64 -- libs/secure/test +$H $L 14.3 --tree $T -- libs/secure/test +$H $L 14.5 --tree $T -- libs/secure/test +``` + Expected (`summarize.sh`): every secure test and its `_no_exceptions` twin passed, `new + failures:` empty; on arm64 `timing_guard_windows` runs its Windows branch (`cpu_has_dit()` true, + DIT kept across ten sleeps), `timing_guard_header` holds the Windows coverage; on x64 the guard is + empty. +- [ ] **Step 2: The lanes, release** (the withdrawn change never ran one): the two arm64 lines + again with `variant=release` after the targets. Expected: as Step 1. +- [ ] **Step 3: Record.** The four consoles' paths and counts go in the task report (Task 9's page + cites the coverage as verified on MSVC 14.3 and 14.5, debug and release); `known-failures.txt` is + not edited. A failure is fixed in secure, committed (`secure: ...`), and Steps 1-2 re-run. + +--- + +### Task 4: The wipe, `erase_secret` and `secret` + +Model tier: cheap. Covers tasks.md 3.1, 3.2. + +**Files:** +- Create: `include/webcpp/secure/detail/wipe.hpp` (from crypto's `detail/wipe.hpp` by P1 to P3, + without `wipe_object`, with the seam below), `include/webcpp/secure/erase_secret.hpp`, + `include/webcpp/secure/secret.hpp` (from `reference/prior/crypto/include/` by P1 to P4) +- Create: `test/erase_secret_test.cpp` (from `reference/prior/crypto/test/` by P1 to P5), + `test/secret_test.cpp` (from `git -C libs/crypto show 3314a1d:test/secret_test.cpp` by P1 to P5), + `test/wipe_record_test.cpp`, `test/messages/Jamfile`, + `test/messages/{erase_secret_const_range,secret_of_no_bytes}/` (from crypto's + `test/messages/` by P1 to P4, project requirement `/webcpp/secure//secure`) +- Modify: `test/Jamfile`, `include/webcpp/secure.hpp` + +**Interfaces:** +- Consumes: Task 1's config. +- Produces: + +```cpp +namespace webcpp::secure { +namespace detail { +inline void wipe(void* wiped_data, std::size_t byte_count) noexcept; // volatile stores, then + // atomic_signal_fence +template inline constexpr bool dependent_false = false; +template concept erasable_range = /* crypto's, unchanged */; +} +template requires detail::erasable_range +void erase_secret(Range&& erased_range) noexcept; // + the refusing overload, P4 message +template class secret; // crypto's interface, unchanged (D6) +#ifdef WEBCPP_SECURE_TEST_WIPE_RECORD +namespace test { void wipe_record(void const* wiped_data, std::size_t byte_count) noexcept; } +#endif +} +``` + `detail::wipe` calls `test::wipe_record(wiped_data, byte_count)` after the fence, under the macro + only (hash's `detail/wipe.hpp` is the model of the seam's text). `secret`'s three wipes and its + destructor call `detail::wipe(bytes_.data(), N)`. + +- [ ] **Step 1: Write the failing tests.** The ported two, and `test/wipe_record_test.cpp` (the + spec's scenario "A wipe reported to a test"): it defines + `void webcpp::secure::test::wipe_record(void const*, std::size_t) noexcept` recording each + call's address, size and whether those bytes read zero at the call; it erases a + `std::array` filled with 0xA5 (one record: its `data()`, 32, zero), destroys a + `secret<16>` written with 0x5A in placement storage (one record: the storage's address, 16, + zero), moves one `secret<16>` into another (records for the source after the move and for the + target before it takes the bytes), and erases a `std::span(&context, 1)` of a + `struct context { std::uint64_t key[4]; }` (one record, `sizeof(context)`). `test/Jamfile`: + +```jam +OPTIMISED = speed emscripten:off ; +# secure::erase_secret zeroes the bytes of any contiguous range the program may +# write, and a buffer erased as its scope ends stays zero: optimised, with every +# call inlined, where a wipe the compiler could drop as a dead store would be. +secure-run erase_secret : erase_secret_test.cpp : $(OPTIMISED) full ; +# secret: not copyable, moves wipe the source, the destructor wipes the +# storage; optimised and inlined as erase_secret's. +secure-run secret : secret_test.cpp : $(OPTIMISED) full ; +# The wipe's test seam (B9): every wipe reported once, its bytes already zero. +secure-run wipe_record : wipe_record_test.cpp + : WEBCPP_SECURE_TEST_WIPE_RECORD ; +build-project messages ; +``` + `test/messages/Jamfile` builds `erase_secret_const_range` (compile-diagnostic, native wasip2 + wasip3, `alone`) and `secret_of_no_bytes` (native wasip2 wasip3), their `expected-error` texts + saying `webcpp/secure/...hpp` and `webcpp::secure:`. + +- [ ] **Step 2: Run, expect failure.** `B2 toolset=clang libs/secure/test//erase_secret`: the + header is not found. +- [ ] **Step 3: Port the headers** (P1 to P4, the seam above); `secure.hpp` includes + `erase_secret.hpp` and `secret.hpp`. +- [ ] **Step 4: Run** `libs/secure/test` on native clang, gcc-15, wasip2, wasip3 and Emscripten. + Expected: pass, the messages included (clang lanes). +- [ ] **Step 5: Commit, lint.** `secure: erase_secret and secret, moved from crypto, over secure's wipe and its test seam`. Lint step. + +--- + +### Task 5: `constant_time_equal` and `declassify` + +Model tier: standard (new generic interface). Covers tasks.md 3.3, 3.4. + +**Files:** +- Create: `include/webcpp/secure/constant_time_equal.hpp`, `include/webcpp/secure/declassify.hpp` +- Create: `test/constant_time_equal_test.cpp` (from `reference/prior/crypto/test/` by P1 to P5, + extended below), `test/declassify_compile_test.cpp` (from prior, extended below), + `test/support/constant_time_marks.hpp`, + `test/support/valgrind_stub/valgrind/memcheck.h` (crypto's stub by P2, its comment naming + secure's `declassify`; it adds `VALGRIND_MAKE_MEM_UNDEFINED`, `VALGRIND_GET_VBITS` (returns 0) + and `VALGRIND_CHECK_VALUE_IS_DEFINED` reading their arguments, for the marks header) +- Modify: `test/Jamfile`, `include/webcpp/secure.hpp` + +**Interfaces:** +- Consumes: Task 2's guard and recorder, Task 4's `secret`. +- Produces: + +```cpp +namespace webcpp::secure { +namespace detail { +template // std::uint8_t, unsigned char, char, std::byte (cv dropped) +concept byte_element = std::same_as, std::uint8_t> || + std::same_as, unsigned char> || std::same_as, char> || + std::same_as, std::byte>; +template // a contiguous sized range of byte_element, or a type whose bytes() gives one +concept byte_sequence = + (std::ranges::contiguous_range && std::ranges::sized_range && + byte_element>) || + requires(T const& value) { { value.bytes() } -> std::convertible_to>; }; +} +template + requires detail::byte_sequence && detail::byte_sequence +[[nodiscard]] bool constant_time_equal(First const& first, Second const& second) noexcept; + +template + requires std::is_trivially_copyable_v && (!std::is_const_v) +void declassify(T& value) noexcept; +} +// test/support/constant_time_marks.hpp, namespace webcpp::secure::test: under +// WEBCPP_SECURE_CT_VALGRIND `struct memcheck`, under WEBCPP_SECURE_CT_MSAN +// `struct memory_sanitizer`, each { exact_subtraction; reads_destroyed; +// mark_secret(std::span); mark_public(std::span); +// std::optional traced(std::span); verdict(bool const&); } +// (crypto's ctgrind_test.cpp and msan_test.cpp structs, moved), plus +// template bool carries_mark(std::span) (crypto's paths.hpp). +``` + `constant_time_equal`: a guard first (`timing_guard const timing_scope;`); each operand viewed as + its `bytes()` when it has one, else as its range; sizes differ -> `false` without reading; else + every element read through `static_cast(element)` (no `reinterpret_cast`), XOR + accumulated with OR in `unsigned volatile`, reduced as crypto's `((total - 1U) >> 8U) & 1U`. + Includes no Boost.Hash2 header. `declassify`: empty in a program's build and including nothing; + under `WEBCPP_SECURE_CT_VALGRIND` `static_cast(VALGRIND_MAKE_MEM_DEFINED(&value, sizeof value))` + with ``; under `WEBCPP_SECURE_CT_MSAN` `__msan_unpoison(&value, sizeof value)` + with ``; both defined -> `#error "define WEBCPP_SECURE_CT_VALGRIND or WEBCPP_SECURE_CT_MSAN, not both"`. + +- [ ] **Step 1: Write the failing tests.** `constant_time_equal_test.cpp` includes + `"support/timing_seam.hpp"` first and checks, besides the prior's cases: a 32-byte sequence + against itself and against each of its 256 one-bit flips, as `std::span`, + `std::array`, `std::array`, `secret<32>` (lvalue and a temporary + from a function), `std::string_view` holding bytes 0x80 to 0x9F, and `boost::hash2::digest<32>` + (mixed pairs too: digest against array, secret against span); only the identical compare equal; + 31 against 32 bytes is `false`, and so is a null `data()` of size 31 against 32 (sizes compared + first); two empty spans are equal; each call raises `timing_entries` by exactly one and its + `timing_first_entry` names `constant_time_equal`; static_asserts that a `std::list`, a + `std::vector` and an `int` are not `detail::byte_sequence`. + `declassify_compile_test.cpp`: includes `` and every header, defines nothing + itself; with the stub it calls `declassify` on a `bool`, a `std::uint32_t` and a + `std::array` and branches on each; static_asserts that `declassify` is not + callable on a `const bool` or a `std::string`. `test/Jamfile`: + +```jam +# constant_time_equal over any two byte sequences, its guard through the seam. +secure-run constant_time_equal : constant_time_equal_test.cpp ; +# declassify with the memcheck build's marks, on every lane, against a stand-in +# for Valgrind's header; and with MemorySanitizer's under clang natively. +secure-run declassify_compile : declassify_compile_test.cpp + : WEBCPP_SECURE_CT_VALGRIND support/valgrind_stub ; +secure-compile declassify_compile_msan : declassify_compile_test.cpp + : WEBCPP_SECURE_CT_MSAN gcc:no msvc:no + : native ; +``` + +- [ ] **Step 2: Run, expect failure.** `B2 toolset=clang libs/secure/test//constant_time_equal`. +- [ ] **Step 3: Write both headers** (interfaces above; doc comments as crypto's, P4); the marks + header moves crypto's `memcheck` and `memory_sanitizer` structs and `carries_mark` verbatim but + for P3; `secure.hpp` includes both headers. +- [ ] **Step 4: Run** `libs/secure/test` on all five local lanes. Expected: pass; `grep -n hash2 + libs/secure/include -r` prints nothing. +- [ ] **Step 5: Commit, lint.** `secure: constant_time_equal over any two byte sequences, and declassify with its checkers' marks as test support`. Lint step. + +--- + +### Task 6: The constant-time building blocks + +Model tier: most capable (barriers, promotions, MSVC, constexpr). Covers tasks.md 4.1. + +**Files:** +- Create: `include/webcpp/secure/constant_time.hpp`, `test/constant_time_test.cpp` +- Modify: `test/Jamfile` (`secure-run constant_time : constant_time_test.cpp ;`), + `include/webcpp/secure.hpp` + +**Interfaces:** +- Produces, verbatim from D8, every function `constexpr` and `noexcept`: + +```cpp +namespace webcpp::secure::constant_time { +template constexpr U value_barrier(U value) noexcept; +template constexpr U mask_from_bit(U bit) noexcept; +template constexpr U is_zero_mask(U value) noexcept; +template constexpr U is_equal_mask(U first, U second) noexcept; +template constexpr U is_less_mask(U first, U second) noexcept; +template constexpr U is_in_range_mask(U value, U low, U high) noexcept; +template constexpr U select(U mask, U when_set, U when_clear) noexcept; +template +constexpr Element lookup(std::span table, std::size_t index) noexcept; +constexpr void select_bytes(std::uint8_t mask, std::span destination, + std::span when_set, + std::span when_clear) noexcept; +constexpr std::uint8_t equal_mask(std::span first, + std::span second) noexcept; +constexpr std::uint8_t is_zero_mask(std::span bytes) noexcept; +constexpr std::uint8_t less_mask(std::span first, + std::span second) noexcept; // big-endian +} +``` + The algorithms (BoringSSL's `constant_time_*`), each operation cast back to `U` (Review Focus 1), + with `bits = std::numeric_limits::digits` and `msb(x) = x >> (bits - 1)`: + - `value_barrier`: `if (std::is_constant_evaluated()) return value;` then, on GCC and clang but + not WebAssembly, `__asm__("" : "+r"(value));`; on MSVC and WebAssembly (`__wasm__`) a round trip + through a `U volatile` local (ruling R6). + - `mask_from_bit(bit) = value_barrier(U(U(0) - bit))`; `is_zero_mask(v) = mask_from_bit(msb(U(~v & U(v - 1))))`; + `is_equal_mask(a, b) = is_zero_mask(U(a ^ b))`; + `is_less_mask(a, b) = mask_from_bit(msb(U(a ^ U(U(a ^ b) | U(U(a - b) ^ a)))))`; + `is_in_range_mask(v, lo, hi) = U(U(~is_less_mask(v, lo)) & U(~is_less_mask(hi, v)))`; + `select(m, s, c) = U(U(value_barrier(m) & s) | U(U(~value_barrier(m)) & c))`. + - `lookup`: `Element result{}`; for every `i` of the table, in order, + `result |= table[i] & static_cast(is_equal_mask(i, index))`. + - `select_bytes`: `BOOST_ASSERT` on equal sizes; unequal -> return without writing; else each + byte `select(mask, s[i], c[i])`. + - `equal_mask`, `is_zero_mask` (bytes): unequal sizes -> 0 without reading (`BOOST_ASSERT` + first); OR of XORs (of bytes), then `is_zero_mask`. + - `less_mask`: unequal sizes -> 0 without reading; from the last byte to the first, + `std::uint16_t difference = first[i] - second[i] - borrow; borrow = (difference >> 8) & 1`; + the result `mask_from_bit(borrow)`. + +- [ ] **Step 1: Write the failing test** `constant_time_test.cpp`, with a plain reference + `template constexpr U reference_mask(bool on) { return on ? U(~U(0)) : U(0); }`: + - every pair `a, b` of `std::uint8_t`: `mask_from_bit(U(a & 1)) == reference_mask(a & 1)`, + `is_zero_mask(a) == reference_mask(a == 0)`, `is_equal_mask(a, b) == reference_mask(a == b)`, + `is_less_mask(a, b) == reference_mask(a < b)`, `select(reference_mask(b & 1), a, U(~a))` + equals `(b & 1) ? a : U(~a)`, `value_barrier(a) == a`; + - every triple of `std::uint8_t`: `is_in_range_mask(v, lo, hi) == reference_mask(lo <= v && v <= hi)`; + - `std::uint16_t`, `std::uint32_t`, `std::uint64_t`: the edges {0, 1, 2, max/2, max/2 + 1, + max - 1, max} in every pair (triple for the range), then 2^16 random values from + `std::mt19937_64{20261124}`, same checks; + - `lookup` over a 64-entry `std::uint8_t` table (`i * 7 + 3`) and a 32-entry `std::uint32_t` + table at every index, at 64, 65 and `SIZE_MAX` (-> 0), over a `std::span<..., std::dynamic_extent>`, + and over a one-entry table; + - byte comparisons over random sequences of 0, 1, 31 and 32 bytes and their edges (all 0x00, + all 0xFF, differing only in the first or the last byte): `equal_mask` vs `std::ranges::equal`, + `is_zero_mask` vs `std::ranges::all_of(== 0)`, `less_mask` vs + `std::ranges::lexicographical_compare` (big-endian of equal sizes); `select_bytes` with + `mask` 0 and 0xFF writes `when_clear` or `when_set` exactly; + - `static_assert`s evaluating `select`, `is_in_range_mask`, `lookup` and `equal_mask` in constant + expressions; `bool` refused, through a concept probe + `template concept maskable = requires(U v) { constant_time::is_equal_mask(v, v); };` + with `static_assert(maskable && !maskable && !maskable)`. +- [ ] **Step 2: Run, expect failure.** `B2 toolset=clang libs/secure/test//constant_time`. +- [ ] **Step 3: Write `constant_time.hpp`** (above; Doc Comments say what each block covers and + what the compiler may still do, D8); `secure.hpp` includes it. +- [ ] **Step 4: Run** `libs/secure/test` on all five local lanes, and the MSVC lanes of Task 3 on + `libs/secure/test//constant_time` (14.3 and 14.5, x64 and arm64, debug). Expected: pass, no + warning (`/W4 /WX`). +- [ ] **Step 5: Commit, lint.** `secure: the constant-time building blocks, masks, select, lookup and byte comparisons, checked against a plain reference`. Lint step. + +--- + +### Task 7: No heap, the convenience header, a user's Jamfile + +Model tier: cheap. Covers tasks.md 4.2 and the spec's scenario "A program that erases a buffer +builds nothing". + +**Files:** +- Create: `test/allocation_test.cpp` (counting `operator new` from + `libs/crypto/test/support/counting.hpp`'s form, copied into `test/support/counting.hpp` by P3), + `test/convenience_header_test.cpp` +- Create (superproject): `tools/test/secure_jamfiles_test.py` (crypto_jamfiles_test.py's form, + libraries `('config', 'secure')`), `tools/test/fixtures/secure_jamfiles/program/` + (`Jamfile`: `exe app : app.cpp /webcpp/secure//secure ;`; `app.cpp` includes + ``, holds a `secure::timing_guard`, compares two buffers with + `secure::constant_time_equal`, erases one with `secure::erase_secret`, prints `equal` and + `erased`; outcome: targets native wasip2 wasip3 emscripten, build succeeds, run prints both + lines), `program_no_exceptions/` (the same with `off` in its `exe`) +- Modify: `test/Jamfile` + +- [ ] **Step 1: Write the failing tests.** `allocation_test.cpp` calls every function of the + library (each block for `std::uint8_t` and `std::uint64_t`, `lookup`, the byte comparisons, + `select_bytes`, `constant_time_equal` on every operand kind of Task 5, `erase_secret`, + `secret<32>`'s construction, move, `clone`, `bytes`, destruction, a guard engaged and + disengaged, `cpu_has_dit`, `dit_is_set`, `declassify`) and checks the counter is zero after each. + `convenience_header_test.cpp` includes `` alone and names one function of + each header. Jamfile: `secure-run allocation : allocation_test.cpp ;`, + `secure-run convenience_header : convenience_header_test.cpp ;`. +- [ ] **Step 2: Run, expect failure** (missing files); then write the tests' bodies until they + pass; no library change is expected (a failure here is a finding in the library). +- [ ] **Step 3: Run** `libs/secure/test` on all five local lanes and + `python3 tools/test/secure_jamfiles_test.py`. Expected: pass. +- [ ] **Step 4: Commit, lint.** secure: `secure: no function allocates, and the convenience header compiles alone`; superproject: `tools: secure_jamfiles_test, a user's Jamfile of webcpp::secure on every target`. Lint step. + +--- + +### Task 8: The constant-time lane + +Model tier: most capable (checkers' semantics, planted leaks, CI wiring). Covers tasks.md 5.1. + +**Files (libs/secure/test/constant_time/):** +- Create: `Jamfile`, `ctgrind_test.cpp`, `ctgrind_planted_test.cpp` (`#include "ctgrind_test.cpp"` + with its NOLINT, as crypto's), `msan_test.cpp`, `msan_planted_test.cpp`, `paths.hpp`, + `dudect.hpp` (crypto's `test/constant_time/dudect.hpp` copied, P3, its DIT report on + `secure::cpu_has_dit()` and `secure::dit_is_set()` under `WEBCPP_SECURE_TIMING_COVERED`), + `dudect_test.cpp`, `dudect_planted_test.cpp`, `dudect_harness_test.cpp` (crypto's, P3), + `dudect_judge.py` (crypto's; only its docstring changes), `valgrind.mjs` (crypto's without the + three suppression files), `msan_report.mjs` (crypto's), `package.json` and `package-lock.json` + (name `webcpp-secure-constant-time`) +- Modify: `libs/secure/test/Jamfile` (`build-project constant_time ;`) +- Modify (superproject): `tools/ci/matrix.py` (`OWN_LANE_PACKAGES` gains + `('secure', 'constant-time', 'native'): ('valgrind', 'llvm-18', 'libclang-rt-18-dev')` and its + comment names secure), `tools/ci/matrix_test.py` (its assertion on `OWN_LANE_PACKAGES` and the + lint-packages expectation), `.github/workflows/library.yml` (the "Judge dudect" step runs for + `matrix.lane == 'constant-time' && (matrix.library == 'crypto' || matrix.library == 'secure')` + and calls `libs/${{ matrix.library }}/test/constant_time/dudect_judge.py`; its comment says so), + `tools/test/secure_dudect_judge_test.py` (new: imports `crypto_dudect_judge_test`, sets its + `JUDGE` to secure's judge and runs its `main`, as `crypto_jamfiles_format_test.py` imports its + sibling) +- Stream tool (not committed): `$W/secure/ct-run/linux.sh` and `inside.sh`, copied from + `$W/crypto-sign/ct-run/` with the tree `$W/secure/lane-tree`, the container `ct-secure`, the + volume `ct-secure-work`, and the library as their first argument (`--library "$1"`) + +**Interfaces:** +- Consumes: `test/support/constant_time_marks.hpp` (Task 5), every block (Task 6). +- Produces: the own lane `constant-time` of secure (`webcpp.lane constant-time : ... : native ;`). + +- [ ] **Step 1: Write the lane, planted leaks first.** `paths.hpp` holds + `template int common_paths()`: for each block on `std::uint8_t`, `std::uint32_t` + and `std::uint64_t`, its operands marked secret (`Checker::mark_secret` over their bytes), its + result checked `carries_mark` where `Checker::exact_subtraction` (memcheck) and not checked + where not (MemorySanitizer drops a subtraction's carry: crypto's msan_test.cpp says why); + `lookup` with the index secret over a 64-entry table; `select_bytes` with the mask secret; + `equal_mask`, `is_zero_mask`, `less_mask` with both operands secret; `constant_time_equal` with + both secret, its `bool` passed to `Checker::verdict` only after `secure::declassify` (the mark's + test); `secret<32>`'s move, move assignment, `clone` and destruction with its bytes secret. + Planted, each a `[[gnu::noinline]]` function of its own so that a report's first frame names it: + `planted_select` (`if (mask != 0) { planted_sink(when_set); }` with a `noinline` sink, so that no + compiler if-converts it) and `planted_lookup` (`return table[index];`), each called with its + mask or index itself marked secret, under `WEBCPP_TEST_SECURE_PLANTED_SELECT` or + `WEBCPP_TEST_SECURE_PLANTED_LOOKUP`, run before the paths. `dudect_test.cpp`: cases + `constant_time_equal` (class 0: equal 64-byte inputs; class 1: random second), `lookup` (index + 0 vs random over 64 entries), `select_bytes` (mask 0x00 vs 0xFF), `less_mask` (equal vs random + 32 bytes), each with dudect.hpp's A/A control; `dudect_planted_test.cpp`: an early-exit + comparison of 4096 bytes, class 0 differing at byte 0, class 1 equal, which must exceed the + threshold (judged everywhere). The Jamfile: + +```jam +project : requirements /webcpp/secure//secure ; +import webcpp os ; +webcpp.targets native ; +webcpp.original node ; +# linux-only and clang-on-linux: crypto's test/constant_time/Jamfile rules, copied. +CTGRIND = release on @linux-only + WEBCPP_SECURE_CT_VALGRIND 300 ; +webcpp.drive ctgrind : ctgrind_test.cpp : $(CTGRIND) : valgrind.mjs : : native ; +webcpp.drive ctgrind_space : ctgrind_test.cpp : $(CTGRIND) space + : valgrind.mjs : : native ; +webcpp.drive ctgrind_planted_select : ctgrind_planted_test.cpp + : $(CTGRIND) WEBCPP_TEST_SECURE_PLANTED_SELECT + : valgrind.mjs : --expect-leak --in planted_select : native ; +webcpp.drive ctgrind_planted_lookup : ctgrind_planted_test.cpp + : $(CTGRIND) WEBCPP_TEST_SECURE_PLANTED_LOOKUP ctgrind_planted_lookup + : valgrind.mjs : --expect-leak --in planted_lookup : native ; +MSAN_FLAGS = -fsanitize=memory -fno-sanitize-memory-param-retval ; +MSAN = WEBCPP_SECURE_CT_MSAN $(MSAN_FLAGS) -fsanitize=memory + release on @clang-on-linux ; +webcpp.run msan : msan_test.cpp : $(MSAN) : native ; +webcpp.drive msan_planted_select : msan_planted_test.cpp + : $(MSAN) WEBCPP_TEST_SECURE_PLANTED_SELECT + : msan_report.mjs : --in planted_select : native ; +webcpp.drive msan_planted_lookup : msan_planted_test.cpp + : $(MSAN) WEBCPP_TEST_SECURE_PLANTED_LOOKUP msan_planted_lookup + : msan_report.mjs : --in planted_lookup : native ; +DUDECT = release ; +if [ os.environ RUNNER_ENVIRONMENT ] = github-hosted +{ + DUDECT += WEBCPP_TEST_DUDECT_UNJUDGED ; +} +webcpp.run dudect : dudect_test.cpp : $(DUDECT) : native ; +webcpp.run dudect_planted : dudect_planted_test.cpp : release : native ; +webcpp.run dudect_harness : dudect_harness_test.cpp : : native ; +webcpp.lane constant-time : ctgrind ctgrind_space ctgrind_planted_select + ctgrind_planted_lookup msan msan_planted_select msan_planted_lookup dudect + dudect_planted dudect_harness + : native ; +``` + (with crypto's comments' reasons, secure's words: what is checked, the planted leaks, dudect on + hosted runners). +- [ ] **Step 2: See the planted leaks fail and the rest pass, natively on Linux.** + `$W/heavy.sh secure $W/secure/ct-run/linux.sh secure` (commit and refresh first). Expected: the + lane exits 0: memcheck and MemorySanitizer pass on the paths and report each planted function in + its own frame (the drivers' `--in` passes only then), `dudect` judges every case below the + threshold with its A/A control, `dudect_planted` exceeds it. Then once more with + `toolset=gcc-15` for the memcheck programs (Review Focus 2): in the container, + `b2 toolset=gcc-15 libs/secure/test/constant_time//ctgrind libs/secure/test/constant_time//ctgrind_planted_select` + (if the container has no gcc-15, the run's report says so and the clang lane stands). +- [ ] **Step 3: On this Mac** (dudect only; the rest is `no`): + `B2 toolset=clang libs/secure/test/constant_time//dudect libs/secure/test/constant_time//dudect_planted libs/secure/test/constant_time//dudect_harness`. + Expected: pass, DIT reported set inside the calls where the CPU has it, clear outside. +- [ ] **Step 4: The superproject's wiring.** Run `python3 tools/ci/matrix_test.py`, + `python3 tools/test/crypto_dudect_judge_test.py`, `python3 tools/test/secure_dudect_judge_test.py`, + `python3 tools/ci/matrix.py own-lanes --library secure --user-config .local/user-config.jam` + (one entry, native, its apt packages). Expected: pass. +- [ ] **Step 5: Commit, lint.** secure: `secure: the constant-time lane, memcheck, MemorySanitizer and dudect over every block, each with a planted leak that must fail`; superproject: `ci: secure's constant-time lane, its packages and dudect's judge`. Lint step (the lint analyses the lane's programs natively with the lane's packages). + +--- + +### Task 9: The documentation and the guard's measured cost + +Model tier: standard. Covers tasks.md 6.1. + +**Files:** +- Create: `doc/overview.adoc` (or sections in `secure.adoc`, as hash's page includes its sections): + what secure is and is not (no algorithm; crypto, hash and codecs use it); the guard (D3's + coverage table, verified as Task 3 recorded, nesting, `engaged`, the seam, what DIT covers and + not, the probe's absent path untested); erasing (`erase_secret`, a span of one for a C + library's object, the wipe seam for tests); `secret` (crypto's warning kept); + `constant_time_equal`; `declassify`; the blocks with their limits (what masks and + `value_barrier` cover and what the compiler may still do, `lookup`'s cost); the measured cost; + the changelog +- Create: `example/{guard,erase,secret,compare,hex_digit}.cpp` with `.expected` beside each + (`hex_digit.cpp`: a 4-bit value to its hex character and back by `is_in_range_mask` and + `select`, libsodium's method), each `webcpp.example` in `example/Jamfile`, quoted in the page by + tags +- Create: `bench/Jamfile`, `bench/timing.cpp` (hash's `bench/timing.cpp` on + ``, P3; `timing_check` in every lane, `timing` at + `release`, explicit), `bench/collect.py` (hash's `bench/collect.py` reduced to its + `--timing` and `--render-only` paths: it writes `doc/measurements.json` and renders + `doc/performance.adoc`, refusing a program not built at `variant=release`), and in + `test/Jamfile` `build-project ../bench ;` +- Create (superproject): `tools/test/secure_collect_test.py` (hash_collect_test.py's timing + cases on secure's collect.py) +- Modify: `doc/changelog.adoc` (Unreleased: one line per public header), `README.md` (no longer + "being built"), `AGENTS.md` (the generated page and how to measure) + +- [ ] **Step 1: Write the failing tests:** the examples' `.expected` files and + `secure_collect_test.py`; run `B2 toolset=clang libs/secure/example` and + `python3 tools/test/secure_collect_test.py`. Expected: FAIL (missing programs, missing script). +- [ ] **Step 2: Write the examples, the bench and collect.py; run** the examples on the five local + lanes, `B2 toolset=clang libs/secure/bench//timing_check`, the collect test. Expected: pass. +- [ ] **Step 3: Measure on an idle machine.** Only when no `$W/HEAVY.lock*` slot is held and + `uptime`'s 1-minute load is below 2: `B2 toolset=clang libs/secure/bench//timing`, then + `python3 libs/secure/bench/collect.py --timing --data libs/secure/doc/measurements.json --page libs/secure/doc/performance.adoc`. + Never `--provisional`; if the machine is not idle, wait (the controller may defer this step to + the delivery, before the review). +- [ ] **Step 4: Build the page.** `B2 libs/secure/doc doc`. Expected: the page with every section + of the spec's requirement "Documentation", the strict reference, the index entry. +- [ ] **Step 5: Commit, lint.** secure: `secure: the page, its examples, and the guard's cost measured from a release build`; superproject: `tools: secure_collect_test`. Lint step. + +--- + +### Task 10: hash on secure + +Model tier: standard (multi-file, worked example `445a403` + `1e0ddf5`). Covers tasks.md 7. + +Before it the controller runs `git -C libs/hash fetch origin` and, if `origin/main` moved past +`030e757` (hkdf-pieces may have landed new guarded functions), `git -C libs/hash merge origin/main` +(never rebase), and `B2 toolset=clang libs/hash/test//timing`. The guards and wipes are found by +grep at execution time, never from a list. + +**Files:** +- Delete: `libs/hash/include/webcpp/hash/detail/timing.hpp`, `.../detail/wipe.hpp` +- Modify: every file `grep -rlE 'timing_guard|TIMING_(ENTERED|COVERED)|detail/timing\.hpp|detail/wipe\.hpp|cpu_has_dit|dit_is_set|write_dit|dit_bit|(^|[^_[:alnum:]])wipe(_object)?\(|WIPE_RECORD|wipe_record|crypto::constant_time_equal|crypto/constant_time_equal' libs/hash` + prints (at planning time: the guarded headers `argon2.hpp`, `bcrypt.hpp`, `blake2b_subkey.hpp`, + `blake3.hpp`, `digest.hpp`, `hkdf.hpp`, `kdf_standards.hpp`, `mac.hpp`, `pbkdf2.hpp`, + `scrypt.hpp`, the wiping headers, `async.hpp`, `backends/*.hpp`, `hmac.hpp`; `test/support/timing_seam.hpp`, + `timing_dit.hpp`, `timing_coverage.hpp`; every `test/timing_*_test.cpp`; the five tests of the + wipe seam; `test/Jamfile`; `bench/timing.cpp`, `bench/Jamfile`, `bench/collect.py`; the MAC + examples and `example/Jamfile`; `AGENTS.md`; `meta/include-boundaries.json`; the pages' sources + `doc/*.adoc`, `doc/guide.json`; `doc/changelog.adoc`) +- Modify: `libs/hash/build.jam` (`/webcpp/secure//secure` in `hash`'s usage requirements) +- Modify (crypto, so that crypto still builds): delete `libs/crypto/test/timing_hash_interop_test.cpp` + and its three Jamfile lines (worked example `c02020d`) +- Modify (superproject): `tools/hash/doc_tables.py` (the DIT section: secure's + `webcpp::secure::timing_guard`, Windows on ARM64 covered; the guard "secure's, shared with crypto + and codecs"), `tools/test/hash_doc_tables_test.py` if it pins that text, + `tools/test/hash_jamfiles_test.py` and `tools/test/crypto_jamfiles_test.py` (libraries gain + `'secure'`) +- Regenerate: hash's generated pages (Global Constraints) + +**Interfaces:** +- Consumes: Tasks 2 and 4 (`secure::timing_guard`, `secure::erase_secret`, the wipe seam). +- Produces: hash's `test/support/timing_seam.hpp` in the form of secure's recorder (Task 2) with + `namespace webcpp::test` kept, `timing_library = "hash"`, `path_in_library` anchored on + `include/webcpp//`, and `#define WEBCPP_SECURE_TIMING_ENTERED(where) (::webcpp::test::timing_entered(where))`; + its `#error` checks `WEBCPP_SECURE_TIMING_GUARD_HPP`; hash's `support/timing_dit.hpp` calls + `secure::detail::write_dit` (R1). + +**Substitution rules** (Task 11 applies them to crypto with `crypto` for `hash`): +- S1. `#include ` -> `#include `; + `` -> ``; clang-format orders them. +- S2. Every use of `timing_guard`, `cpu_has_dit`, `dit_is_set`, whatever qualifies it, becomes + `secure::timing_guard` (etc.; inside `webcpp::hash`, `secure::` finds `webcpp::secure`); + `write_dit` and `dit_bit` (tests and benches only) become `secure::detail::...`. Guards keep their + variable and argument: `detail::timing_guard const timing{keyed_};` -> + `secure::timing_guard const timing{keyed_};`. +- S3. `WEBCPP_HASH_DETAIL_TIMING_COVERED` -> `WEBCPP_SECURE_TIMING_COVERED`; + `WEBCPP_HASH_DETAIL_TIMING_ENTERED` -> `WEBCPP_SECURE_TIMING_ENTERED`; + `WEBCPP_HASH_DETAIL_TEST_WIPE_RECORD` -> `WEBCPP_SECURE_TEST_WIPE_RECORD`; a test's definition of + `webcpp::hash::detail::test::wipe_record` becomes `webcpp::secure::test::wipe_record` (same + signature). +- S4. Wipes (B1): `detail::wipe(bytes)` of a byte span -> `secure::erase_secret(bytes)`; + `wipe(x.data(), x.size())` -> `secure::erase_secret(x)`; `wipe(p, n)` of a prefix -> + `secure::erase_secret(std::span(x).first(n))`; `wipe_object(object)` of an array -> + `secure::erase_secret(object)`, of any other object -> `secure::erase_secret(std::span(&object, 1))`. + The bytes zeroed (address and size) stay the same, which the wipe-seam tests confirm. +- S5. Prose: `detail::timing_guard` -> `webcpp::secure::timing_guard` (secure's guard); + "hash's own copy", "a copy of crypto's", "a change to one is a change to the other" and + `timing_hash_interop_test` go; "macOS, iOS, Linux and Android" gains Windows on ARM64; "depends on + no other webcpp library" becomes "depends on config and secure"; + `webcpp::crypto::constant_time_equal` -> `webcpp::secure::constant_time_equal` (and its header). +- S6. Every count of a guard declared in the test file itself reads `timing_all_entries`; every + count of hash's own guards reads `timing_entries` (worked example's S5). +- Completion grep: `grep -rnE 'WEBCPP_HASH_DETAIL_(TIMING|TEST_WIPE)|hash/detail/(timing|wipe)\.hpp|hash::detail::(timing_guard|cpu_has_dit|dit_is_set|write_dit|dit_bit|wipe)|crypto::constant_time_equal|timing_hash_interop' libs/hash tools CODING-GUIDELINES.md` + prints only `libs/hash/doc/*.json` measurement strings (data collect.py wrote; kept) and + `CODING-GUIDELINES.md` lines Task 12 rewrites. + +- [ ] **Step 1: Point hash's seam support at secure's seam and test it.** Rewrite the recorder's + top and `timing_dit.hpp` as Interfaces say; add `path_in_library_spellings()` to + `test/timing_test.cpp` (Task 2's cases with `hash`); `seam_fires` reads `timing_all_entries`. +- [ ] **Step 2: Run, expect failure.** + `B2 toolset=clang libs/hash/test//timing libs/hash/test//timing_coverage_hash2 libs/hash/test//wipe`: + hash's headers still hold hash's own guard and wipe seam, which the support no longer defines. +- [ ] **Step 3: Migrate** by S1 to S6 every file the grep prints; delete the two headers, their + entries in `meta/include-boundaries.json` and `test/Jamfile`'s headers-alone list; hash's MAC + examples include ``, and `example/Jamfile` keeps + `/webcpp/crypto//crypto` only where a crypto name remains (`random_device`); delete + crypto's interop test; `bench/collect.py`'s paragraph names secure's guard ("Elsewhere (x86, + WebAssembly) it executes no instruction"), then `--render-only` (no measurement: the guard's + instructions on Apple and Linux are unchanged, R9); `tools/hash/doc_tables.py --write`; + `AGENTS.md` and `doc/changelog.adoc` (Unreleased: "Changed every keyed function to hold + webcpp::secure's timing guard, which also sets DIT on Windows on ARM64, and every wipe to + secure's erase_secret; hash depends on secure."). +- [ ] **Step 4: Run.** `B2 toolset=clang libs/hash/test libs/hash/example libs/hash/bench//timing_check`, + `B2 toolset=gcc-15 libs/hash/test//timing libs/hash/test//timing_coverage_hash2 libs/hash/test//timing_keyed libs/hash/test//timing_unseamed libs/hash/test//wipe`, + `B2 toolset=clang libs/hash/test//timing_unseamed_release`, + wasip2 `libs/hash/test//timing libs/hash/test//timing_coverage_hash2 libs/hash/test//wipe`, + Emscripten `libs/hash/test//timing libs/hash/test//timing_async`, + `B2 toolset=clang libs/crypto/test`, `python3 tools/hash/doc_tables.py --check`, + `python3 tools/test/hash_doc_tables_test.py`, `python3 tools/test/hash_jamfiles_test.py`, + `python3 tools/test/crypto_jamfiles_test.py`, `B2 libs/hash/doc`, the completion grep. + Expected: pass; the grep prints only what it allows. +- [ ] **Step 5: Commit, lint.** hash: `hash: every keyed function holds webcpp::secure's timing guard and every wipe is secure's erase_secret; hash's copies are gone and hash depends on secure`; + crypto: `crypto: timing_hash_interop goes with hash's copy of the guard`; superproject: + `tools: hash's DIT section names secure's guard and Windows on ARM64, and the user Jamfile tests copy libs/secure`. + Lint step. + +--- + +### Task 11: crypto on secure + +Model tier: most capable (largest change, judgment at each wipe and declassify). Covers tasks.md 8. +Before it the controller runs `git -C libs/crypto fetch origin` and merges `origin/main` if it +moved (never rebase). + +**Files:** +- Delete: `libs/crypto/include/webcpp/crypto/{detail/timing,detail/wipe,detail/declassify,erase_secret,constant_time_equal,secret}.hpp`; + `test/{erase_secret,constant_time_equal,secret,declassify_compile,wipe}_test.cpp` (moved to + secure in Tasks 4 and 5; `wipe_test.cpp`'s `detail::exceeds` half stays as `test/limits_test.cpp` + with its Jamfile line), `test/support/valgrind_stub/` (ruling R4), + `test/messages/{erase_secret_const_range,secret_of_no_bytes}/` (moved), + `tools/test/fixtures/crypto_jamfiles/secret_of_no_bytes_on_emscripten/` (superproject: moved to + `tools/test/fixtures/secure_jamfiles/` with secure's message) +- Modify: every file `grep -rlE 'timing_guard|TIMING_(ENTERED|COVERED)|detail/timing\.hpp|cpu_has_dit|dit_is_set|write_dit|dit_bit|detail/wipe\.hpp|(^|[^_[:alnum:]])wipe(_object)?\(|DECLASSIFY|declassify\.hpp|CT_VALGRIND|CT_MSAN|erase_secret|constant_time_equal|(^|[^_[:alnum:]])secret<|crypto/secret\.hpp' libs/crypto tools/test/fixtures/crypto_jamfiles` + prints (at planning time 49 files for the guard, 22 for the wipe, 16 for declassify, about 90 + for erase, comparison and secret: the headers, tests, `test/constant_time/*`, `test/Jamfile`'s + headers-alone list, `bench/*`, `doc/*.adoc`, `doc/tables/crypto.json`, `AGENTS.md`, + `doc/changelog.adoc`, the fixtures) +- Modify: `libs/crypto/build.jam` (`/webcpp/secure//secure` in `crypto`'s usage + requirements) +- Create: `test/support/timing_dit.hpp` (crypto's DIT helper, hash's form of Task 10 with + `WEBCPP_TEST_CRYPTO_SUPPORT_TIMING_DIT_HPP`), `test/timing_nested_hash_test.cpp` (worked example + `4f62e73`'s file, with its includes on crypto's own support: `"support/timing_seam.hpp"` first, + `"support/timing_dit.hpp"`, and ``), its Jamfile line where the + interop test was; `test/messages/{constant_time_equal_moved,erase_secret_moved,secret_moved}/` + (each a compile-diagnostic: `webcpp::crypto::constant_time_equal`, `erase_secret`, `secret<16>` + named with `` included, `expected-error` "no member named ... in namespace + 'webcpp::crypto'" or clang's "no type named" form, as `equal_removed` writes it) +- Modify: `test/messages/{equal_removed,wipe_removed}/*.cpp` include `` + in place of the deleted headers; `test/messages/Jamfile` +- Modify (superproject): `tools/hash/doc_tables.py` (the sentence naming crypto's + `timing_nested_hash_test`, as `ae4ef95`), then `tools/hash/doc_tables.py --write` +- Regenerate: crypto's generated pages and `performance.adoc` (Global Constraints) + +**Interfaces:** +- Consumes: every name of secure; hash on secure (Task 10). +- Produces: crypto's `test/support/timing_seam.hpp` as hash's of Task 10 with + `timing_library = "crypto"` (crypto's own `named_function` machinery below the top kept). + +**Substitution rules:** S1 to S6 of Task 10 with `crypto` for `hash`, and: +- S7. `crypto::erase_secret`, `crypto::constant_time_equal`, `crypto::secret` (and unqualified + uses inside `webcpp::crypto`) -> `secure::erase_secret`, `secure::constant_time_equal`, + `secure::secret`, always qualified (a class with a member `secret()` would otherwise find the + function); includes of the deleted headers -> secure's. +- S8. `WEBCPP_CRYPTO_DETAIL_DECLASSIFY(&x, sizeof x);` -> `secure::declassify(x);` (every site is + of this form; `x` is never const there); `WEBCPP_CRYPTO_DETAIL_CT_VALGRIND` -> + `WEBCPP_SECURE_CT_VALGRIND`, `WEBCPP_CRYPTO_DETAIL_CT_MSAN` -> `WEBCPP_SECURE_CT_MSAN` (in + `curves/secp256k1.hpp`, `test/constant_time/Jamfile` and its comments). +- S9. dudect (`test/constant_time/dudect.hpp`, `dudect_sodium_test.cpp`) and benches + (`bench/timing.cpp`, `bench/Jamfile`, `bench/collect.py`) read `secure::cpu_has_dit()` and + `secure::dit_is_set()` under `WEBCPP_SECURE_TIMING_COVERED`, "not applicable here (not arm64 + under macOS, Linux or Windows)". +- Completion grep: `grep -rnE 'WEBCPP_CRYPTO_DETAIL_(TIMING|DECLASSIFY|CT_)|crypto/detail/(timing|wipe|declassify)\.hpp|crypto/(erase_secret|constant_time_equal|secret)\.hpp|crypto::(erase_secret|constant_time_equal|secret<)|detail::wipe(_object)?|timing_hash_interop' libs tools CODING-GUIDELINES.md` + prints only `libs/*/doc/*.json` measurement strings, crypto's own moved-name messages, and + `CODING-GUIDELINES.md` lines Task 12 rewrites; the spec's scenario "No copy remains" holds: + `grep -rnE 'class timing_guard|void erase_secret|bool constant_time_equal|void wipe|class secret[^_[:alnum:]]|define [A-Z_]*DECLASSIFY' libs/hash/include libs/crypto/include` + prints nothing. + +- [ ] **Step 1: Point crypto's seam support at secure's seam, add its DIT helper, write the nested + test**; `timing_test.cpp` gains `path_in_library_spellings()` with crypto's paths, `seam_fires` + reads `timing_all_entries`; write the three moved-name messages. +- [ ] **Step 2: Run, expect failure.** + `B2 toolset=clang libs/crypto/test//timing_nested_hash libs/crypto/test//timing libs/crypto/test//timing_mock`: + crypto's headers still hold crypto's own guard. +- [ ] **Step 3: Migrate** by S1 to S9; delete the files above; `doc/backends.adoc`, + `doc/x25519.adoc` and `doc/tables/crypto.json` say Windows on ARM64 is covered (worked example + `89c3d84`'s texts, secure's names) and name `secure::secret` and `secure::constant_time_equal`; + `generate.py --root .`; `bench/collect.py --render-only` (R9); `AGENTS.md`; + `doc/changelog.adoc` (Unreleased: "Changed every public operation to hold webcpp::secure's timing + guard, also on Windows on ARM64, and moved erase_secret, constant_time_equal and secret to + webcpp::secure, with no alias; crypto depends on secure."). The test/messages that include + `` stay; any `expected-error` naming a moved header is updated. +- [ ] **Step 4: Run.** `B2 toolset=clang libs/crypto/test libs/crypto/example libs/crypto/bench//timing_check`, + `B2 toolset=gcc-15 libs/crypto/test//timing libs/crypto/test//timing_nested_hash libs/crypto/test//timing_mock libs/crypto/test//timing_coverage_sodium libs/crypto/test//timing_unseamed`, + `B2 toolset=clang libs/crypto/test//timing_unseamed_release`, + wasip2 `libs/crypto/test//timing libs/crypto/test//timing_nested_hash libs/crypto/test//timing_coverage_sodium`, + Emscripten `libs/crypto/test//timing libs/crypto/test//timing_nested_hash`, + `B2 toolset=clang libs/crypto/test/constant_time//dudect_sodium libs/crypto/test/constant_time//dudect_harness`, + `$W/heavy.sh secure $W/secure/ct-run/linux.sh crypto` (crypto's lane natively on Linux, after a + commit and refresh), `B2 toolset=clang libs/hash/test//timing`, + `python3 libs/crypto/doc/tables/generate.py --root . --check`, + `python3 tools/test/crypto_jamfiles_test.py`, `python3 tools/test/secure_jamfiles_test.py`, + `B2 libs/crypto/doc`, both completion greps. Expected: all pass. +- [ ] **Step 5: Commit, lint.** crypto: `crypto: every public operation holds webcpp::secure's timing guard, and erase_secret, constant_time_equal, secret, the wipe and declassify are secure's, with no alias`; + superproject: `tools: hash's DIT section names crypto's timing_nested_hash_test, and secret_of_no_bytes is secure's fixture`. + Lint step. + +--- + +### Task 12: The superproject + +Model tier: standard. Covers tasks.md 9. + +The registration mirrors hash's (`647813c`, `3724513`) and webrtc's (`aa0ea3a`). Every place the +superproject names a library, found at planning time: + +| File | Change | Task | +| --- | --- | --- | +| `.gitmodules`, `libs/secure` | the submodule | done (`b1972f8`) | +| `AGENTS.md` | the libraries table gains secure's row ("the side-channel and secret-in-memory primitives crypto, hash and codecs share; no algorithm; webcpp's own" / native, wasip2, wasip3, emscripten; its own lane `constant-time` / a submodule at `libs/secure`) and hash's row, missing today (its targets, own lane `c-suites`, "depends on config and secure"); crypto's row says it depends on hash and secure; the layout's list of `libs//` gains hash and secure | 12 | +| `doc/releases/0.1.0.adoc` | New Libraries: `link:{library-pages}secure/{library-page}[secure]`, one sentence, "from R."; Tools and build: one line each for `secure_jamfiles_test.py`, `secure_collect_test.py`, `secure_dudect_judge_test.py`, secure's constant-time lane in `matrix.py` and `library.yml`, and the jamfiles tests copying libs/secure | 12 | +| `CODING-GUIDELINES.md` | chapter 17: "### secure (side-channel and secret-in-memory primitives; own; accepted 2026-11-24, built, not merged)" with its decisions (D1 to D11, B1 to B9, O1) each with its `Source:`; chapter 15 crypto: its DIT bullet, `constant_time_equal` bullet and every `crypto::erase_secret`/`secret`/wipe mention name secure's; chapter 17 hash: its DIT bullet and wipe mentions; chapter 1's list of tools tests gains the secure tests if that list names hash's | 12 | +| `tools/ci/matrix.py`, `tools/ci/matrix_test.py`, `.github/workflows/library.yml` | secure's lane, packages, judge | 8 | +| `tools/test/crypto_jamfiles_test.py`, `tools/test/hash_jamfiles_test.py` | `'secure'` copied | 10 | +| `tools/test/secure_jamfiles_test.py`, `secure_collect_test.py`, `secure_dudect_judge_test.py`, `tools/test/fixtures/secure_jamfiles/` | new | 7, 8, 9, 11 | +| `tools/hash/doc_tables.py` | DIT text | 10, 11 | +| the index page `doc/index.adoc` | nothing: it lists `libs/*/meta/libraries.json` (checked by `b2 doc`) | 1 | +| `README.md` | nothing: its table lists neither hash, config, cobalt nor webrtc today (reported, not changed) | - | +| `tools/lint/lint.sh` | nothing: its canary list (`crypto hash`) is of C libraries' canaries; secure has none | - | + +- [ ] **Step 1: Write** the three files' changes above. +- [ ] **Step 2: The gitlinks.** `git add libs/secure libs/hash libs/crypto` (nothing else) and + commit `libs/secure, libs/hash, libs/crypto: the gitlinks at secure built and hash and crypto on it (, , )`. +- [ ] **Step 3: Run.** `B2 doc`, `python3 tools/test/doc_test.py`, `python3 tools/release/release.py`'s + check of the notes if it runs offline (`AGENTS.md` chapter 5 names it), and the completion greps + of Tasks 10 and 11 over `CODING-GUIDELINES.md` (now nothing). +- [ ] **Step 4: Commit, lint.** `build: register secure, a library of the superproject`, + `guidelines: secure is accepted and built, in chapter 17, and crypto's and hash's chapters name its guard, erase, comparison and secret`. + Lint step. + +--- + +### Task 13: The delivery (a checklist the controller runs) + +Model tier: the controller; the final review by the most capable model. + +- [ ] hash: `git -C libs/hash fetch origin`; if `origin/main` moved (hkdf-pieces landed), merge it + (never rebase), migrate any new guard site and wipe by Task 10's rules, re-run Task 10's Step 4, + commit, update the gitlink. crypto and the superproject: the same merge of `origin/main` if it + moved. +- [ ] Commit everything; `$W/secure/refresh-tree.sh`. +- [ ] Lanes, each from scratch, one build directory each, through heavy.sh, for `L` in + `secure hash crypto`: + +```bash +B2="env -u CPATH -u CPLUS_INCLUDE_PATH -u C_INCLUDE_PATH b2 --user-config=.local/user-config.jam" +H="$W/heavy.sh secure" +$H $B2 -a --dump-tests --build-dir=bin/lane-clang --out-xml=clang.$L.xml toolset=clang libs/$L/test libs/$L/example +$H $B2 -a --dump-tests --build-dir=bin/lane-gcc-15 --out-xml=gcc-15.$L.xml toolset=gcc-15 libs/$L/test libs/$L/example +$H $B2 -a --dump-tests --build-dir=bin/lane-wasip2 --out-xml=wasip2.$L.xml toolset=clang-wasip2 testing.launcher=tools/boost/asio-wasip2/run.sh libs/$L/test libs/$L/example +$H $B2 -a --dump-tests --build-dir=bin/lane-wasip3 --out-xml=wasip3.$L.xml toolset=clang-wasip3 testing.launcher=tools/boost/asio-wasip3/run.sh libs/$L/test libs/$L/example +$H $B2 -a --dump-tests --build-dir=bin/lane-emscripten --out-xml=emscripten.$L.xml toolset=emscripten libs/$L/test libs/$L/example +``` + (wasip2 and wasip3 with `WEBCPP_WASIP2_TEST_TIMEOUT=1800 WEBCPP_WASIP3_TEST_TIMEOUT=1800`, as + hkdf-pieces' run.sh), plus `toolset=clang variant=release libs/$L/test`; every test with its + `_no_exceptions` twin. +- [ ] The constant-time lanes: `$H $W/secure/ct-run/linux.sh secure`, `$H $W/secure/ct-run/linux.sh crypto`, + natively on this Mac the dudect programs of both, and crypto's wasip2 half + (`$H $B2 -a --build-dir=bin/lane-ct-wasip2 toolset=clang-wasip2 testing.launcher=tools/boost/asio-wasip2/run.sh libs/crypto/test/constant_time//constant-time`). +- [ ] MSVC on the VM: `run-lane.sh 14.3` and `14.5`, x64 and `--arch arm64`, over + `libs/secure/test libs/secure/example libs/hash/test libs/hash/example libs/crypto/test libs/crypto/example`; + release on arm64 for `libs/secure/test`; on arm64 also + `libs/crypto/test/constant_time//dudect_sodium` (dudect's X25519 on Windows ARM64 with DIT set by + the library). Each `summarize.sh`: `new failures:` empty. +- [ ] Docs and tools: `$B2 doc`, the generators' `--check`s, every `tools/test/*_test.py` the + stream touched, `python3 tools/ci/matrix_test.py`, `$B2 libs/{secure,hash,crypto}/bench//timing_check`. +- [ ] The report: `python3 tools/report/report.py` over the XML files, every cell green. +- [ ] Lints: macOS `$H tools/lint/lint.sh --clang-format .local/wasi-sdk/bin/clang-format --clang-tidy .local/wasi-sdk/bin/clang-tidy`; + Linux full `$H $W/linux-lint/run.sh --full $W/secure/lane-tree`. Clean. +- [ ] Task 9's measurement, if deferred, on an idle machine. +- [ ] The final whole-branch review (most capable model) over the four repositories; fixes in + their own commits; lanes that a fix touches re-run. +- [ ] Pull requests, in merge order: secure, hash, crypto (each merged with a merge commit), then + the superproject (gitlinks at the merged mains, `tools/`, guidelines, notes), then the proposals + (this change; its status moves on with the archive when the owner says). Merged by the owner's + standing instruction or by the owner; no CI gates them (pushes' runs are cancelled); one CI at + the end on the superproject's main. + +## Rulings (the planner's) + +- **R1:** the guard's register helpers (`dit_bit`, `write_dit`, the Windows constants, + `probe_dit`) are `webcpp::secure::detail`; the public names are `timing_guard`, `cpu_has_dit`, + `dit_is_set`. Test code (secure's, hash's and crypto's `force_dit`, their benches) may call + `secure::detail::write_dit`; no library header of another library names `secure::detail`. +- **R2 (B9, added to design D4 and the spec):** the wipe's test seam + `WEBCPP_SECURE_TEST_WIPE_RECORD` / `secure::test::wipe_record`, hash's moved: deleting hash's + `detail/wipe.hpp` would otherwise remove the evidence of five hash tests. +- **R3:** every `detail::wipe`/`wipe_object` of hash and crypto becomes `secure::erase_secret` over + a span (B1); no library of webcpp calls `secure::detail::wipe`. +- **R4:** crypto's `declassify_compile_test` and `valgrind_stub` go: `secure::declassify(x)` is a + call whose argument every build compiles, which was the test's reason; secure's + `declassify_compile_test` covers the marks. +- **R5:** `constant_time_equal` accepts `secret` through its `bytes()` (it is not a range), and + exactly the four element types the spec names. +- **R6:** `value_barrier` is a volatile round trip on MSVC and on WebAssembly (where an + `asm` register constraint is not relied on), an empty `asm` with `"+r"` elsewhere. +- **R7:** secure's constant-time lane runs natively only (memcheck and MemorySanitizer on Linux, + dudect natively everywhere, D10); its own copies of dudect.hpp, the harness test and the judge + (O1); the CI's judge step runs the library's own judge; locally the Linux half runs in the + linux-lint image by the stream's `ct-run/linux.sh`, as crypto-sign's did. +- **R8:** the spec's scenario "A program that erases a buffer builds nothing" is a user Jamfile + fixture (`secure_jamfiles_test.py`), and crypto's `secret_of_no_bytes_on_emscripten` fixture moves + there with secure's message. +- **R9:** hash's and crypto's guard-cost benches stay, on secure's guard, rendered again + (`--render-only`), not re-measured: the guard's instructions on Apple and Linux are unchanged. + secure measures its own once, on an idle machine (D11). +- **R10:** crypto gains three moved-name messages, as it keeps `equal_removed`, so that a program + still naming `crypto::constant_time_equal`, `erase_secret` or `secret` fails with that name. +- **R11:** tasks.md's chapter 17 entry moves from task 1.2 to the superproject's task (9.1), with + every other superproject registration, so that it records the library as built. +- **R12:** AGENTS.md gains hash's missing row and layout name with secure's, since its + dependencies change; README.md's libraries table, which lacks hash, config, cobalt and webrtc + alike, is reported, not changed. +- **R13:** the Windows branch is ported with the rest in Task 2 (it is the prior's, built and once + verified); Task 3 verifies it on the VM, release included, which the withdrawn change never ran. diff --git a/libraries/secure/openspec/changes/genesis/specs/secure/spec.md b/libraries/secure/openspec/changes/genesis/specs/secure/spec.md index d77188e..b49c43c 100644 --- a/libraries/secure/openspec/changes/genesis/specs/secure/spec.md +++ b/libraries/secure/openspec/changes/genesis/specs/secure/spec.md @@ -49,12 +49,16 @@ A macro `WEBCPP_SECURE_TIMING_ENTERED(where)`, defined by a test alone before it - **THEN** `` is not included by the guard's header and the constructor takes only `engaged` ### Requirement: Memory: erase_secret -`` SHALL declare `secure::erase_secret(range)`, which zeroes `size() * sizeof(element)` bytes from the first element of a contiguous sized range of non-const, trivially copyable elements, with volatile stores followed by a signal fence that the optimiser keeps, and touches no byte around them. A range of const or not trivially copyable elements MUST stop the build with a message naming the ranges it takes; a range that is not contiguous, and a pointer with a size, MUST NOT be accepted. +`` SHALL declare `secure::erase_secret(range)`, which zeroes `size() * sizeof(element)` bytes from the first element of a contiguous sized range of non-const, trivially copyable elements, with volatile stores followed by a signal fence that the optimiser keeps, and touches no byte around them. A range of const or not trivially copyable elements MUST stop the build with a message naming the ranges it takes; a range that is not contiguous, and a pointer with a size, MUST NOT be accepted. A program built with `WEBCPP_SECURE_TEST_WIPE_RECORD` defined SHALL have every wipe of the library, `erase_secret`'s and `secret`'s, call `webcpp::secure::test::wipe_record(address, size)`, which that program defines, once the bytes are zero; without the macro nothing is declared or called. #### Scenario: A buffer erased before its scope ends - **WHEN** a test erases a stack buffer as its last use before its scope ends, built at `-O2` with full inlining, and reads that storage afterwards through the test's placement storage - **THEN** every byte reads zero, on every lane +#### Scenario: A wipe reported to a test +- **WHEN** a test built with `WEBCPP_SECURE_TEST_WIPE_RECORD` erases a 32-byte buffer and destroys a `secret<16>` +- **THEN** its `wipe_record` is called once with the buffer's address and 32, and once with 16 bytes at the secret's storage, each time with those bytes already zero + #### Scenario: A refused range - **WHEN** a test asks whether `erase_secret` accepts a `std::list&`, a `std::vector&` and a `std::span` - **THEN** it accepts none of them, and accepts a `std::vector&`, a `std::string&`, a `std::span` and a span of one C library context @@ -112,3 +116,14 @@ The library SHALL have its page under `libs/secure/doc/`, built by `b2 doc`: wha #### Scenario: The page builds - **WHEN** `b2 doc` runs in the superproject - **THEN** secure's page is produced with every section above, and its examples' expected outputs match their runs + +### Requirement: One copy in webcpp +webcpp::hash and webcpp::crypto SHALL use secure's guard, wipe, erase, comparison, secret type and declassify marker, and MUST keep no copy and no alias of them: hash's and crypto's `detail/timing.hpp` and `detail/wipe.hpp`, crypto's `detail/declassify.hpp`, `erase_secret.hpp`, `constant_time_equal.hpp` and `secret.hpp` are deleted, and both libraries name `/webcpp/secure//secure` as a dependency. Each keeps its own test support (seam recorder, DIT helper, checkers' marks) in its own `test/support/`, counting its own guards by `file_name()`. + +#### Scenario: No copy remains +- **WHEN** the headers of `libs/hash/include/` and `libs/crypto/include/` are searched for a definition of a class `timing_guard`, of a function `erase_secret`, `constant_time_equal`, `wipe` or `wipe_object`, of a class template `secret`, and of a macro ending in `DECLASSIFY` +- **THEN** none is found, and hash's and crypto's tests pass with every guard they count entered through secure's seam + +#### Scenario: A guarded hash call inside a guarded crypto call +- **WHEN** crypto's `timing_nested_hash_test` runs a keyed call of hash inside a guarded call of crypto, from a thread whose DIT is clear and from one that set it +- **THEN** the seam records crypto's guard first and hash's second, DIT is set inside both where the CPU has it, and after both it is as it was before diff --git a/libraries/secure/openspec/changes/genesis/tasks.md b/libraries/secure/openspec/changes/genesis/tasks.md index 596543b..72ceefc 100644 --- a/libraries/secure/openspec/changes/genesis/tasks.md +++ b/libraries/secure/openspec/changes/genesis/tasks.md @@ -1,42 +1,59 @@ # Tasks Each task writes its tests first; the library builds and its tests pass on every local lane at the -end of every task. A plan with code goes in `reference/plan.md` when the proposal is accepted. The -owner's gates come first: the repository `webcpporg/secure` and the submodule `libs/secure` -(chapter 10's checklist, items 1 and 2); until then the library is a local repository at -`libs/secure`. The prior code to port is in `reference/prior/` (`reference/STATUS.md`). +end of every task. The plan with code is `reference/plan.md` (its task numbers follow in brackets). +The owner's gates are done: the repository `webcpporg/secure` and the submodule `libs/secure` +(chapter 10's checklist, items 1 and 2). The prior code to port is in `reference/prior/` +(`reference/STATUS.md`). + +Test support (design O1, decided by the owner on 2026-11-24): the seam recorder, the DIT helper and +the constant-time checkers' marks stay in each library's own `test/support/`: secure's in secure's, +and hash and crypto keep or gain their own copies in theirs; nothing goes to `tools/node-test`, and +no `webcpp::core` is made. ## 1. The library's skeleton -- [ ] 1.1 The repository's files (chapter 10's checklist, items 3 to 7): `meta/libraries.json` with `"port-of": null`, `build.jam` with `secure` (D1), `LICENSE_1_0.txt`, `README.md`, `AGENTS.md`, `.gitattributes`, `.gitignore`, `.github/workflows/ci.yml`, `test/Jamfile`, `example/Jamfile`, `doc/Jamfile` and `doc/changelog.adoc`; the index page's entry -- [ ] 1.2 `config.hpp` and its test three ways (exceptions, `WEBCPP_NO_EXCEPTIONS`, `WEBCPP_SECURE_NO_EXCEPTIONS`); `CODING-GUIDELINES.md` chapter 17's entry (D1) +- [ ] 1.1 The repository's files (chapter 10's checklist, items 3 to 7): `meta/libraries.json` with `"port-of": null`, `build.jam` with `secure` (D1), `LICENSE_1_0.txt`, `README.md`, `AGENTS.md`, `.gitattributes`, `.gitignore`, `.github/workflows/ci.yml`, `test/Jamfile`, `example/Jamfile`, `doc/Jamfile` and `doc/changelog.adoc`; the index page's entry (plan task 1) +- [ ] 1.2 `config.hpp` and its test three ways (exceptions, `WEBCPP_NO_EXCEPTIONS`, `WEBCPP_SECURE_NO_EXCEPTIONS`) (D1) (plan task 1) ## 2. The guard -- [ ] 2.1 `timing_guard.hpp` on Apple's systems and Linux, ported from `reference/prior/config/include/` with `WEBCPP_SECURE_*` names in `webcpp::secure`; secure's `test/support/timing_seam.hpp` and `timing_dit.hpp`; `timing_guard_test`, `_nesting_`, `_seam_`, `_threads_` and the header-alone test (D2, D9, D10) -- [ ] 2.2 Windows on ARM64: the intrinsics, the SEH probe, `timing_guard_windows_test`, run on the Windows ARM64 lane with MSVC 14.3 and 14.5, debug and release (D3, D11) +- [ ] 2.1 `timing_guard.hpp` on Apple's systems and Linux, ported from `reference/prior/config/include/` with `WEBCPP_SECURE_*` names in `webcpp::secure`; secure's `test/support/timing_seam.hpp` and `timing_dit.hpp`; `timing_guard_test`, `_nesting_`, `_seam_`, `_threads_` and the header-alone test (D2, D9, D10) (plan task 2) +- [ ] 2.2 Windows on ARM64: the intrinsics, the SEH probe, `timing_guard_windows_test`, run on the Windows ARM64 lane with MSVC 14.3 and 14.5, debug and release (D3, D11) (plan task 3) ## 3. Memory and comparison -- [ ] 3.1 `detail/wipe.hpp` and `erase_secret.hpp`, moved from crypto with `erase_secret_test` (D4) -- [ ] 3.2 `secret.hpp`, moved from crypto, with `secret_test` (D6) -- [ ] 3.3 `constant_time_equal.hpp` over byte ranges, with `constant_time_equal_test` and its seam check (D5) -- [ ] 3.4 `declassify.hpp`, secure's `test/support/constant_time_marks.hpp`, `declassify_compile_test` (D7, D9) +- [ ] 3.1 `detail/wipe.hpp` with its test seam (B9) and `erase_secret.hpp`, moved from crypto with `erase_secret_test` (D4) (plan task 4) +- [ ] 3.2 `secret.hpp`, moved from crypto, with `secret_test` (D6) (plan task 4) +- [ ] 3.3 `constant_time_equal.hpp` over byte ranges, with `constant_time_equal_test` and its seam check (D5) (plan task 5) +- [ ] 3.4 `declassify.hpp`, secure's `test/support/constant_time_marks.hpp`, `declassify_compile_test` (D7, D9) (plan task 5) ## 4. The constant-time blocks -- [ ] 4.1 `constant_time.hpp`: `value_barrier`, the masks, `select`, `lookup`, `select_bytes` and the byte comparisons, with the exhaustive and random tests against a plain reference (D8, D10) -- [ ] 4.2 The allocation test over every function; the convenience header and its test (D1, D10) +- [ ] 4.1 `constant_time.hpp`: `value_barrier`, the masks, `select`, `lookup`, `select_bytes` and the byte comparisons, with the exhaustive and random tests against a plain reference (D8, D10) (plan task 6) +- [ ] 4.2 The allocation test over every function; the convenience header and its test; a user's Jamfile of secure on every target (D1, D10) (plan task 7) ## 5. The constant-time lane -- [ ] 5.1 The lane `constant-time`: memcheck with the operands undefined, MemorySanitizer where crypto runs it, dudect with its A/A control, the planted branching `select` and indexing `lookup` that must fail (D10) +- [ ] 5.1 The lane `constant-time`: memcheck with the operands undefined, MemorySanitizer where crypto runs it, dudect with its A/A control, the planted branching `select` and indexing `lookup` that must fail (D10) (plan task 8) + +## 6. The documentation + +- [ ] 6.1 The page: what secure is, the guard, erase, `secret`, `constant_time_equal`, `declassify`, the blocks and their limits, the changelog; every example built and run; the guard's cost measured on release builds on an idle machine (D11) (plan task 9) + +## 7. hash on secure (owner decision 9) + +- [ ] 7.1 Before it: hash's `origin/main` merged into its branch (never rebased), and any guard site a stream merged since (hkdf-pieces) moved with the rest (plan task 10) +- [ ] 7.2 Every guard site of hash on `secure::timing_guard` (its `engaged` arguments kept), every wipe on `secure::erase_secret` (B1), the wipe seam on secure's (B9); hash's `detail/timing.hpp` and `detail/wipe.hpp` deleted; hash's own `test/support/` seam recorder and DIT helper pointed at secure's seam; hash's build, `AGENTS.md`, page and "depends on" statements name secure; its MAC examples and pages name `secure::constant_time_equal`; crypto's `timing_hash_interop_test` deleted with hash's copy; generated pages regenerated by their generators (plan task 10) + +## 8. crypto on secure (owner decision 9) + +- [ ] 8.1 Every guard site, wipe, erase, comparison, secret and declassify of crypto on secure's names; crypto's `detail/timing.hpp`, `detail/wipe.hpp`, `detail/declassify.hpp`, `erase_secret.hpp`, `constant_time_equal.hpp` and `secret.hpp` deleted with no alias, and their tests moved to secure; crypto's constant-time lane on `WEBCPP_SECURE_CT_VALGRIND` and `WEBCPP_SECURE_CT_MSAN`; dudect and benches on `secure::cpu_has_dit()`; crypto's own `test/support/` seam recorder and a DIT helper of its own; `timing_nested_hash_test` in place of `timing_hash_interop_test`; generated pages regenerated by their generators (plan task 11) + +## 9. The superproject -## 6. The documentation and the delivery +- [ ] 9.1 `CODING-GUIDELINES.md` chapter 17's entry for secure, and crypto's and hash's chapters' mentions of the moved names; `AGENTS.md`'s libraries and dependencies; `doc/releases/0.1.0.adoc`'s New Libraries and tools lines; the tools that list libraries; the gitlinks (plan task 12) -- [ ] 6.1 The page: what secure is, the guard, erase, `secret`, `constant_time_equal`, `declassify`, the blocks and their limits, the changelog; every example built and run; the guard's cost measured on release builds on an idle machine (D11) -- [ ] 6.2 Full local verification on every lane (native clang and gcc 15, MSVC 14.3 and 14.5, the Windows ARM64 lane, wasip2, wasip3, Emscripten, the constant-time lane, the Linux lint), exceptions on and off; the review; pull requests the owner merges; one CI at the end +## 10. The delivery -Not tasks of this genesis, each a change of its own library after secure: hash's guard and wipe on -secure's; crypto's callers on secure's names, its copies deleted with no alias; and the place of -the shared test support, once the owner decides (design O1). +- [ ] 10.1 hash's `origin/main` merged again, and any new guard site migrated; full local verification on every lane (native clang and gcc 15, MSVC 14.3 and 14.5, the Windows ARM64 lane, wasip2, wasip3, Emscripten, the constant-time lanes of secure and crypto, the Linux lint), exceptions on and off; the review; pull requests, merged in order secure, hash, crypto, the superproject, the proposals; one CI at the end (plan task 13) From 36d4a266a020371cb15f181d1fb1520046c60403 Mon Sep 17 00:00:00 2001 From: R Date: Wed, 25 Nov 2026 16:18:02 -0300 Subject: [PATCH 3/8] secure: genesis is built (status implementing, tasks 1.1 to 9.1 ticked, D8's constraint as built: std::unsigned_integral admits bool, the blocks take detail::mask_word, STATUS dated) --- README.md | 2 +- .../openspec/changes/genesis/.openspec.yaml | 4 +-- .../secure/openspec/changes/genesis/design.md | 21 ++++++------ .../changes/genesis/reference/STATUS.md | 8 +++++ .../secure/openspec/changes/genesis/tasks.md | 32 +++++++++---------- 5 files changed, 38 insertions(+), 29 deletions(-) diff --git a/README.md b/README.md index 7bea094..dd0e79f 100644 --- a/README.md +++ b/README.md @@ -64,7 +64,7 @@ tag is placed. | lexical | [genesis](libraries/lexical/openspec/changes/archive/2026-10-09-genesis) | lexical: the lexical forms of JSON Schema's string formats | own | implemented | 0.1.0 | 2026-10-09 | [code](https://github.com/webcpporg/lexical/tree/e286ca4) | | lexical | [strategies](libraries/lexical/openspec/changes/strategies) | lexical: one entry point, strategies and Boost.Regex | own | draft | | | | | pratt | [genesis](libraries/pratt/openspec/changes/archive/2026-10-08-genesis) | pratt: a generic Pratt parser engine for C++20, with a decimal calculator | own | implemented | 0.1.0 | 2026-10-08 | [code](https://github.com/webcpporg/pratt/tree/d78451b) | -| secure | [genesis](libraries/secure/openspec/changes/genesis) | secure: the side-channel and secret-in-memory primitives crypto, hash and codecs share (DIT guard, erase, secret, constant-time blocks), no algorithm | own | accepted | | 2026-11-24 | | +| secure | [genesis](libraries/secure/openspec/changes/genesis) | secure: the side-channel and secret-in-memory primitives crypto, hash and codecs share (DIT guard, erase, secret, constant-time blocks), no algorithm | own | implementing | | 2026-11-24 | [code](https://github.com/webcpporg/secure) | | trystero | [genesis](libraries/trystero/openspec/changes/archive/2026-10-09-genesis) | trystero: serverless WebRTC rooms, wire compatible with Trystero | port of Trystero 0.26.0 | implemented | 0.1.0 | 2026-10-09 | [code](https://github.com/webcpporg/trystero/tree/160f431) | | trystero | [bounded-json-parse](libraries/trystero/openspec/changes/bounded-json-parse) | trystero: bound the text and the objects a room parses | port of Trystero 0.26.0 | draft | | | | | trystero | [shared-connection](libraries/trystero/openspec/changes/archive/2026-11-14-shared-connection) | trystero: one connection shared by the rooms of an app | port of Trystero 0.26.0 | implemented | 0.1.0 | 2026-10-11 | [code](https://github.com/webcpporg/trystero/tree/e9326e94c06cfa9ffdbd0a8d3c8d72b80b3b9b59) | diff --git a/libraries/secure/openspec/changes/genesis/.openspec.yaml b/libraries/secure/openspec/changes/genesis/.openspec.yaml index 79160ff..89b05f2 100644 --- a/libraries/secure/openspec/changes/genesis/.openspec.yaml +++ b/libraries/secure/openspec/changes/genesis/.openspec.yaml @@ -5,7 +5,7 @@ webcpp: title: "secure: the side-channel and secret-in-memory primitives crypto, hash and codecs share (DIT guard, erase, secret, constant-time blocks), no algorithm" kind: own port_of: null - status: accepted + status: implementing release: null - implementation: null + implementation: https://github.com/webcpporg/secure decided: 2026-11-24 diff --git a/libraries/secure/openspec/changes/genesis/design.md b/libraries/secure/openspec/changes/genesis/design.md index b35609f..e4dd7ee 100644 --- a/libraries/secure/openspec/changes/genesis/design.md +++ b/libraries/secure/openspec/changes/genesis/design.md @@ -254,14 +254,14 @@ verdicts and secure's are marked alike. ```cpp namespace webcpp::secure::constant_time { -template U value_barrier(U value) noexcept; // opaque to the optimiser -template U mask_from_bit(U bit) noexcept; // 0 or 1 -> 0 or ~0 -template U is_zero_mask(U value) noexcept; // ~0 when value == 0 -template U is_equal_mask(U first, U second) noexcept; -template U is_less_mask(U first, U second) noexcept; // unsigned -template U is_in_range_mask(U value, U low, U high) noexcept; // low <= value <= high -template U select(U mask, U when_set, U when_clear) noexcept; -template +template U value_barrier(U value) noexcept; // opaque to the optimiser +template U mask_from_bit(U bit) noexcept; // 0 or 1 -> 0 or ~0 +template U is_zero_mask(U value) noexcept; // ~0 when value == 0 +template U is_equal_mask(U first, U second) noexcept; +template U is_less_mask(U first, U second) noexcept; // unsigned +template U is_in_range_mask(U value, U low, U high) noexcept; // low <= value <= high +template U select(U mask, U when_set, U when_clear) noexcept; +template Element lookup(std::span table, std::size_t index) noexcept; // reads every entry void select_bytes(std::uint8_t mask, std::span destination, std::span when_set, @@ -272,8 +272,9 @@ std::uint8_t less_mask(std::span first, std::span`, `constant_time_equal`, `declassify`, the blocks and their limits, the changelog; every example built and run; the guard's cost measured on release builds on an idle machine (D11) (plan task 9) +- [x] 6.1 The page: what secure is, the guard, erase, `secret`, `constant_time_equal`, `declassify`, the blocks and their limits, the changelog; every example built and run; the guard's cost measured on release builds on an idle machine (D11) (plan task 9) ## 7. hash on secure (owner decision 9) -- [ ] 7.1 Before it: hash's `origin/main` merged into its branch (never rebased), and any guard site a stream merged since (hkdf-pieces) moved with the rest (plan task 10) -- [ ] 7.2 Every guard site of hash on `secure::timing_guard` (its `engaged` arguments kept), every wipe on `secure::erase_secret` (B1), the wipe seam on secure's (B9); hash's `detail/timing.hpp` and `detail/wipe.hpp` deleted; hash's own `test/support/` seam recorder and DIT helper pointed at secure's seam; hash's build, `AGENTS.md`, page and "depends on" statements name secure; its MAC examples and pages name `secure::constant_time_equal`; crypto's `timing_hash_interop_test` deleted with hash's copy; generated pages regenerated by their generators (plan task 10) +- [x] 7.1 Before it: hash's `origin/main` merged into its branch (never rebased), and any guard site a stream merged since (hkdf-pieces) moved with the rest (plan task 10) +- [x] 7.2 Every guard site of hash on `secure::timing_guard` (its `engaged` arguments kept), every wipe on `secure::erase_secret` (B1), the wipe seam on secure's (B9); hash's `detail/timing.hpp` and `detail/wipe.hpp` deleted; hash's own `test/support/` seam recorder and DIT helper pointed at secure's seam; hash's build, `AGENTS.md`, page and "depends on" statements name secure; its MAC examples and pages name `secure::constant_time_equal`; crypto's `timing_hash_interop_test` deleted with hash's copy; generated pages regenerated by their generators (plan task 10) ## 8. crypto on secure (owner decision 9) -- [ ] 8.1 Every guard site, wipe, erase, comparison, secret and declassify of crypto on secure's names; crypto's `detail/timing.hpp`, `detail/wipe.hpp`, `detail/declassify.hpp`, `erase_secret.hpp`, `constant_time_equal.hpp` and `secret.hpp` deleted with no alias, and their tests moved to secure; crypto's constant-time lane on `WEBCPP_SECURE_CT_VALGRIND` and `WEBCPP_SECURE_CT_MSAN`; dudect and benches on `secure::cpu_has_dit()`; crypto's own `test/support/` seam recorder and a DIT helper of its own; `timing_nested_hash_test` in place of `timing_hash_interop_test`; generated pages regenerated by their generators (plan task 11) +- [x] 8.1 Every guard site, wipe, erase, comparison, secret and declassify of crypto on secure's names; crypto's `detail/timing.hpp`, `detail/wipe.hpp`, `detail/declassify.hpp`, `erase_secret.hpp`, `constant_time_equal.hpp` and `secret.hpp` deleted with no alias, and their tests moved to secure; crypto's constant-time lane on `WEBCPP_SECURE_CT_VALGRIND` and `WEBCPP_SECURE_CT_MSAN`; dudect and benches on `secure::cpu_has_dit()`; crypto's own `test/support/` seam recorder and a DIT helper of its own; `timing_nested_hash_test` in place of `timing_hash_interop_test`; generated pages regenerated by their generators (plan task 11) ## 9. The superproject -- [ ] 9.1 `CODING-GUIDELINES.md` chapter 17's entry for secure, and crypto's and hash's chapters' mentions of the moved names; `AGENTS.md`'s libraries and dependencies; `doc/releases/0.1.0.adoc`'s New Libraries and tools lines; the tools that list libraries; the gitlinks (plan task 12) +- [x] 9.1 `CODING-GUIDELINES.md` chapter 17's entry for secure, and crypto's and hash's chapters' mentions of the moved names; `AGENTS.md`'s libraries and dependencies; `doc/releases/0.1.0.adoc`'s New Libraries and tools lines; the tools that list libraries; the gitlinks (plan task 12) ## 10. The delivery From b427005b040969959f2c84b7222b2a90262e24cf Mon Sep 17 00:00:00 2001 From: R Date: Wed, 25 Nov 2026 18:43:03 -0300 Subject: [PATCH 4/8] secure genesis design: the signatures name the parameters the headers now have --- .../secure/openspec/changes/genesis/design.md | 34 +++++++++---------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/libraries/secure/openspec/changes/genesis/design.md b/libraries/secure/openspec/changes/genesis/design.md index e4dd7ee..be2f332 100644 --- a/libraries/secure/openspec/changes/genesis/design.md +++ b/libraries/secure/openspec/changes/genesis/design.md @@ -24,7 +24,7 @@ The primitives this library gathers exist today in three places, two of them cop (`test/constant_time/ctgrind_test.cpp`'s `memcheck` and `msan_test.cpp`'s primitives: `mark_secret`, `mark_public`, `traced`, `verdict`). - webcpp::hash (`libs/hash`): `include/webcpp/hash/detail/timing.hpp`, the same guard with - `WEBCPP_HASH_*` names and `timing_guard(bool engaged = true)`, a disengaged guard doing nothing, + `WEBCPP_HASH_*` names and `timing_guard(bool guard_engaged = true)`, a disengaged guard doing nothing, for functions keyed only by their arguments (28 sites); and its own `detail/wipe.hpp`. - config's change `timing-guard`, withdrawn on 2026-11-24 before any push (its branch is local: config `ba72ad4`, hash `43b6732`, crypto `b0c1f4f`, superproject `83c9a31`). It built one guard @@ -76,7 +76,7 @@ webcpp. ``. 4. **The guard:** `timing_guard` (DIT on arm64: Apple's systems, Linux and Android, Windows `_M_ARM64` through `_ReadStatusReg` and `_WriteStatusReg` with `isb`, FEAT_DIT probed once under - structured exception handling; empty elsewhere), `cpu_has_dit()`, `dit_is_set()`, the `engaged` + structured exception handling; empty elsewhere), `cpu_has_dit()`, `dit_is_set()`, the `guard_engaged` flag, the nesting rules and the test seam, with `WEBCPP_SECURE_*` macros; a public API of `webcpp::secure`, not `detail`, since it is the library's purpose. 5. **Moved from crypto with their names:** `erase_secret`, `constant_time_equal` and `secret`; @@ -128,7 +128,7 @@ namespace webcpp::secure { [[nodiscard]] bool dit_is_set() noexcept; // PSTATE.DIT of this thread; false where not covered class timing_guard { // not copyable, not movable public: - explicit timing_guard(bool engaged = true) noexcept; // + std::source_location under the seam + explicit timing_guard(bool guard_engaged = true) noexcept; // + std::source_location under the seam ~timing_guard(); }; } @@ -148,7 +148,7 @@ stays crypto's open measurement and applies here when made. The seam: without `WEBCPP_SECURE_TIMING_ENTERED` the constructor takes no source location, so no function name or path reaches a program. With it, the constructor's last parameter is -`std::source_location where = std::source_location::current()`, evaluated where the guard is +`std::source_location entry_location = std::source_location::current()`, evaluated where the guard is declared, so `function_name()` is the guarded function (crypto's, hash's, codecs' or secure's own `constant_time_equal`) and `file_name()` tells the library (`webcpp/crypto/`, `webcpp/hash/`, `webcpp/codecs/`, `webcpp/secure/`, either separator). @@ -227,7 +227,7 @@ copies a move or a `clone` leaves in registers or temporaries. namespace webcpp::secure { template requires std::is_trivially_copyable_v && (!std::is_const_v) -void declassify(T& value) noexcept; +void declassify(T& derived_value) noexcept; } // WEBCPP_SECURE_CT_VALGRIND or WEBCPP_SECURE_CT_MSAN: defined by a constant-time test build alone. ``` @@ -254,21 +254,21 @@ verdicts and secure's are marked alike. ```cpp namespace webcpp::secure::constant_time { -template U value_barrier(U value) noexcept; // opaque to the optimiser -template U mask_from_bit(U bit) noexcept; // 0 or 1 -> 0 or ~0 -template U is_zero_mask(U value) noexcept; // ~0 when value == 0 -template U is_equal_mask(U first, U second) noexcept; -template U is_less_mask(U first, U second) noexcept; // unsigned -template U is_in_range_mask(U value, U low, U high) noexcept; // low <= value <= high -template U select(U mask, U when_set, U when_clear) noexcept; +template U value_barrier(U word_value) noexcept; // opaque to the optimiser +template U mask_from_bit(U low_bit) noexcept; // 0 or 1 -> 0 or ~0 +template U is_zero_mask(U word_value) noexcept; // ~0 when word_value == 0 +template U is_equal_mask(U first_word, U second_word) noexcept; +template U is_less_mask(U first_word, U second_word) noexcept; // unsigned +template U is_in_range_mask(U word_value, U low_bound, U high_bound) noexcept; // low_bound <= word_value <= high_bound +template U select(U choice_mask, U when_set, U when_clear) noexcept; template -Element lookup(std::span table, std::size_t index) noexcept; // reads every entry -void select_bytes(std::uint8_t mask, std::span destination, +Element lookup(std::span table_entries, std::size_t entry_index) noexcept; // reads every entry +void select_bytes(std::uint8_t choice_mask, std::span destination_bytes, std::span when_set, std::span when_clear) noexcept; // equal sizes -std::uint8_t equal_mask(std::span first, std::span second) noexcept; -std::uint8_t is_zero_mask(std::span bytes) noexcept; -std::uint8_t less_mask(std::span first, std::span second) noexcept; // big-endian +std::uint8_t equal_mask(std::span first_bytes, std::span second_bytes) noexcept; +std::uint8_t is_zero_mask(std::span tested_bytes) noexcept; +std::uint8_t less_mask(std::span first_bytes, std::span second_bytes) noexcept; // big-endian } ``` From be0594e88c3a689ec7b70595f45b474d6252d35c Mon Sep 17 00:00:00 2001 From: R Date: Wed, 25 Nov 2026 18:49:20 -0300 Subject: [PATCH 5/8] secure: design.md keeps hash's own copy and the owner's decision in their words, engaged --- libraries/secure/openspec/changes/genesis/design.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/libraries/secure/openspec/changes/genesis/design.md b/libraries/secure/openspec/changes/genesis/design.md index be2f332..a9ac349 100644 --- a/libraries/secure/openspec/changes/genesis/design.md +++ b/libraries/secure/openspec/changes/genesis/design.md @@ -24,7 +24,7 @@ The primitives this library gathers exist today in three places, two of them cop (`test/constant_time/ctgrind_test.cpp`'s `memcheck` and `msan_test.cpp`'s primitives: `mark_secret`, `mark_public`, `traced`, `verdict`). - webcpp::hash (`libs/hash`): `include/webcpp/hash/detail/timing.hpp`, the same guard with - `WEBCPP_HASH_*` names and `timing_guard(bool guard_engaged = true)`, a disengaged guard doing nothing, + `WEBCPP_HASH_*` names and `timing_guard(bool engaged = true)`, a disengaged guard doing nothing, for functions keyed only by their arguments (28 sites); and its own `detail/wipe.hpp`. - config's change `timing-guard`, withdrawn on 2026-11-24 before any push (its branch is local: config `ba72ad4`, hash `43b6732`, crypto `b0c1f4f`, superproject `83c9a31`). It built one guard @@ -76,7 +76,7 @@ webcpp. ``. 4. **The guard:** `timing_guard` (DIT on arm64: Apple's systems, Linux and Android, Windows `_M_ARM64` through `_ReadStatusReg` and `_WriteStatusReg` with `isb`, FEAT_DIT probed once under - structured exception handling; empty elsewhere), `cpu_has_dit()`, `dit_is_set()`, the `guard_engaged` + structured exception handling; empty elsewhere), `cpu_has_dit()`, `dit_is_set()`, the `engaged` flag, the nesting rules and the test seam, with `WEBCPP_SECURE_*` macros; a public API of `webcpp::secure`, not `detail`, since it is the library's purpose. 5. **Moved from crypto with their names:** `erase_secret`, `constant_time_equal` and `secret`; From a0c2a843e35f3d6dc0f96a90b8a0e9d72769b157 Mon Sep 17 00:00:00 2001 From: R Date: Thu, 26 Nov 2026 01:32:28 -0300 Subject: [PATCH 6/8] secure genesis: the guard leaves DIT as found (set again when found set and cleared), Windows on ARM64's clear after a catch and the guard-free catch, timing_guard_exceptions on the Windows lane, the blocks need DIT on 64-bit ARM and dudect measures them inside a guard, the page's Exceptions section, and the risk --- .../secure/openspec/changes/genesis/design.md | 43 ++++++++++++++++--- .../changes/genesis/specs/secure/spec.md | 18 +++++--- 2 files changed, 49 insertions(+), 12 deletions(-) diff --git a/libraries/secure/openspec/changes/genesis/design.md b/libraries/secure/openspec/changes/genesis/design.md index a9ac349..47811d0 100644 --- a/libraries/secure/openspec/changes/genesis/design.md +++ b/libraries/secure/openspec/changes/genesis/design.md @@ -137,10 +137,12 @@ public: ``` Behaviour, the two copies' and the withdrawn change's: an engaged guard runs the seam (in a test's -build), then sets DIT if the CPU has it and it is clear, and remembers to clear it; its destructor -clears DIT only if it set it. A disengaged guard does nothing, the seam included. So guards nest -in any order of libraries (crypto inside hash, hash inside crypto, codecs inside either): an inner -guard finds DIT set and leaves it, and a program that set DIT itself (Apple's +build), then sets DIT if the CPU has it and it is clear, and remembers what it found; its +destructor leaves DIT as found: it clears DIT if it set it, and, if it found DIT set, reads it +again (a second `mrs`) and sets it if something inside its scope cleared it, as Windows on ARM64 +does on resuming a thread after a catch (D3). A disengaged guard does nothing, the seam included. +So guards nest in any order of libraries (crypto inside hash, hash inside crypto, codecs inside +either): an inner guard finds DIT set and leaves it set, and a program that set DIT itself (Apple's `timingsafe_enable_if_supported`) keeps it. DIT is a thread's state; a guard never changes another thread's. Each write keeps its `memory` clobber (or the intrinsics' ordering on MSVC) and an `isb` after it; which barrier each write needs (Apple asks for `sb` or `dsb nsh; isb sy` after setting) @@ -180,6 +182,17 @@ or off. That read is the only DIT instruction executed where FEAT_DIT may be abs registry's per-processor `CP 4020` value (undocumented, needs advapi32); leaving Windows on ARM64 uncovered. +Windows on ARM64 and exceptions, measured on the owner's VM with MSVC 14.3 and 14.5, debug and +release (Microsoft documents none of it): the system keeps DIT through the search for a handler, +the unwinding and the catch block, then resumes the thread after the catch, or in an `__except` +block, with DIT clear, from set as from clear (`RtlRestoreContext` clears it whatever bit 24 of +the context's `Cpsr` says). A guard whose scope holds the catch leaves DIT as it found it at its +end (D2); code that computes on a secret after such a catch holds a guard of its own; code that +catches inside a guarded scope and returns into a C library (crypto's OpenSSL memory adapter) +holds, around its `try`, a guard engaged only when DIT is set; after a catch outside every guard, +a guard-free catch, DIT is clear, which no destructor can change, and a program that wants DIT +there sets it again. On Apple's systems and Linux DIT after a catch is as the unwinding left it. + ### D4. `erase_secret` and the wipe `secure::erase_secret(Range&&)` is crypto's, moved: a contiguous sized range of non-const, @@ -250,7 +263,12 @@ verdicts and secure's are marked alike. ### D8. The constant-time building blocks ``, namespace `webcpp::secure::constant_time`, every function -`constexpr` where the language allows, `noexcept`, branch-free and index-free on its data: +`constexpr` where the language allows, `noexcept`, branch-free and index-free on its data. On 64-bit +ARM that is not enough for a time independent of the data: Arm promises it only for the +instructions it lists and only with DIT set, and MSVC 14.5's branch-free, index-free `lookup` was +measured with a dudect |t| of 11 to 17.5 with DIT clear on Windows on ARM64 and under 3 with DIT +set; a caller that runs the blocks on a secret holds a guard (D2), as every guarded function of +webcpp does: ```cpp namespace webcpp::secure::constant_time { @@ -319,6 +337,9 @@ every library's do. `timing_guard_nesting_test` (three levels, every order of engaged and disengaged), `timing_guard_seam_test` (the seam's `function_name()` and `file_name()`, `timing_guard{true}`, nothing fired by a disengaged guard, nothing named in a build without the seam), + `timing_guard_exceptions_test` (an exception through nested guards and caught inside and outside + them, and DIT cleared inside a scope: each guard leaves DIT as found, on every target, with + exceptions on and off, and on the Windows ARM64 lane), `timing_guard_threads_test` (another thread's DIT unchanged, natively where the build has threads), `timing_guard_windows_test` (D3, on the Windows ARM64 lane), each header compiled first and alone; on a target not covered, `std::is_empty_v` and both functions @@ -339,7 +360,8 @@ every library's do. - **Constant time:** the own lane `constant-time` (`test/constant_time/`): memcheck with the operands marked undefined (ctgrind) over every block, `constant_time_equal` and `secret`'s moves, MemorySanitizer where crypto runs it, dudect natively with its A/A control over - `constant_time_equal`, `lookup`, `select_bytes` and `less_mask`, and a planted leak (a `select` + `constant_time_equal`, `lookup`, `select_bytes` and `less_mask`, each block inside a guard as a + guarded caller runs it (D8), and a planted leak (a `select` written with a branch, a `lookup` that indexes) that must fail on each checker. ### D11. Lanes, documentation, measurements @@ -348,7 +370,8 @@ Every test runs on native (clang and gcc 15), wasip2, wasip3 and Emscripten, eac `_no_exceptions` twin; MSVC 14.3 and 14.5 (x64 and arm64) and Apple clang as the other libraries; the Windows ARM64 lane on the owner's VM for the guard (D3), in a release build too, which the withdrawn change did not run; the own lane `constant-time`; the lint. The page (`doc/`): what -secure is and is not, the guard (coverage table, nesting, engaged, the seam), erasing, `secret`, +secure is and is not, the guard (coverage table, nesting, engaged, exceptions, the seam), erasing, +`secret`, `constant_time_equal`, `declassify`, the blocks with their limits (what DIT and masks cover and what the compiler may still do), and the changelog. One measurement: the guard's cost on release builds (engaged with DIT clear, engaged with DIT set, disengaged) on an idle machine, since the withdrawn @@ -389,6 +412,12 @@ to the owner. an empty guard's effect); the Windows lane's test fails if a CPU known to have DIT reads absent. - [The probe's absent path is untested] -> no machine without FEAT_DIT runs Windows on ARM64 here; the filter is small and reviewed, and the page says so. +- [Windows on ARM64 clears DIT after a catch] -> each guard leaves DIT as found at its end (D2), + crypto's OpenSSL memory adapter keeps DIT set across its catches, and the guard's page tells a + program to hold a guard after a catch inside a guarded scope and to set DIT again after a catch + of its own; third-party code that catches internally inside a guarded call (a C library's own + catches, a program's memory resource) runs with DIT clear after its catch until the guard ends, + which webcpp cannot reach. - [`lookup` costs the table's size] -> codecs' tables are at most 64 entries; a caller with a larger public table indexes it directly. diff --git a/libraries/secure/openspec/changes/genesis/specs/secure/spec.md b/libraries/secure/openspec/changes/genesis/specs/secure/spec.md index b49c43c..8428ae6 100644 --- a/libraries/secure/openspec/changes/genesis/specs/secure/spec.md +++ b/libraries/secure/openspec/changes/genesis/specs/secure/spec.md @@ -12,7 +12,7 @@ The library SHALL be header-only C++20 in namespace `webcpp::secure` (with `webc - **THEN** it compiles, and `WEBCPP_VERSION` is defined after it ### Requirement: Timing guard: DIT for a scope, nesting across libraries -`` SHALL declare `secure::timing_guard`, `secure::cpu_has_dit()` and `secure::dit_is_set()`, public names of the library and the only DIT guard of webcpp. An engaged guard (`timing_guard{}` or `timing_guard{true}`) MUST set PSTATE.DIT for its scope when the CPU has FEAT_DIT and DIT is clear, and clear it on destruction only when it set it; a guard that finds DIT set MUST leave it set; a disengaged guard (`timing_guard{false}`) MUST do nothing. Each write of DIT MUST be followed by an `isb`. The guard MUST NOT be copyable or movable, MUST NOT change another thread's DIT, and MUST NOT execute a DIT instruction on a CPU without FEAT_DIT but the one probe Windows needs. `cpu_has_dit()` MUST be read once per process. +`` SHALL declare `secure::timing_guard`, `secure::cpu_has_dit()` and `secure::dit_is_set()`, public names of the library and the only DIT guard of webcpp. An engaged guard (`timing_guard{}` or `timing_guard{true}`) MUST set PSTATE.DIT for its scope when the CPU has FEAT_DIT and DIT is clear, and MUST leave DIT at its end as it found it: clear it when it set it, and, when it found DIT set, set it again if DIT was cleared within its scope (as Windows on ARM64 does when it resumes a thread after a catch); a guard that finds DIT set MUST leave it set; a disengaged guard (`timing_guard{false}`) MUST do nothing. Each write of DIT MUST be followed by an `isb`. The guard MUST NOT be copyable or movable, MUST NOT change another thread's DIT, and MUST NOT execute a DIT instruction on a CPU without FEAT_DIT but the one probe Windows needs. `cpu_has_dit()` MUST be read once per process. #### Scenario: Guards nest - **WHEN** a test constructs three engaged guards nested, as codecs inside crypto inside hash would, with a disengaged one between them, on a CPU with DIT and DIT clear @@ -22,6 +22,14 @@ The library SHALL be header-only C++20 in namespace `webcpp::secure` (with `webc - **WHEN** a thread sets DIT itself and then constructs and destroys an engaged guard - **THEN** DIT is set after the guard ends +#### Scenario: DIT cleared inside a guard's scope is as found after the guard +- **WHEN** DIT is cleared within an engaged guard's scope, by a catch inside it on Windows on ARM64 or by the test itself on any CPU with DIT, the guard having found DIT set, or having set it +- **THEN** DIT is set after the guard that found it set ends, and clear after the guard that set it ends, at every level of nested guards + +#### Scenario: A catch outside every guard on Windows on ARM64 +- **WHEN** an exception thrown inside an engaged guard is caught outside every guard on Windows on ARM64 +- **THEN** each destructor run during the unwinding and the catch block see DIT as the code before them left it, the guard having left it as found, and after the catch DIT is clear, from set as from clear, which a program that wants DIT there sets again + #### Scenario: Another thread is untouched - **WHEN** one thread holds an engaged guard while another thread, with DIT clear, reads `dit_is_set()` - **THEN** the other thread reads false, natively where the build has threads @@ -30,8 +38,8 @@ The library SHALL be header-only C++20 in namespace `webcpp::secure` (with `webc The guard SHALL act, and `WEBCPP_SECURE_TIMING_COVERED` SHALL be defined, on arm64 under Apple's systems (FEAT_DIT from `sysctlbyname("hw.optional.arm.FEAT_DIT")`), under Linux and Android (`HWCAP_DIT` of `AT_HWCAP`), and under Windows with `_MSC_VER`, `_M_ARM64` and not `_M_ARM64EC` (the register through `_ReadStatusReg` and `_WriteStatusReg` and `__isb`, FEAT_DIT from one read of the register under structured exception handling, `STATUS_ILLEGAL_INSTRUCTION` meaning absent, other exceptions passed on). On every other target the guard MUST be an empty class that executes no instruction, and `cpu_has_dit()` and `dit_is_set()` MUST return false. #### Scenario: Windows on ARM64 -- **WHEN** `timing_guard_windows_test` runs on the Windows 11 ARM64 lane with MSVC 14.3 and 14.5, debug and release, with exceptions on and off -- **THEN** `cpu_has_dit()` is true on that CPU, DIT is set inside a guard, still set after the thread sleeps inside it, and clear after it +- **WHEN** `timing_guard_windows_test` and `timing_guard_exceptions_test` run on the Windows 11 ARM64 lane with MSVC 14.3 and 14.5, debug and release, with exceptions on and off +- **THEN** `cpu_has_dit()` is true on that CPU, DIT is set inside a guard, still set after the thread sleeps inside it, and clear after it, and every guard leaves DIT as it found it after an exception caught inside its scope #### Scenario: WebAssembly and x86 - **WHEN** the guard's tests run on wasip2, wasip3, Emscripten and x86-64 @@ -100,7 +108,7 @@ A macro `WEBCPP_SECURE_TIMING_ENTERED(where)`, defined by a test alone before it - **THEN** no conditional jump and no address depends on them, while the planted branching `select` and indexing `lookup` are reported #### Scenario: dudect judges -- **WHEN** dudect measures `constant_time_equal`, `lookup`, `select_bytes` and `less_mask` with two classes of input natively +- **WHEN** dudect measures `constant_time_equal`, `lookup`, `select_bytes` and `less_mask` with two classes of input natively, each block inside a `timing_guard` as a guarded caller runs it (`constant_time_equal` holds its own) - **THEN** each case's |t| stays below the threshold, its A/A control too, and the planted leak exceeds it ### Requirement: Tests and lanes @@ -111,7 +119,7 @@ Every test of the library SHALL run on native (clang and gcc 15), wasip2, wasip3 - **THEN** the counter is zero after every call, on every target ### Requirement: Documentation -The library SHALL have its page under `libs/secure/doc/`, built by `b2 doc`: what secure is and is not (no algorithm), the guard (its coverage table, nesting, `engaged`, the seam), `erase_secret`, `secret`, `constant_time_equal`, `declassify`, the constant-time blocks with their limits, the guard's measured cost from release builds, and the changelog, every example built and run in the lanes. +The library SHALL have its page under `libs/secure/doc/`, built by `b2 doc`: what secure is and is not (no algorithm), the guard (its coverage table, nesting, `guard_engaged`, exceptions, the seam), `erase_secret`, `secret`, `constant_time_equal`, `declassify`, the constant-time blocks with their limits, the guard's measured cost from release builds, and the changelog, every example built and run in the lanes. #### Scenario: The page builds - **WHEN** `b2 doc` runs in the superproject From c4db64e45f95d9cd60f7dbc864ba82c6752fd1b8 Mon Sep 17 00:00:00 2001 From: R Date: Thu, 26 Nov 2026 03:43:47 -0300 Subject: [PATCH 7/8] secure, hash: tasks state the guard's idle re-measurement (37.0 ns clear, 1.2 ns set) --- .../hash/openspec/changes/data-independent-timing/tasks.md | 4 ++-- libraries/secure/openspec/changes/genesis/tasks.md | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/libraries/hash/openspec/changes/data-independent-timing/tasks.md b/libraries/hash/openspec/changes/data-independent-timing/tasks.md index 4f6582e..2a9b0e4 100644 --- a/libraries/hash/openspec/changes/data-independent-timing/tasks.md +++ b/libraries/hash/openspec/changes/data-independent-timing/tasks.md @@ -23,8 +23,8 @@ increment 6 (Botan) merges (design D8). ## Open -- [ ] The final quiet measurement pass measures the guard's cost again and regenerates the - throughput tables (design.md, "As built"). +- [ ] The final quiet measurement pass regenerates the throughput tables (design.md, "As built"); + the guard's cost was measured again on an idle machine on 2026-11-26 (clear 37.0 ns, set 1.2 ns). - [ ] crypto's `detail/timing.hpp` names hash's copy at crypto's next change of it. - [ ] The MSVC lane's known-failures list gains the seven no-exceptions builds of the Boost.JSON class. diff --git a/libraries/secure/openspec/changes/genesis/tasks.md b/libraries/secure/openspec/changes/genesis/tasks.md index 5593c75..e7d1f41 100644 --- a/libraries/secure/openspec/changes/genesis/tasks.md +++ b/libraries/secure/openspec/changes/genesis/tasks.md @@ -39,7 +39,7 @@ no `webcpp::core` is made. ## 6. The documentation -- [x] 6.1 The page: what secure is, the guard, erase, `secret`, `constant_time_equal`, `declassify`, the blocks and their limits, the changelog; every example built and run; the guard's cost measured on release builds on an idle machine (D11) (plan task 9) +- [x] 6.1 The page: what secure is, the guard, erase, `secret`, `constant_time_equal`, `declassify`, the blocks and their limits, the changelog; every example built and run; the guard's cost measured on release builds on an idle machine (D11) (plan task 9; 2026-11-26, load 1.9: clear 37.0 ns, set 1.2 ns, disengaged 0.0 ns) ## 7. hash on secure (owner decision 9) From 849455b813e43ba388b6a9387b37e6a34607bcf6 Mon Sep 17 00:00:00 2001 From: R Date: Thu, 26 Nov 2026 06:02:12 -0300 Subject: [PATCH 8/8] secure: genesis task 10.1 done, merged in order (secure#1, hash#15, crypto#19, webcpp#59); the status stays implementing until the CI on main --- libraries/secure/openspec/changes/genesis/tasks.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries/secure/openspec/changes/genesis/tasks.md b/libraries/secure/openspec/changes/genesis/tasks.md index e7d1f41..025ad9b 100644 --- a/libraries/secure/openspec/changes/genesis/tasks.md +++ b/libraries/secure/openspec/changes/genesis/tasks.md @@ -56,4 +56,4 @@ no `webcpp::core` is made. ## 10. The delivery -- [ ] 10.1 hash's `origin/main` merged again, and any new guard site migrated; full local verification on every lane (native clang and gcc 15, MSVC 14.3 and 14.5, the Windows ARM64 lane, wasip2, wasip3, Emscripten, the constant-time lanes of secure and crypto, the Linux lint), exceptions on and off; the review; pull requests, merged in order secure, hash, crypto, the superproject, the proposals; one CI at the end (plan task 13) +- [x] 10.1 hash's `origin/main` merged again, and any new guard site migrated; full local verification on every lane (native clang and gcc 15, MSVC 14.3 and 14.5, the Windows ARM64 lane, wasip2, wasip3, Emscripten, the constant-time lanes of secure and crypto, the Linux lint), exceptions on and off; the review; pull requests, merged in order secure, hash, crypto, the superproject, the proposals; one CI at the end (plan task 13); done 2026-11-26 but for that CI, which is the owner's to run, so the status stays implementing (CONTRIBUTING step 5)