From ff5b365053b813491e1e6303f05bfd9a96aadf6a Mon Sep 17 00:00:00 2001 From: R Date: Sun, 22 Nov 2026 07:16:17 -0300 Subject: [PATCH 01/27] hash: detail::timing_guard sets arm64's DIT for its scope and restores the thread's state, hash's own copy of crypto's with an engaged flag --- include/webcpp/hash/detail/timing.hpp | 215 ++++++++++++++++++ meta/include-boundaries.json | 1 + test/Jamfile | 16 ++ test/support/timing_seam.hpp | 308 ++++++++++++++++++++++++++ test/timing_test.cpp | 240 ++++++++++++++++++++ test/timing_unseamed_test.cpp | 137 ++++++++++++ 6 files changed, 917 insertions(+) create mode 100644 include/webcpp/hash/detail/timing.hpp create mode 100644 test/support/timing_seam.hpp create mode 100644 test/timing_test.cpp create mode 100644 test/timing_unseamed_test.cpp diff --git a/include/webcpp/hash/detail/timing.hpp b/include/webcpp/hash/detail/timing.hpp new file mode 100644 index 0000000..03acd7a --- /dev/null +++ b/include/webcpp/hash/detail/timing.hpp @@ -0,0 +1,215 @@ +// 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_HASH_DETAIL_TIMING_HPP +#define WEBCPP_HASH_DETAIL_TIMING_HPP + +#include + +/* + * timing_guard sets 64-bit ARM's DIT (Data Independent Timing) bit, PSTATE.DIT, for the scope of + * one public operation 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 hash calls sets it. Every public function that + * computes on a key holds one as its first statement. + * + * This is hash's own copy of the guard of webcpp::crypto, not an include of it: hash depends on + * no other webcpp library, and crypto's detail headers are not hash's to include (config's rule + * on dependencies, and the direction of the dependency). The other copy is + * libs/crypto/include/webcpp/crypto/detail/timing.hpp, and what keeps the two in step is + * libs/crypto/test/timing_hash_interop_test.cpp, which runs both guards nested and checks that + * each leaves the thread's DIT as it found it. A change to one is a change to the other. + * + * The one difference is the constructor's `engaged` flag. Some of hash's functions are keyed only + * by their arguments (a BLAKE2b digest of a call that passes a key, a BLAKE3 object made with a + * key), and an unkeyed call of the same function computes on public data and must not pay for + * DIT: those functions construct the guard with `engaged` false when the call is not keyed. A + * disengaged guard sets nothing and clears nothing; on a target the guard does not cover, + * `engaged` is read only to fire the seam. + * + * The guard applies on arm64 under macOS, iOS, Linux and Android, where the system says whether + * the CPU has FEAT_DIT. Everywhere else (x86, WebAssembly, where the engine decides, and Windows + * on ARM64, which documents no way to ask) 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_HASH_DETAIL_TIMING_COVERED 1 +#include +#include +#ifdef __APPLE__ +#include +#else +#include +#endif +#endif + +/* + * WEBCPP_HASH_DETAIL_TIMING_ENTERED(where), the seam, is defined by a test alone, before its + * first include, to record the guards a call enters and the function of the first, the outermost + * (test/support/timing_seam.hpp), so that a public 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 runs the seam with it first, on every + * target. Nothing in a program's build: without the seam the constructor takes no argument, so + * that no function's name or header's path reaches a program, whether the constructor is + * inlined or not. + */ +#ifdef WEBCPP_HASH_DETAIL_TIMING_ENTERED +#include +#endif + +namespace webcpp::hash::detail { + +#ifdef WEBCPP_HASH_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; + +/** + * 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 measured in the final measurement pass of the change data-independent-timing. + * + * @param value `dit_bit` to set DIT, 0 to clear it. + */ +inline void write_dit(std::uint64_t value) noexcept { + __asm__ volatile("msr s3_3_c4_c2_5, %0\n\tisb" : : "r"(value) : "memory"); +} +#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; `HWCAP_DIT` (bit 24 of `AT_HWCAP`) on Linux. Executing DIT's instructions on a CPU + * without it traps, so nothing 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_HASH_DETAIL_TIMING_COVERED) && defined(__APPLE__) + static bool const has_dit = [] { + int feature = 0; + std::size_t size = sizeof feature; + return sysctlbyname("hw.optional.arm.FEAT_DIT", &feature, &size, nullptr, 0) == 0 && + feature != 0; + }(); + return has_dit; +#elif defined(WEBCPP_HASH_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`, 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_HASH_DETAIL_TIMING_COVERED + if (!cpu_has_dit()) { + return false; + } + std::uint64_t state = 0; + __asm__ volatile("mrs %0, s3_3_c4_c2_5" : "=r"(state) : : "memory"); + return (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 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, so that guards nest 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, equal's 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_HASH_DETAIL_TIMING_ENTERED + /** + * Runs the seam, then sets DIT where `engaged`, the CPU has it and it is clear: a test's + * build alone. + * + * @param engaged Whether the call is keyed; false makes the guard do nothing but fire the + * seam. + * @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 { + WEBCPP_HASH_DETAIL_TIMING_ENTERED(where); + enter(engaged); + } +#else + /** + * Sets DIT where `engaged`, the CPU has it and it is clear. + * + * @param engaged Whether the call is keyed; false makes the guard do nothing. + */ + explicit timing_guard(bool engaged = true) noexcept { enter(engaged); } +#endif + + /** Clears DIT when this guard set it. */ + ~timing_guard() { +#ifdef WEBCPP_HASH_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 `engaged`, the CPU has it and it is clear, and remembers to clear it. + * + * @param engaged Whether the call is keyed. + */ + void enter([[maybe_unused]] bool engaged) noexcept { +#ifdef WEBCPP_HASH_DETAIL_TIMING_COVERED + if (engaged && cpu_has_dit() && !dit_is_set()) { + write_dit(dit_bit); + armed_ = true; + } +#endif + } + +#ifdef WEBCPP_HASH_DETAIL_TIMING_COVERED + /** Whether this guard set DIT, and so clears it. */ + bool armed_ = false; +#endif +}; + +} // namespace webcpp::hash::detail + +#endif // WEBCPP_HASH_DETAIL_TIMING_HPP diff --git a/meta/include-boundaries.json b/meta/include-boundaries.json index 79592e0..7b153d3 100644 --- a/meta/include-boundaries.json +++ b/meta/include-boundaries.json @@ -21,6 +21,7 @@ "include/webcpp/hash/backends/hash2.hpp", "include/webcpp/hash/detail/engines.hpp", "include/webcpp/hash/detail/limits.hpp", + "include/webcpp/hash/detail/timing.hpp", "include/webcpp/hash/detail/wipe.hpp", "include/webcpp/hash/hkdf.hpp", "include/webcpp/hash/kdf.hpp", diff --git a/test/Jamfile b/test/Jamfile index ed59ae5..e591764 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -65,6 +65,7 @@ webcpp.headers-alone hash : ../include : hash/config.hpp hash/detail/engines.hpp hash/detail/limits.hpp + hash/detail/timing.hpp hash/detail/wipe.hpp hash/detail/xkcp.hpp hash/digest.hpp @@ -693,6 +694,21 @@ hash-run allocation_openssl : allocation_openssl_test.cpp wasi:-Wl,--wrap=malloc,--wrap=calloc,--wrap=realloc,--wrap=aligned_alloc,--wrap=posix_memalign : native wasip2 wasip3 ; +# detail::timing_guard sets DIT for its scope where the CPU has it and leaves +# the thread's state as it found it; its seam fires on every target, engaged +# or not. timing_threads adds a second thread, natively, with threads. +hash-run timing : timing_test.cpp ; +hash-run timing_threads : timing_test.cpp + : multi WEBCPP_TEST_TIMING_THREADS : native ; +# Without the seam, the guard takes a bool and no source_location, on every +# target; natively, at release, a program that calls mac reads its own +# executable and finds neither mac's name nor mac.hpp's path, which a guard's +# source_location would keep where its constructor is not inlined (clang on +# arm64). +hash-run timing_unseamed : timing_unseamed_test.cpp ; +webcpp.run timing_unseamed_release : timing_unseamed_test.cpp + : release WEBCPP_TEST_TIMING_READ_SELF : native ; + build-project messages ; # The canaries at link time, each C library's absence and another commit of diff --git a/test/support/timing_seam.hpp b/test/support/timing_seam.hpp new file mode 100644 index 0000000..c5d1e2e --- /dev/null +++ b/test/support/timing_seam.hpp @@ -0,0 +1,308 @@ +// 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 detail::timing_guard, recorded: a test includes this header before any hash +// header, so that every guard a call enters raises timing_entries and the first records the +// function that holds it, on every target, also where DIT does not apply. require_enters then +// checks that a call entered a guard, and that the first, the outermost since a guard is its +// function's first statement, is the one of the function the check names: a public function that +// forgot its own guard fails, also when it calls another guarded function. uncovered checks the +// converse: a function that calls no backend's code enters no guard. +// +// This is a copy of libs/crypto/test/support/timing_seam.hpp with hash's macro: the duplication is +// accepted for the reason of detail/timing.hpp's own (hash includes nothing of crypto). + +#ifndef WEBCPP_TEST_HASH_SUPPORT_TIMING_SEAM_HPP +#define WEBCPP_TEST_HASH_SUPPORT_TIMING_SEAM_HPP + +#ifdef WEBCPP_HASH_DETAIL_TIMING_HPP +#error "support/timing_seam.hpp must be included before any hash header" +#endif + +#include + +#include +#include +#include +#include +#include + +namespace webcpp::test { + +/** The number of detail::timing_guard objects this thread has constructed. */ +// 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 detail::timing_guard 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; + +/** + * Records the entry into a detail::timing_guard: counts it, and keeps its function when it is the + * first since timing_first_entry was reset. + * + * @param where Where the guard is declared. + */ +inline void timing_entered(std::source_location const& where) noexcept { + ++timing_entries; + if (timing_first_entry == nullptr) { + timing_first_entry = where.function_name(); + } +} + +} // namespace webcpp::test + +/** Records the entry into a detail::timing_guard declared at `where`. */ +#define WEBCPP_HASH_DETAIL_TIMING_ENTERED(where) (::webcpp::test::timing_entered(where)) + +namespace webcpp::test { + +/** + * A function as a check names it: its identifier, the scope that qualifies it, and optionally a + * word its parameter list holds, for overloads of one scope and name. + */ +struct named_function { + /** The class or namespace that qualifies it, unqualified and without template arguments. */ + std::string scope; + /** Its name: an identifier, or `operator` and its symbol (`operator==`). */ + std::string identifier; + /** A word its parameter list holds, or empty for any. */ + std::string parameter; +}; + +/** + * Reads a function, spelled `::::`, optionally followed by + * `(`, or by a space and words that say how it is called. + * + * The scope is the component before the identifier, empty when there is none. A check named + * `pem::algorithm::unarmour of a text without lines on sodium` names `algorithm::unarmour`; + * `secp256k1::equal(digest` names `secp256k1::equal` with a parameter list that holds `digest`. + * + * @param spelled The function as a check spells it. + * @return Its scope, identifier and parameter word. + */ +inline named_function function_named(std::string_view spelled) { + named_function named; + std::size_t const end = spelled.find_first_of(" ("); + if (end != std::string_view::npos && spelled[end] == '(') { + std::string_view const rest = spelled.substr(end + 1); + named.parameter = std::string(rest.substr(0, rest.find_first_of(" ,)"))); + } + std::string_view const qualified = spelled.substr(0, end); + std::size_t const separator = qualified.rfind("::"); + if (separator == std::string_view::npos) { + named.identifier = std::string(qualified); + return named; + } + named.identifier = std::string(qualified.substr(separator + 2)); + std::string_view const qualifiers = qualified.substr(0, separator); + std::size_t const scope_separator = qualifiers.rfind("::"); + named.scope = std::string(scope_separator == std::string_view::npos + ? qualifiers + : qualifiers.substr(scope_separator + 2)); + return named; +} + +/** Whether `character` can be part of an identifier. */ +constexpr bool identifier_character(char character) noexcept { + return (character >= 'a' && character <= 'z') || (character >= 'A' && character <= 'Z') || + (character >= '0' && character <= '9') || character == '_'; +} + +/** + * A `function_name()` in one spelling for clang, GCC and MSVC: the template arguments clang and + * GCC append (` [B = ...]`, ` [with B = ...]`) cut, and the space MSVC puts between `operator` + * and its symbol (`operator ==`) removed. + * + * @param entered A `function_name()`. + * @return The same function, spelled for the search of `names_function`. + */ +inline std::string normalized_function_name(std::string_view entered) { + std::string normal(entered.substr(0, entered.find(" ["))); + constexpr std::string_view operator_word = "operator "; + for (std::size_t found = normal.find(operator_word); found != std::string::npos; + found = normal.find(operator_word, found + 1)) { + std::size_t const symbol = found + operator_word.size(); + if (symbol < normal.size() && !identifier_character(normal[symbol])) { + normal.erase(symbol - 1, 1); + } + } + return normal; +} + +/** + * The component that qualifies a name, read back from the `::` before it at `separator`: + * `algorithm` in `pem::algorithm::armour`, its template arguments skipped. + * + * @param text A normalized `function_name()`. + * @param separator The position of the `::` before the name. + * @return The qualifying component, unqualified, or empty. + */ +inline std::string_view qualifier_before(std::string_view text, std::size_t separator) { + std::size_t end = separator; + if (end > 0 && text[end - 1] == '>') { + std::size_t depth = 0; + while (end > 0) { + --end; + if (text[end] == '>') { + ++depth; + } else if (text[end] == '<' && --depth == 0) { + break; + } + } + } + std::size_t begin = end; + while (begin > 0 && identifier_character(text[begin - 1])) { + --begin; + } + return text.substr(begin, end - begin); +} + +/** + * The position of the `(` that opens a function's own parameter list in a normalized + * `function_name()`: the one matching its last `)`, so that parentheses and template arguments in + * the return type and the parameter types are skipped. + * + * @param text A normalized `function_name()`. + * @return The position, or `npos` when there is no parameter list. + */ +inline std::size_t parameter_list_of(std::string_view text) { + std::size_t position = text.rfind(')'); + if (position == std::string_view::npos) { + return position; + } + std::size_t depth = 0; + while (true) { + if (text[position] == ')') { + ++depth; + } else if (text[position] == '(' && --depth == 0) { + return position; + } + if (position == 0) { + return std::string_view::npos; + } + --position; + } +} + +/** + * Whether a `function_name()` is the named function: its own name, the qualified name before its + * outermost parameter list (and before the template arguments MSVC writes there), ends with + * `::::`, its scope read without template arguments, and its parameter list + * holds the named word. A name in the return type or a parameter type never counts, a named + * function without a scope never matches, and a lambda's (`(lambda)`, `(anonymous class)`, + * ``, ``) never is: a guard belongs at the top of the public function, not in + * a lambda in it. + * + * @param entered A `function_name()`, as clang, GCC or MSVC spells it. + * @param named The function a check names. + * @return Whether `entered` is `named`. + */ +inline bool names_function(std::string_view entered, named_function const& named) { + if (named.scope.empty() || entered.find("lambda") != std::string_view::npos || + entered.find("anonymous class") != std::string_view::npos) { + return false; + } + std::string const normal = normalized_function_name(entered); + std::string_view const text = normal; + std::size_t const open = parameter_list_of(text); + if (open == std::string_view::npos) { + return false; + } + std::string const needle = "::" + named.identifier; + std::string_view name = text.substr(0, open); + if (!name.ends_with(needle) && name.ends_with('>')) { + // MSVC writes a function template's arguments after its name: armour(. + std::size_t depth = 0; + std::size_t end = name.size(); + while (end > 0) { + --end; + if (name[end] == '>') { + ++depth; + } else if (name[end] == '<' && --depth == 0) { + break; + } + } + name = name.substr(0, end); + } + if (!name.ends_with(needle) || + qualifier_before(text, name.size() - needle.size()) != named.scope) { + return false; + } + std::string_view const parameters = text.substr(open, text.rfind(')') - open); + return named.parameter.empty() || parameters.find(named.parameter) != std::string_view::npos; +} + +/** + * Runs `call` and reports an error when it entered no detail::timing_guard, or when the first + * guard it entered is not the one of `function`. + * + * @param name What the call is, as an error names it. + * @param function The function whose guard the call must enter first, as `function_named` reads + * it: `::` where the name cannot say it (an alias of a class template, an + * operator, a constructor, overloads). + * @param call The call, with its arguments bound. + */ +template +void require_enters(std::string_view name, std::string_view function, Call&& call) { + std::size_t const before = timing_entries; + timing_first_entry = nullptr; + std::forward(call)(); + if (timing_entries == before) { + std::string const message = std::string(name) + " did not enter detail::timing_guard"; + BOOST_ERROR(message.c_str()); + } else if (function_named(function).scope.empty()) { + std::string const message = + std::string(name) + " names no scope: give the function, ::"; + BOOST_ERROR(message.c_str()); + } else if (!names_function(timing_first_entry, function_named(function))) { + std::string const message = std::string(name) + + " entered first the detail::timing_guard of " + + timing_first_entry + ", not its own"; + BOOST_ERROR(message.c_str()); + } + timing_first_entry = nullptr; +} + +/** + * Runs `call` and reports an error when it entered no detail::timing_guard, or when the first + * guard it entered is not the one of the function the name begins with. + * + * @param name What the call is, `::::[ how] on `, which + * names the function as `function_named` reads it. + * @param call The call, with its arguments bound. + */ +template +void require_enters(std::string_view name, Call&& call) { + require_enters(name, name, std::forward(call)); +} + +/** + * Runs `call` and reports an error when it entered a detail::timing_guard: a public function that + * calls no backend's code holds none (the data-independent-timing change of hash). A guard + * added to one by mistake costs every call, and makes the rule "a guard where the backend runs" + * harder to check. + * + * @param name What the call is, `:: on `, as an error names it. + * @param call The call, with its arguments bound. + */ +template +void uncovered(std::string_view name, Call&& call) { + std::size_t const before = timing_entries; + std::forward(call)(); + if (timing_entries != before) { + std::string const message = + std::string(name) + " entered a detail::timing_guard it should not hold"; + BOOST_ERROR(message.c_str()); + } +} + +} // namespace webcpp::test + +#endif // WEBCPP_TEST_HASH_SUPPORT_TIMING_SEAM_HPP diff --git a/test/timing_test.cpp b/test/timing_test.cpp new file mode 100644 index 0000000..98b5a86 --- /dev/null +++ b/test/timing_test.cpp @@ -0,0 +1,240 @@ +// 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) + +// detail::timing_guard, with no backend: its seam fires once per guard, engaged or not, on every +// target and names the function that holds the guard, which require_enters reads in the spellings +// of clang, GCC and MSVC; where the CPU has DIT, an engaged guard sets it for its scope and +// clears it after when it was clear, leaves it set when it was set, and nests; a disengaged guard +// touches nothing. Built with WEBCPP_TEST_TIMING_THREADS (timing_threads, native, with threads), +// a guard on one thread leaves another's DIT clear. A copy of libs/crypto/test/timing_test.cpp +// with hash's names and the engaged flag. + +#include "support/timing_seam.hpp" + +#include +#include + +#include + +#include +#include +#include + +#ifdef WEBCPP_TEST_TIMING_THREADS +#include +#include +#endif + +namespace { + +namespace detail = webcpp::hash::detail; + +namespace seam_probe { + +/** Holds a guard, as a public function does, for seam_names_function. */ +void guarded_function() { + webcpp::hash::detail::timing_guard const guard; +} + +/** Calls guarded_function and holds no guard of its own, as a function that forgot its own. */ +void forwarding_function() { + guarded_function(); +} + +} // namespace seam_probe + +/** + * Sets or clears DIT for this thread, as a program can, so that a test starts from a known state; + * only where the CPU has DIT, since the instruction traps on a CPU without it. + */ +void force_dit([[maybe_unused]] bool set) { +#ifdef WEBCPP_HASH_DETAIL_TIMING_COVERED + if (!detail::cpu_has_dit()) { + return; + } + detail::write_dit(set ? detail::dit_bit : 0); +#endif +} + +// Constructing a guard raises the seam's count by exactly one, on every target. +void seam_fires() { + std::size_t const before = webcpp::test::timing_entries; + { + detail::timing_guard const guard; + BOOST_TEST_EQ(webcpp::test::timing_entries, before + 1); + } + BOOST_TEST_EQ(webcpp::test::timing_entries, before + 1); +} + +// The seam records the function that holds the first guard a call enters, as the compiler spells +// it, and require_enters' reading of it finds that function and no other. +void seam_names_function() { + webcpp::test::timing_first_entry = nullptr; + seam_probe::forwarding_function(); + if (BOOST_TEST(webcpp::test::timing_first_entry != nullptr)) { + std::string_view const entered = webcpp::test::timing_first_entry; + BOOST_TEST(webcpp::test::names_function( + entered, webcpp::test::function_named("seam_probe::guarded_function"))); + BOOST_TEST(!webcpp::test::names_function(entered, + webcpp::test::function_named("guarded_function"))); + BOOST_TEST(!webcpp::test::names_function( + entered, webcpp::test::function_named("seam_probe::forwarding_function"))); + BOOST_TEST(!webcpp::test::names_function( + entered, webcpp::test::function_named("other::guarded_function"))); + BOOST_TEST(!webcpp::test::names_function( + entered, webcpp::test::function_named("seam_probe::guarded"))); + } + webcpp::test::timing_first_entry = nullptr; +} + +// require_enters' reading of a function_name() in the spellings of clang, GCC and MSVC, whatever +// compiles this test: a free forwarder and the member it forwards to, a constructor, operators, +// overloads told apart by a parameter, and lambdas, which are never a public function. +void names_function_spellings() { + auto const names = [](std::string_view entered, std::string_view spelled) { + return webcpp::test::names_function(entered, webcpp::test::function_named(spelled)); + }; + BOOST_TEST(names("int ns::pem::armour(int) [with B = int]", "pem::armour")); + BOOST_TEST(!names("static int ns::pem::algorithm::armour(int) [B = int]", "pem::armour")); + BOOST_TEST( + names("static int ns::pem::algorithm::armour(int) [with B = int]", "algorithm::armour")); + BOOST_TEST(names("int __cdecl ns::pem::armour(int)", "pem::armour")); + BOOST_TEST(!names("int __cdecl ns::pem::algorithm::armour(int)", "pem::armour")); + BOOST_TEST( + names("struct ns::gcm &__cdecl ns::gcm::operator =(struct ns::gcm &&)", + "gcm::operator=")); + BOOST_TEST( + !names("bool __cdecl ns::operator ==(struct ns::pk,struct ns::pk)", "ns::operator=")); + BOOST_TEST( + names("bool __cdecl ns::operator ==(struct ns::pk,struct ns::pk)", "ns::operator==")); + BOOST_TEST(names("ns::gcm::gcm(ns::gcm&&) [with C = int]", "gcm::gcm")); + BOOST_TEST( + names("bool ns::equal(std::span, std::span)", + "ns::equal(span")); + BOOST_TEST( + !names("bool ns::equal(std::span, std::span)", + "ns::equal(digest")); + BOOST_TEST( + names("bool __cdecl ns::equal<16>(const class ns::digest<16> &)", "ns::equal(digest")); + // A name in the return type or a parameter type is not the function's own. + BOOST_TEST(!names("int ns::other(ns::pem::armour, int) [with B = int]", "pem::armour")); + BOOST_TEST(!names("int ns::other(ns::pem::armour(int)) [with B = int]", "pem::armour")); + BOOST_TEST(!names("ns::pem::armour ns::make(int) [B = int]", "pem::armour")); + BOOST_TEST(!names("struct ns::pem::armour __cdecl ns::make(int)", "pem::armour")); + BOOST_TEST(!names("ns::algorithm>::seal(int)", "pem::armour")); + BOOST_TEST(names("ns::pem::armour ns::pem::armour(ns::pem::armour)", "pem::armour")); + // A function named without a scope never matches. + BOOST_TEST(!names("int ns::pem::armour(int) [with B = int]", "armour")); + BOOST_TEST(names("auto ns::pk::operator<=>(const pk &) const", "pk::operator<=>")); + BOOST_TEST( + names("auto __cdecl ns::pk::operator <=>(const struct ns::pk &) const", "pk::operator<=>")); + BOOST_TEST(!names("auto ns::f()::(anonymous class)::operator()() const", "ns::f")); + BOOST_TEST(!names("auto ns::f()::(lambda)::operator()() const", "ns::f")); + BOOST_TEST(!names("ns::f()::", "ns::f")); + BOOST_TEST(!names("auto __cdecl ns::f::::operator ()(void) const", "ns::f")); +} + +// From clear: set inside a guard, clear after it. Where the guard does not apply, never set. +void guard_sets_and_clears() { + force_dit(false); + BOOST_TEST(!detail::dit_is_set()); + { + detail::timing_guard const guard; + BOOST_TEST_EQ(detail::dit_is_set(), detail::cpu_has_dit()); + } + BOOST_TEST(!detail::dit_is_set()); +} + +// From set, as a program sets it: still set after a guard. +void guard_leaves_set_bit() { + force_dit(true); + BOOST_TEST_EQ(detail::dit_is_set(), detail::cpu_has_dit()); + { + detail::timing_guard const guard; + BOOST_TEST_EQ(detail::dit_is_set(), detail::cpu_has_dit()); + } + BOOST_TEST_EQ(detail::dit_is_set(), detail::cpu_has_dit()); + force_dit(false); + BOOST_TEST(!detail::dit_is_set()); +} + +// From clear: set inside both guards and after the inner one, clear after the outer one. +void nested_guards() { + force_dit(false); + { + detail::timing_guard const outer; + { + detail::timing_guard const inner; + BOOST_TEST_EQ(detail::dit_is_set(), detail::cpu_has_dit()); + } + BOOST_TEST_EQ(detail::dit_is_set(), detail::cpu_has_dit()); + { + detail::timing_guard const quiet{false}; + BOOST_TEST_EQ(detail::dit_is_set(), detail::cpu_has_dit()); + } + BOOST_TEST_EQ(detail::dit_is_set(), detail::cpu_has_dit()); + } + BOOST_TEST(!detail::dit_is_set()); +} + +// A guard constructed with false fires the seam and touches nothing, whichever state it finds. +void disengaged_does_nothing() { + std::size_t const before = webcpp::test::timing_entries; + force_dit(false); + { + detail::timing_guard const guard{false}; + BOOST_TEST_EQ(webcpp::test::timing_entries, before + 1); + BOOST_TEST(!detail::dit_is_set()); + } + BOOST_TEST(!detail::dit_is_set()); + force_dit(true); + { + detail::timing_guard const guard{false}; + BOOST_TEST_EQ(detail::dit_is_set(), detail::cpu_has_dit()); + } + BOOST_TEST_EQ(detail::dit_is_set(), detail::cpu_has_dit()); + force_dit(false); + BOOST_TEST(!detail::dit_is_set()); +} + +#ifdef WEBCPP_TEST_TIMING_THREADS +// While a guard holds DIT on this thread, another thread reads it clear. The other thread is +// started before the guard, so that it cannot inherit the state at its creation (Linux's clone +// copies PSTATE), and reads it only once the guard is entered. +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(detail::dit_is_set()); + }); + { + detail::timing_guard const guard; + guard_entered.set_value(); + BOOST_TEST(!other_reading.get_future().get()); + BOOST_TEST_EQ(detail::dit_is_set(), detail::cpu_has_dit()); + } + other.join(); + BOOST_TEST(!detail::dit_is_set()); +} +#endif + +} // namespace + +int main() { + seam_fires(); + seam_names_function(); + names_function_spellings(); + guard_sets_and_clears(); + guard_leaves_set_bit(); + nested_guards(); + disengaged_does_nothing(); +#ifdef WEBCPP_TEST_TIMING_THREADS + other_thread_untouched(); +#endif + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/timing_unseamed_test.cpp b/test/timing_unseamed_test.cpp new file mode 100644 index 0000000..2efe0d4 --- /dev/null +++ b/test/timing_unseamed_test.cpp @@ -0,0 +1,137 @@ +// 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) + +// detail::timing_guard in a program's build, without the seam: its constructor takes a bool and no +// std::source_location, on every target, so that no guarded function's name or header's path can +// reach a program. Built with WEBCPP_TEST_TIMING_READ_SELF (natively, at release), the program +// reads its own executable and finds neither the name of mac, which it calls over HMAC-SHA-256 on +// backends::hash2, nor the path of mac.hpp, where mac is declared. A copy of +// libs/crypto/test/timing_unseamed_test.cpp over hash's mac. + +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include + +#ifdef WEBCPP_TEST_TIMING_READ_SELF +#include +#include +#include +#include +#include +#endif + +namespace { + +namespace detail = webcpp::hash::detail; +namespace hash = webcpp::hash; + +static_assert(!std::is_constructible_v, + "without the seam, timing_guard takes no source_location"); +static_assert(!std::is_constructible_v, + "without the seam, timing_guard takes no source_location"); +static_assert(std::is_nothrow_constructible_v, + "without the seam, timing_guard is constructed from a bool, and never throws"); +static_assert(std::is_nothrow_default_constructible_v, + "without the seam, timing_guard is constructed from nothing, and never throws"); + +// mac over HMAC-SHA-256 on backends::hash2 runs and answers as it does with the seam. The call is +// outside BOOST_TEST, whose message would put the call's text, mac's name among it, in the program. +void mac_runs() { + std::array const key{1, 2, 3, 4}; + std::array const input{5, 6, 7, 8}; + std::array tag{}; + auto const computed = + hash::mac, hash::backends::hash2>(tag, key, + input); + BOOST_TEST(computed.has_value()); +} + +#ifdef WEBCPP_TEST_TIMING_READ_SELF +/** + * The texts this program must not hold, kept in it with their last character changed, so that + * the program's own constants are not what the search finds. Each is read through a volatile + * pointer, which keeps it in the program whole: a search for a constant could otherwise compile + * to comparisons with no copy of the text. + */ +constexpr std::string_view masked_name_text = "webcpp::hash::mac#"; +constexpr std::string_view masked_path_text = "mac.hp#"; + +/** + * A text of the program's, read where the compiler cannot see it. + * + * @param text A text of the program. + * @return The same text, as the program holds it. + */ +std::string_view kept(std::string_view text) { + char const* volatile const at = text.data(); + return {at, text.size()}; +} + +/** + * A text this program must not hold, from its masked copy: the last character is restored at run + * time, from a volatile the compiler cannot read ahead. + * + * @param masked The text, its last character replaced. + * @param last The text's real last character. + * @return The text. + */ +std::string unmasked(std::string_view masked, char last) { + char volatile const restored = last; + std::string text(masked); + text.back() = restored; + return text; +} + +/** + * Whether the bytes hold the text. + * + * @param bytes A file's bytes. + * @param text The text. + * @return Whether the text is somewhere in them. + */ +bool holds(std::vector const& bytes, std::string_view text) { + return !std::ranges::search(bytes, text).empty(); +} + +// The executable holds the masked texts, which shows the search reads it whole, and neither +// mac's name, as clang, GCC and MSVC begin function_name(), nor its header's path. +void executable_holds_no_location(char const* executable) { + std::ifstream file(executable, std::ios::binary); + if (!BOOST_TEST(file.is_open())) { + return; + } + std::vector const bytes{std::istreambuf_iterator(file), + std::istreambuf_iterator()}; + std::string_view const masked_name = kept(masked_name_text); + std::string_view const masked_path = kept(masked_path_text); + BOOST_TEST(holds(bytes, masked_name)); + BOOST_TEST(holds(bytes, masked_path)); + BOOST_TEST(!holds(bytes, unmasked(masked_name, '('))); + BOOST_TEST(!holds(bytes, unmasked(masked_path, 'p'))); +} +#endif + +} // namespace + +// NOLINTNEXTLINE(misc-const-correctness): main's arguments have the type the standard gives them +int main([[maybe_unused]] int argc, [[maybe_unused]] char** argv) { + mac_runs(); +#ifdef WEBCPP_TEST_TIMING_READ_SELF + if (BOOST_TEST(argc > 0)) { + executable_holds_no_location(argv[0]); + } +#endif + return webcpp::test::exit_status(boost::report_errors()); +} From 1ff528f14598afc2318c885286c78e50a19ad16a Mon Sep 17 00:00:00 2001 From: R Date: Sun, 22 Nov 2026 07:18:30 -0300 Subject: [PATCH 02/27] hash: a disengaged detail::timing_guard fires no seam, and the seam support's examples name hash's functions --- include/webcpp/hash/detail/timing.hpp | 33 +++++++++++++++------------ test/Jamfile | 5 ++-- test/support/timing_seam.hpp | 6 ++--- test/timing_test.cpp | 18 +++++++-------- 4 files changed, 34 insertions(+), 28 deletions(-) diff --git a/include/webcpp/hash/detail/timing.hpp b/include/webcpp/hash/detail/timing.hpp index 03acd7a..5ba50e7 100644 --- a/include/webcpp/hash/detail/timing.hpp +++ b/include/webcpp/hash/detail/timing.hpp @@ -27,8 +27,8 @@ * by their arguments (a BLAKE2b digest of a call that passes a key, a BLAKE3 object made with a * key), and an unkeyed call of the same function computes on public data and must not pay for * DIT: those functions construct the guard with `engaged` false when the call is not keyed. A - * disengaged guard sets nothing and clears nothing; on a target the guard does not cover, - * `engaged` is read only to fire the seam. + * disengaged guard sets nothing, clears nothing and fires no seam, on every target; on a target the + * guard does not cover, `engaged` alone decides whether the seam fires and nothing else happens. * * The guard applies on arm64 under macOS, iOS, Linux and Android, where the system says whether * the CPU has FEAT_DIT. Everywhere else (x86, WebAssembly, where the engine decides, and Windows @@ -147,25 +147,32 @@ class timing_guard { public: #ifdef WEBCPP_HASH_DETAIL_TIMING_ENTERED /** - * Runs the seam, then sets DIT where `engaged`, the CPU has it and it is clear: a test's - * build alone. + * 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 is keyed; false makes the guard do nothing but fire the - * seam. + * @param engaged Whether the call is keyed; 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_HASH_DETAIL_TIMING_ENTERED(where); - enter(engaged); + enter(); } #else /** - * Sets DIT where `engaged`, the CPU has it and it is clear. + * Where `engaged`, sets DIT where the CPU has it and it is clear. * * @param engaged Whether the call is keyed; false makes the guard do nothing. */ - explicit timing_guard(bool engaged = true) noexcept { enter(engaged); } + explicit timing_guard(bool engaged = true) noexcept { + if (engaged) { + enter(); + } + } #endif /** Clears DIT when this guard set it. */ @@ -191,13 +198,11 @@ class timing_guard { private: /** - * Sets DIT where `engaged`, the CPU has it and it is clear, and remembers to clear it. - * - * @param engaged Whether the call is keyed. + * Sets DIT where the CPU has it and it is clear, and remembers to clear it. */ - void enter([[maybe_unused]] bool engaged) noexcept { + void enter() noexcept { #ifdef WEBCPP_HASH_DETAIL_TIMING_COVERED - if (engaged && cpu_has_dit() && !dit_is_set()) { + if (cpu_has_dit() && !dit_is_set()) { write_dit(dit_bit); armed_ = true; } diff --git a/test/Jamfile b/test/Jamfile index e591764..60ecb53 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -695,8 +695,9 @@ hash-run allocation_openssl : allocation_openssl_test.cpp : native wasip2 wasip3 ; # detail::timing_guard sets DIT for its scope where the CPU has it and leaves -# the thread's state as it found it; its seam fires on every target, engaged -# or not. timing_threads adds a second thread, natively, with threads. +# the thread's state as it found it; its seam fires on every target for an engaged +# guard and never for a disengaged one. timing_threads adds a second thread, +# natively, with threads. hash-run timing : timing_test.cpp ; hash-run timing_threads : timing_test.cpp : multi WEBCPP_TEST_TIMING_THREADS : native ; diff --git a/test/support/timing_seam.hpp b/test/support/timing_seam.hpp index c5d1e2e..c592f42 100644 --- a/test/support/timing_seam.hpp +++ b/test/support/timing_seam.hpp @@ -81,8 +81,8 @@ struct named_function { * `(`, or by a space and words that say how it is called. * * The scope is the component before the identifier, empty when there is none. A check named - * `pem::algorithm::unarmour of a text without lines on sodium` names `algorithm::unarmour`; - * `secp256k1::equal(digest` names `secp256k1::equal` with a parameter list that holds `digest`. + * `hkdf::hkdf_extract of a salt on hash2` names `hkdf::hkdf_extract`; + * `blake3::update(void` names `blake3::update` with a parameter list that holds `void`. * * @param spelled The function as a check spells it. * @return Its scope, identifier and parameter word. @@ -138,7 +138,7 @@ inline std::string normalized_function_name(std::string_view entered) { /** * The component that qualifies a name, read back from the `::` before it at `separator`: - * `algorithm` in `pem::algorithm::armour`, its template arguments skipped. + * `mac_engine` in `detail::mac_engine::compute`, its template arguments skipped. * * @param text A normalized `function_name()`. * @param separator The position of the `::` before the name. diff --git a/test/timing_test.cpp b/test/timing_test.cpp index 98b5a86..7acc90e 100644 --- a/test/timing_test.cpp +++ b/test/timing_test.cpp @@ -4,13 +4,13 @@ // accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) -// detail::timing_guard, with no backend: its seam fires once per guard, engaged or not, on every -// target and names the function that holds the guard, which require_enters reads in the spellings -// of clang, GCC and MSVC; where the CPU has DIT, an engaged guard sets it for its scope and -// clears it after when it was clear, leaves it set when it was set, and nests; a disengaged guard -// touches nothing. Built with WEBCPP_TEST_TIMING_THREADS (timing_threads, native, with threads), -// a guard on one thread leaves another's DIT clear. A copy of libs/crypto/test/timing_test.cpp -// with hash's names and the engaged flag. +// detail::timing_guard, with no backend: its seam fires once per engaged guard on every +// target, and never for a disengaged one, and names the function that holds the guard, which +// require_enters reads in the spellings of clang, GCC and MSVC; where the CPU has DIT, an engaged +// guard sets it for its scope and clears it after when it was clear, leaves it set when it was set, +// and nests; a disengaged guard touches nothing. Built with WEBCPP_TEST_TIMING_THREADS +// (timing_threads, native, with threads), a guard on one thread leaves another's DIT clear. A copy +// of libs/crypto/test/timing_test.cpp with hash's names and the engaged flag. #include "support/timing_seam.hpp" @@ -180,13 +180,13 @@ void nested_guards() { BOOST_TEST(!detail::dit_is_set()); } -// A guard constructed with false fires the seam and touches nothing, whichever state it finds. +// A guard constructed with false fires no seam and touches nothing, whichever state it finds. void disengaged_does_nothing() { std::size_t const before = webcpp::test::timing_entries; force_dit(false); { detail::timing_guard const guard{false}; - BOOST_TEST_EQ(webcpp::test::timing_entries, before + 1); + BOOST_TEST_EQ(webcpp::test::timing_entries, before); BOOST_TEST(!detail::dit_is_set()); } BOOST_TEST(!detail::dit_is_set()); From be454f1d1b9a390f04eab53a0ddda89515ef3ca4 Mon Sep 17 00:00:00 2001 From: R Date: Sun, 22 Nov 2026 07:24:43 -0300 Subject: [PATCH 03/27] hash: mac and the keyed modes of BLAKE2b and BLAKE3 set DIT around each call on every backend --- include/webcpp/hash/blake3.hpp | 28 ++- include/webcpp/hash/digest.hpp | 28 +++ include/webcpp/hash/mac.hpp | 5 + test/Jamfile | 7 + test/timing_keyed_test.cpp | 361 +++++++++++++++++++++++++++++++++ 5 files changed, 427 insertions(+), 2 deletions(-) create mode 100644 test/timing_keyed_test.cpp diff --git a/include/webcpp/hash/blake3.hpp b/include/webcpp/hash/blake3.hpp index 7ca9e79..e206945 100644 --- a/include/webcpp/hash/blake3.hpp +++ b/include/webcpp/hash/blake3.hpp @@ -22,6 +22,7 @@ #else #include +#include #include @@ -88,8 +89,17 @@ inline void touch_blake3_canary() noexcept { BLAKE3, its keyed mode, its key derivation and its extendable output, over the official C implementation, in Boost.Hash2's HashAlgorithm form. - The object holds the C implementation's state, 1,912 bytes on 64-bit targets, and allocates - nothing. Its destructor does not wipe that state, as Hash2's own algorithms do not. + The object holds the C implementation's state, 1,912 bytes on 64-bit targets, a count of the + bytes `result()` returned and a flag that says whether the object is keyed, 1,928 bytes in all on + 64-bit targets (the flag costs one alignment), and allocates nothing. Its destructor does not wipe + that state, as Hash2's own algorithms do not. + + The keyed modes compute on a secret, and every call on a keyed object sets the CPU's + data-independent timing (DIT) for the call where the CPU has it, as `mac` does, and leaves the + thread's state as it found it (design D1): `keyed`, `derive_key`, a non-zero integer seed and a + seed of bytes, then `update`, `result`, `squeeze` and `reset` of the object they make, which keeps + the flag through copies and moves. The plain mode, a zero integer seed and a seed of no bytes + compute on public data and hold no guard (design D2). */ class blake3 { public: @@ -170,6 +180,7 @@ class blake3 { blake3_hasher hasher_; // the C implementation's state, 1,912 bytes on 64-bit targets std::uint64_t squeezed_ = 0; // bytes result() returned since input was last added + bool keyed_ = false; // keyed or derived from a key: every call holds the timing guard }; // Each constructor initializes hasher_ through BLAKE3's own init function, which writes what @@ -182,7 +193,9 @@ inline blake3::blake3() noexcept { } inline blake3::blake3(std::uint64_t seed_value) noexcept { + detail::timing_guard const timing{seed_value != 0}; detail::touch_blake3_canary(); + keyed_ = seed_value != 0; if (seed_value == 0) { blake3_hasher_init(&hasher_); return; @@ -198,7 +211,9 @@ inline blake3::blake3(void const* input_data, std::size_t input_size) noexcept : blake3(static_cast(input_data), input_size) {} inline blake3::blake3(unsigned char const* input_data, std::size_t input_size) noexcept { + detail::timing_guard const timing{input_size != 0}; detail::touch_blake3_canary(); + keyed_ = input_size != 0; if (input_size == 0) { blake3_hasher_init(&hasher_); return; @@ -216,25 +231,31 @@ inline blake3::blake3(unsigned char const* input_data, std::size_t input_size) n // NOLINTEND(cppcoreguidelines-pro-type-member-init) inline blake3 blake3::keyed(std::span key_bytes) noexcept { + detail::timing_guard const timing; detail::touch_blake3_canary(); blake3 derived_hasher{uninitialized{}}; + derived_hasher.keyed_ = true; blake3_hasher_init_keyed(&derived_hasher.hasher_, key_bytes.data()); return derived_hasher; } inline blake3 blake3::derive_key(std::string_view context_string) noexcept { + detail::timing_guard const timing; detail::touch_blake3_canary(); blake3 derived_hasher{uninitialized{}}; + derived_hasher.keyed_ = true; blake3_hasher_init_derive_key_raw(&derived_hasher.hasher_, context_string.data(), context_string.size()); return derived_hasher; } inline void blake3::update(void const* input_data, std::size_t input_size) noexcept { + detail::timing_guard const timing{keyed_}; update(static_cast(input_data), input_size); } inline void blake3::update(unsigned char const* input_data, std::size_t input_size) noexcept { + detail::timing_guard const timing{keyed_}; detail::touch_blake3_canary(); if (input_size == 0) { return; @@ -244,6 +265,7 @@ inline void blake3::update(unsigned char const* input_data, std::size_t input_si } inline blake3::result_type blake3::result() noexcept { + detail::timing_guard const timing{keyed_}; detail::touch_blake3_canary(); result_type output_bytes; blake3_hasher_finalize_seek(&hasher_, squeezed_, output_bytes.data(), output_bytes.size()); @@ -253,11 +275,13 @@ inline blake3::result_type blake3::result() noexcept { inline void blake3::squeeze(std::span output_bytes, std::uint64_t seek_position) const noexcept { + detail::timing_guard const timing{keyed_}; detail::touch_blake3_canary(); blake3_hasher_finalize_seek(&hasher_, seek_position, output_bytes.data(), output_bytes.size()); } inline void blake3::reset() noexcept { + detail::timing_guard const timing{keyed_}; detail::touch_blake3_canary(); blake3_hasher_reset(&hasher_); squeezed_ = 0; diff --git a/include/webcpp/hash/digest.hpp b/include/webcpp/hash/digest.hpp index d719c9b..758c9b2 100644 --- a/include/webcpp/hash/digest.hpp +++ b/include/webcpp/hash/digest.hpp @@ -35,6 +35,7 @@ #include #include #include +#include #include #include #include @@ -672,6 +673,22 @@ template return {}; } +/** + Whether a digest's options carry a key: a keyed BLAKE2b is a MAC, and holds the timing guard of + one (design D1); every other digest computes on public data. + + @tparam Options A tag's `digest_options`. @param options The digest's parameters. + @return Whether the options hold a non-empty `key`; `false` for options without one. +*/ +template +[[nodiscard]] constexpr bool options_keyed(Options const& options) noexcept { + if constexpr (requires { options.key.empty(); }) { + return !options.key.empty(); + } else { + return false; + } +} + } // namespace detail /** @@ -697,6 +714,7 @@ template > [[nodiscard]] boost::system::result digest_of(std::span output, std::span input, digest_options const& options = {}) { + detail::timing_guard const timing{detail::options_keyed(options)}; using engine = detail::digest_engine; auto checked = detail::digest_guards(output.size(), options); if (!checked) { @@ -723,6 +741,9 @@ template > Unlike Boost.Hash2's types, the result is final: an `update` or a `finish` after `finish`, or on a hasher moved from, is `error::invalid_state`. + A hasher made with a key (BLAKE2b's) holds the timing guard of a MAC in `make`, `update` and + `finish`, as `digest_of` with a key does; one made without a key holds none (design D1, D2). + Move-only. The state is wiped (and what the backend allocated for it freed) by `finish`, by the destructor, and in the hasher moved from. @@ -758,6 +779,7 @@ class hasher { */ [[nodiscard]] static boost::system::result make( digest_options const& options = {}) noexcept { + detail::timing_guard const timing{detail::options_keyed(options)}; auto const checked = traits::check(options); if (!checked) { return checked.error(); @@ -774,6 +796,7 @@ class hasher { } started.min_output_ = traits::min_output(options); started.max_output_ = traits::max_output(options); + started.keyed_ = detail::options_keyed(options); started.phase_ = phase::hashing; return started; } @@ -787,6 +810,7 @@ class hasher { : state_(std::move(moved_from.state_)), min_output_(moved_from.min_output_), max_output_(moved_from.max_output_), + keyed_(moved_from.keyed_), phase_(moved_from.phase_) { moved_from.leave(); } @@ -804,6 +828,7 @@ class hasher { state_ = std::move(moved_from.state_); min_output_ = moved_from.min_output_; max_output_ = moved_from.max_output_; + keyed_ = moved_from.keyed_; phase_ = moved_from.phase_; moved_from.leave(); } @@ -828,6 +853,7 @@ class hasher { either of the last two the hasher is spent (`invalid_state`). */ [[nodiscard]] boost::system::result update(std::span input) noexcept { + detail::timing_guard const timing{keyed_}; if (phase_ != phase::hashing) { return error::invalid_state; } @@ -849,6 +875,7 @@ class hasher { hasher spent. */ [[nodiscard]] boost::system::result finish(std::span output) noexcept { + detail::timing_guard const timing{keyed_}; if (phase_ != phase::hashing) { return error::invalid_state; } @@ -894,6 +921,7 @@ class hasher { engine::state state_{}; std::uint64_t min_output_ = 0; std::uint64_t max_output_ = 0; + bool keyed_ = false; // made with a key: update and finish hold the timing guard phase phase_ = phase::spent; }; diff --git a/include/webcpp/hash/mac.hpp b/include/webcpp/hash/mac.hpp index 7023e14..b09b44f 100644 --- a/include/webcpp/hash/mac.hpp +++ b/include/webcpp/hash/mac.hpp @@ -8,6 +8,9 @@ The MAC family (spec 2.15): `mac`, the tag of a message under a key in one call, over a tag of `macs` and a backend, `default_backend` of the tag by default. + Every call holds the data-independent-timing guard (`detail::timing_guard`): where the CPU has + DIT, `mac` sets it for the call and leaves the thread's state as it found it. + The guards are the same on every backend and run before any work: a tag of a size the MAC does not produce is `invalid_output_size`, a key of a size it does not take `invalid_key_size`, a value the MAC accepts and the chosen backend does not `unsupported_by_backend`. A guard's refusal leaves @@ -33,6 +36,7 @@ #include #include #include +#include #include #include #include @@ -251,6 +255,7 @@ template > std::span key, std::span input, mac_options const& options = {}) { + detail::timing_guard const timing; using engine = detail::mac_engine; auto checked = detail::mac_guards(output.size(), key.size(), options); if (!checked) { diff --git a/test/Jamfile b/test/Jamfile index 60ecb53..453d4cf 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -710,6 +710,13 @@ hash-run timing_unseamed : timing_unseamed_test.cpp ; webcpp.run timing_unseamed_release : timing_unseamed_test.cpp : release WEBCPP_TEST_TIMING_READ_SELF : native ; +# mac and the keyed modes of BLAKE2b (digest_of, hasher with a key) and of BLAKE3 +# (keyed, derive_key and the seeds that key) hold detail::timing_guard; a call +# that is not keyed holds none; no output changes. +hash-run timing_keyed : timing_keyed_test.cpp + : /third_party//blake3 /third_party//sodium + /third_party//blake3_vectors /webcpp//boost_json ; + build-project messages ; # The canaries at link time, each C library's absence and another commit of diff --git a/test/timing_keyed_test.cpp b/test/timing_keyed_test.cpp new file mode 100644 index 0000000..7b847ae --- /dev/null +++ b/test/timing_keyed_test.cpp @@ -0,0 +1,361 @@ +// 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) + +// mac, and the keyed modes of BLAKE2b (digest_of, hasher) and of BLAKE3 (the blake3 class), hold +// detail::timing_guard (design D1, D4): each enters its own guard first, on every target, through +// the seam; a call that is not keyed enters none (D2); a guard changes no byte of any output. +// Where the CPU has DIT, mac leaves the thread's state as it found it. + +#include "support/timing_seam.hpp" + +#include +#include +#include +#include +#include +#include +#include + +#include "require.hpp" +#include "support/hex.hpp" + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +namespace detail = webcpp::hash::detail; +namespace hash = webcpp::hash; +namespace test = webcpp::test; +namespace digests = webcpp::hash::digests; +namespace macs = webcpp::hash::macs; +namespace backends = webcpp::hash::backends; +using webcpp::hash::blake3; + +using hmac_sha256 = macs::hmac; +using blake2b_options = hash::digest_options; + +/** + * Sets or clears DIT for this thread, as a program can, so that a test starts from a known state; + * only where the CPU has DIT, since the instruction traps on a CPU without it. + */ +void force_dit([[maybe_unused]] bool set) { +#ifdef WEBCPP_HASH_DETAIL_TIMING_COVERED + if (!detail::cpu_has_dit()) { + return; + } + detail::write_dit(set ? detail::dit_bit : 0); +#endif +} + +std::array const key = [] { + std::array bytes{}; + for (std::size_t i = 0; i < bytes.size(); ++i) { + bytes[i] = static_cast(i + 1); + } + return bytes; +}(); +std::array const input{9, 8, 7, 6, 5, 4, 3, 2, 1}; + +// mac enters its own guard on the default backend and on sodium, and still does when the output's +// size is wrong, since the guard precedes the checks. +void mac_enters() { + std::array tag{}; + test::require_enters("hash::mac of hmac_sha256 on hash2", [&] { + auto const done = hash::mac(tag, key, input); + BOOST_TEST(done.has_value()); + }); + test::require_enters("hash::mac of blake2b_mac on sodium", [&] { + auto const done = hash::mac(tag, key, input); + BOOST_TEST(done.has_value()); + }); + std::array wrong{}; + test::require_enters("hash::mac with a tag of the wrong size on hash2", [&] { + auto const done = hash::mac(wrong, key, input); + BOOST_TEST(!done.has_value()); + }); + test::require_enters("hash::mac with a key of the wrong size on sodium", [&] { + auto const done = hash::mac( + tag, std::span{}, input); + BOOST_TEST(!done.has_value()); + }); +} + +// Where the CPU has DIT: mac leaves it set when the program set it, and clear when it was clear. +void mac_leaves_set_state() { + std::array tag{}; + force_dit(true); + BOOST_TEST_EQ(detail::dit_is_set(), detail::cpu_has_dit()); + BOOST_TEST((hash::mac(tag, key, input)).has_value()); + BOOST_TEST_EQ(detail::dit_is_set(), detail::cpu_has_dit()); + force_dit(false); + BOOST_TEST(!detail::dit_is_set()); + BOOST_TEST((hash::mac(tag, key, input)).has_value()); + BOOST_TEST(!detail::dit_is_set()); +} + +// digest_of with a key, and hasher's make, update and finish of a keyed hasher, each enter their +// own guard; the output is the one of the unguarded computation, the same on the unkeyed call. +void keyed_blake2b() { + blake2b_options const keyed{.key = key}; + std::array once{}; + test::require_enters("hash::digest_of with a key on sodium", [&] { + BOOST_TEST((hash::digest_of(once, input, keyed)).has_value()); + }); + // The same tag by mac, and by hasher. + std::array by_mac{}; + BOOST_TEST((hash::mac(by_mac, key, input)).has_value()); + BOOST_TEST(once == by_mac); + + std::optional> hashing; + test::require_enters("hash::hasher::make with a key", [&] { + auto made = hash::hasher::make(keyed); + if (BOOST_TEST(made.has_value())) { + hashing.emplace(std::move(*made)); + } + }); + if (!hashing) { + return; + } + test::require_enters("hash::hasher::update of a keyed hasher", + [&] { BOOST_TEST(hashing->update(input).has_value()); }); + std::array pieces{}; + test::require_enters("hash::hasher::finish of a keyed hasher", + [&] { BOOST_TEST(hashing->finish(pieces).has_value()); }); + BOOST_TEST(pieces == once); +} + +// Without a key, BLAKE2b and every other digest compute on public data: no guard. +void unkeyed_blake2b_enters_none() { + std::array out{}; + test::uncovered("hash::digest_of of blake2b without a key", [&] { + BOOST_TEST((hash::digest_of(out, input)).has_value()); + }); + std::optional> hashing; + test::uncovered("hash::hasher::make of blake2b without a key", [&] { + auto made = hash::hasher::make(); + if (BOOST_TEST(made.has_value())) { + hashing.emplace(std::move(*made)); + } + }); + if (!hashing) { + return; + } + test::uncovered("hash::hasher::update of blake2b without a key", + [&] { BOOST_TEST(hashing->update(input).has_value()); }); + test::uncovered("hash::hasher::finish of blake2b without a key", + [&] { BOOST_TEST(hashing->finish(out).has_value()); }); + std::array id{}; + test::uncovered("hash::digest_of of sha2_256 on hash2", [&] { + BOOST_TEST((hash::digest_of(id, input)).has_value()); + }); +} + +// A keyed hasher moved into another still holds its guards, and so does one assigned to; an +// unkeyed one moved holds none. Moving enters no guard of its own. +void moved_keyed_hasher() { + blake2b_options const keyed{.key = key}; + auto made = hash::hasher::make(keyed); + if (!BOOST_TEST(made.has_value())) { + return; + } + std::optional> moved; + test::uncovered("moving a keyed hasher", [&] { moved.emplace(std::move(*made)); }); + test::require_enters("hash::hasher::update of a moved keyed hasher", + [&] { BOOST_TEST(moved->update(input).has_value()); }); + auto other = hash::hasher::make(); + if (!BOOST_TEST(other.has_value())) { + return; + } + test::uncovered("assigning a keyed hasher", [&] { *other = std::move(*moved); }); + test::require_enters("hash::hasher::finish of an assigned keyed hasher", [&] { + std::array out{}; + BOOST_TEST(other->finish(out).has_value()); + }); + + auto plain = hash::hasher::make(); + if (!BOOST_TEST(plain.has_value())) { + return; + } + std::optional> plain_moved; + plain_moved.emplace(std::move(*plain)); + test::uncovered("hash::hasher::update of a moved unkeyed hasher", + [&] { BOOST_TEST(plain_moved->update(input).has_value()); }); + // The destructor of a keyed hasher wipes and holds no guard. + auto dying = hash::hasher::make(keyed); + if (BOOST_TEST(dying.has_value())) { + std::optional> held; + held.emplace(std::move(*dying)); + test::uncovered("destroying a keyed hasher", [&] { held.reset(); }); + } +} + +// The whole file at path; one that cannot be opened ends the test, by name. +std::string read_text(std::string const& path) { + std::ifstream in(path, std::ios::binary); + if (!in) { + std::cerr << "cannot open test data: " << path << '\n'; + std::abort(); + } + return {std::istreambuf_iterator(in), std::istreambuf_iterator()}; +} + +// BLAKE3's official vectors, keyed and derive-key entries, through objects whose every call +// enters a guard: the guard changes no byte. +void blake3_vectors_unchanged() { + namespace json = boost::json; + auto const text = read_text(WEBCPP_TEST_BLAKE3_VECTORS "/test_vectors.json"); + boost::system::error_code ec; + auto const doc = json::parse(text, ec); + test::require(BOOST_TEST(!ec)); + std::string_view const key_text = doc.at("key").as_string(); + test::require(BOOST_TEST_EQ(key_text.size(), std::size_t{32})); + std::array vector_key{}; + for (std::size_t i = 0; i < vector_key.size(); ++i) { + vector_key[i] = static_cast(key_text[i]); + } + std::string_view const context = doc.at("context_string").as_string(); + int cases = 0; + for (auto const& entry : doc.at("cases").as_array()) { + auto const length = static_cast(entry.at("input_len").as_int64()); + std::vector data(length); + for (std::size_t i = 0; i < length; ++i) { + data[i] = static_cast(i % 251); + } + auto const expect = [&](blake3 hasher, std::string_view name) { + std::string_view const hex = entry.at(name).as_string(); + std::vector squeezed(hex.size() / 2); + hasher.squeeze(squeezed); + BOOST_TEST_EQ(test::to_hex(squeezed), std::string(hex)); + }; + auto keyed = blake3::keyed(vector_key); + keyed.update(data.data(), data.size()); + expect(keyed, "keyed_hash"); + auto derived = blake3::derive_key(context); + derived.update(data.data(), data.size()); + expect(derived, "derive_key"); + ++cases; + } + BOOST_TEST_EQ(cases, 35); +} + +// The keyed modes and the seeds that key enter their own guard; the plain mode, and the seeds that +// do not key, enter none. +void blake3_modes() { + std::array const bytes{1, 2, 3, 4, 5, 6, 7, 8, 9}; + std::optional keyed; + test::require_enters("blake3::keyed", [&] { keyed.emplace(blake3::keyed(key)); }); + test::require_enters("blake3::update(void of a keyed object", [&] { + keyed->update(static_cast(bytes.data()), bytes.size()); + }); + test::require_enters("blake3::update(unsigned of a keyed object", [&] { + keyed->update(static_cast(bytes.data()), bytes.size()); + }); + test::require_enters("blake3::result of a keyed object", + [&] { BOOST_TEST(keyed->result().size() == 32); }); + test::require_enters("blake3::squeeze of a keyed object", [&] { + std::array out{}; + keyed->squeeze(out, 3); + }); + test::require_enters("blake3::reset of a keyed object", [&] { keyed->reset(); }); + + std::optional derived; + test::require_enters("blake3::derive_key", [&] { derived.emplace(blake3::derive_key("ctx")); }); + test::require_enters("blake3::update(void of a derived object", [&] { + derived->update(static_cast(bytes.data()), bytes.size()); + }); + test::require_enters("blake3::result of a derived object", + [&] { BOOST_TEST(derived->result().size() == 32); }); + test::require_enters("blake3::reset of a derived object", [&] { derived->reset(); }); + + // A copy and a move of a keyed object are keyed as it is. + blake3 copy{*keyed}; + test::require_enters("blake3::update(void of a copy of a keyed object", + [&] { copy.update(static_cast(bytes.data()), 1); }); + blake3 moved{std::move(copy)}; + test::require_enters("blake3::update(void of a moved keyed object", + [&] { moved.update(static_cast(bytes.data()), 1); }); + + // The seeds that key: a non-zero integer, and bytes. + test::require_enters("blake3::blake3 of a non-zero integer seed", [&] { + blake3 seeded{std::uint64_t{7}}; + BOOST_TEST(seeded.result().size() == 32); + }); + test::require_enters("blake3::blake3(char of 16 bytes", [&] { + blake3 seeded{static_cast(bytes.data()), std::size_t{16}}; + BOOST_TEST(seeded.result().size() == 32); + }); + test::require_enters("blake3::blake3(char of 40 bytes", [&] { + blake3 seeded{static_cast(bytes.data()), std::size_t{40}}; + BOOST_TEST(seeded.result().size() == 32); + }); + // The delegating constructor of void const* holds none: the one it delegates to runs first. + test::require_enters("blake3::blake3(char of 16 bytes through void", [&] { + blake3 seeded{static_cast(bytes.data()), std::size_t{16}}; + BOOST_TEST(seeded.result().size() == 32); + }); + // The seed that keys leaves a keyed object. + blake3 seeded{std::uint64_t{7}}; + test::require_enters("blake3::update(void of a seeded object", + [&] { seeded.update(static_cast(bytes.data()), 3); }); + + // The plain mode, and the seeds that are plain, compute on public data. + test::uncovered("blake3::blake3()", [&] { blake3 plain; }); + blake3 plain; + test::uncovered("blake3::update(void of a plain object", + [&] { plain.update(static_cast(bytes.data()), bytes.size()); }); + test::uncovered("blake3::update(unsigned of a plain object", [&] { + plain.update(static_cast(bytes.data()), bytes.size()); + }); + test::uncovered("blake3::result of a plain object", + [&] { BOOST_TEST(plain.result().size() == 32); }); + test::uncovered("blake3::squeeze of a plain object", [&] { + std::array out{}; + plain.squeeze(out); + }); + test::uncovered("blake3::reset of a plain object", [&] { plain.reset(); }); + test::uncovered("blake3 of a zero integer seed", [&] { + blake3 zero{std::uint64_t{0}}; + zero.update(static_cast(bytes.data()), 3); + BOOST_TEST(zero.result().size() == 32); + }); + test::uncovered("blake3 of a seed of no bytes", [&] { + blake3 empty{static_cast(bytes.data()), std::size_t{0}}; + empty.update(static_cast(bytes.data()), 3); + BOOST_TEST(empty.result().size() == 32); + }); + test::uncovered("blake3 of a seed of no bytes through void", [&] { + blake3 empty{static_cast(bytes.data()), std::size_t{0}}; + BOOST_TEST(empty.result().size() == 32); + }); +} + +} // namespace + +int main() { + mac_enters(); + mac_leaves_set_state(); + keyed_blake2b(); + unkeyed_blake2b_enters_none(); + moved_keyed_hasher(); + blake3_vectors_unchanged(); + blake3_modes(); + return webcpp::test::exit_status(boost::report_errors()); +} From 5cd3d2599f75b713f0638c2f9bf71e36e1b3bcea Mon Sep 17 00:00:00 2001 From: R Date: Sun, 22 Nov 2026 07:27:18 -0300 Subject: [PATCH 04/27] hash: the labels of timing_keyed's BLAKE3 checks spell the overload they name --- test/timing_keyed_test.cpp | 29 +++++++++++++++-------------- 1 file changed, 15 insertions(+), 14 deletions(-) diff --git a/test/timing_keyed_test.cpp b/test/timing_keyed_test.cpp index 7b847ae..c24829e 100644 --- a/test/timing_keyed_test.cpp +++ b/test/timing_keyed_test.cpp @@ -262,10 +262,10 @@ void blake3_modes() { std::array const bytes{1, 2, 3, 4, 5, 6, 7, 8, 9}; std::optional keyed; test::require_enters("blake3::keyed", [&] { keyed.emplace(blake3::keyed(key)); }); - test::require_enters("blake3::update(void of a keyed object", [&] { + test::require_enters("blake3::update(void const*) of a keyed object", [&] { keyed->update(static_cast(bytes.data()), bytes.size()); }); - test::require_enters("blake3::update(unsigned of a keyed object", [&] { + test::require_enters("blake3::update(unsigned char const*) of a keyed object", [&] { keyed->update(static_cast(bytes.data()), bytes.size()); }); test::require_enters("blake3::result of a keyed object", @@ -278,7 +278,7 @@ void blake3_modes() { std::optional derived; test::require_enters("blake3::derive_key", [&] { derived.emplace(blake3::derive_key("ctx")); }); - test::require_enters("blake3::update(void of a derived object", [&] { + test::require_enters("blake3::update(void const*) of a derived object", [&] { derived->update(static_cast(bytes.data()), bytes.size()); }); test::require_enters("blake3::result of a derived object", @@ -287,10 +287,10 @@ void blake3_modes() { // A copy and a move of a keyed object are keyed as it is. blake3 copy{*keyed}; - test::require_enters("blake3::update(void of a copy of a keyed object", + test::require_enters("blake3::update(void const*) of a copy of a keyed object", [&] { copy.update(static_cast(bytes.data()), 1); }); blake3 moved{std::move(copy)}; - test::require_enters("blake3::update(void of a moved keyed object", + test::require_enters("blake3::update(void const*) of a moved keyed object", [&] { moved.update(static_cast(bytes.data()), 1); }); // The seeds that key: a non-zero integer, and bytes. @@ -298,30 +298,31 @@ void blake3_modes() { blake3 seeded{std::uint64_t{7}}; BOOST_TEST(seeded.result().size() == 32); }); - test::require_enters("blake3::blake3(char of 16 bytes", [&] { + test::require_enters("blake3::blake3(unsigned char const*) of 16 bytes", [&] { blake3 seeded{static_cast(bytes.data()), std::size_t{16}}; BOOST_TEST(seeded.result().size() == 32); }); - test::require_enters("blake3::blake3(char of 40 bytes", [&] { + test::require_enters("blake3::blake3(unsigned char const*) of 40 bytes", [&] { blake3 seeded{static_cast(bytes.data()), std::size_t{40}}; BOOST_TEST(seeded.result().size() == 32); }); // The delegating constructor of void const* holds none: the one it delegates to runs first. - test::require_enters("blake3::blake3(char of 16 bytes through void", [&] { - blake3 seeded{static_cast(bytes.data()), std::size_t{16}}; - BOOST_TEST(seeded.result().size() == 32); - }); + test::require_enters( + "blake3::blake3(unsigned char const*) of 16 bytes, through the void const* overload", [&] { + blake3 seeded{static_cast(bytes.data()), std::size_t{16}}; + BOOST_TEST(seeded.result().size() == 32); + }); // The seed that keys leaves a keyed object. blake3 seeded{std::uint64_t{7}}; - test::require_enters("blake3::update(void of a seeded object", + test::require_enters("blake3::update(void const*) of a seeded object", [&] { seeded.update(static_cast(bytes.data()), 3); }); // The plain mode, and the seeds that are plain, compute on public data. test::uncovered("blake3::blake3()", [&] { blake3 plain; }); blake3 plain; - test::uncovered("blake3::update(void of a plain object", + test::uncovered("blake3::update(void const*) of a plain object", [&] { plain.update(static_cast(bytes.data()), bytes.size()); }); - test::uncovered("blake3::update(unsigned of a plain object", [&] { + test::uncovered("blake3::update(unsigned char const*) of a plain object", [&] { plain.update(static_cast(bytes.data()), bytes.size()); }); test::uncovered("blake3::result of a plain object", From 08245b0e3fed37fa3da00a9b6ed9e323a90dd43b Mon Sep 17 00:00:00 2001 From: R Date: Sun, 22 Nov 2026 07:39:22 -0300 Subject: [PATCH 05/27] hash: the key derivations and the password hashes set DIT around each call on every backend --- include/webcpp/hash/argon2.hpp | 6 + include/webcpp/hash/bcrypt.hpp | 7 ++ include/webcpp/hash/blake2b_subkey.hpp | 5 + include/webcpp/hash/hkdf.hpp | 7 ++ include/webcpp/hash/kdf_standards.hpp | 7 ++ include/webcpp/hash/pbkdf2.hpp | 5 + include/webcpp/hash/scrypt.hpp | 5 + test/Jamfile | 9 ++ test/timing_keyed_botan_test.cpp | 167 +++++++++++++++++++++++++ test/timing_keyed_openssl_test.cpp | 136 ++++++++++++++++++++ test/timing_keyed_test.cpp | 137 +++++++++++++++++++- 11 files changed, 487 insertions(+), 4 deletions(-) create mode 100644 test/timing_keyed_botan_test.cpp create mode 100644 test/timing_keyed_openssl_test.cpp diff --git a/include/webcpp/hash/argon2.hpp b/include/webcpp/hash/argon2.hpp index 2b0a639..847c4a1 100644 --- a/include/webcpp/hash/argon2.hpp +++ b/include/webcpp/hash/argon2.hpp @@ -12,6 +12,9 @@ of RFC 9106, on the backends that have each (Argon2i on libsodium with one lane; every variant and every parameter on OpenSSL; every variant on Botan, at most 128 lanes and 8 GiB). + Every call holds the data-independent-timing guard (`detail::timing_guard`): where the CPU has + DIT, the call sets it and leaves the thread's state as it found it. + Every guard runs before any work, and a guard's refusal leaves the output as it was; a backend's failure zeroes it. The backend allocates the memory the costs name. @@ -36,6 +39,7 @@ #include #include +#include #include #include #include @@ -160,6 +164,7 @@ template > std::span password_bytes, std::span salt_bytes, argon2id_parameters const& cost_parameters) { + detail::timing_guard const timing; auto guarded = detail::argon2id_guards(output_bytes.size(), password_bytes.size(), salt_bytes.size(), cost_parameters); if (!guarded) { @@ -290,6 +295,7 @@ template > std::span password, std::span salt, argon2_parameters const& parameters) { + detail::timing_guard const timing; auto guarded = detail::argon2_guards(output.size(), password.size(), salt.size(), parameters); if (!guarded) { diff --git a/include/webcpp/hash/bcrypt.hpp b/include/webcpp/hash/bcrypt.hpp index 05264ba..b657155 100644 --- a/include/webcpp/hash/bcrypt.hpp +++ b/include/webcpp/hash/bcrypt.hpp @@ -16,6 +16,9 @@ another implementation would not. For a new design Argon2id (`argon2id`) is the better choice; bcrypt is here to check and make the strings that systems already store. + Every call holds the data-independent-timing guard (`detail::timing_guard`): where the CPU has + DIT, the call sets it and leaves the thread's state as it found it. + Every guard runs before any work, and a guard's refusal leaves the output as it was; a backend's failure zeroes it. The caller gives every input, the salt included: hash draws no random byte. @@ -38,6 +41,7 @@ #include #include +#include #include #include #include @@ -255,6 +259,7 @@ template > std::span password, std::span salt, bcrypt_parameters const& parameters = {}) { + detail::timing_guard const timing; auto guarded = detail::bcrypt_guards(output.size(), password, salt.size(), parameters); if (!guarded) { return guarded; @@ -285,6 +290,7 @@ template > template > [[nodiscard]] boost::system::result bcrypt_verify(std::span password, std::string_view hash) { + detail::timing_guard const timing; auto const guarded = detail::bcrypt_verify_guards(password, hash); if (!guarded) { return guarded.error(); @@ -311,6 +317,7 @@ template > std::span password, std::span salt, std::uint32_t rounds) { + detail::timing_guard const timing; auto guarded = detail::bcrypt_pbkdf_guards(output.size(), password.size(), salt.size(), rounds); if (!guarded) { return guarded; diff --git a/include/webcpp/hash/blake2b_subkey.hpp b/include/webcpp/hash/blake2b_subkey.hpp index a47899d..821d6f7 100644 --- a/include/webcpp/hash/blake2b_subkey.hpp +++ b/include/webcpp/hash/blake2b_subkey.hpp @@ -14,6 +14,9 @@ zero bytes as the personalisation: the bytes libsodium's `crypto_kdf_derive_from_key` gives, so that a program and a libsodium peer derive the same keys. + Every call holds the data-independent-timing guard (`detail::timing_guard`): where the CPU has + DIT, the call sets it and leaves the thread's state as it found it. + Every guard runs before any work, and a guard's refusal leaves the output as it was; a backend's failure zeroes it. @@ -34,6 +37,7 @@ #include #include +#include #include #include #include @@ -83,6 +87,7 @@ template > std::span master_key, std::uint64_t subkey_id, std::span context) { + detail::timing_guard const timing; using engine = detail::blake2b_subkey_engine; if (output.size() < blake2b_subkey_min_size || output.size() > blake2b_subkey_max_size) { return error::invalid_output_size; diff --git a/include/webcpp/hash/hkdf.hpp b/include/webcpp/hash/hkdf.hpp index a27fb7e..0333b43 100644 --- a/include/webcpp/hash/hkdf.hpp +++ b/include/webcpp/hash/hkdf.hpp @@ -8,6 +8,9 @@ HKDF, RFC 5869: `hkdf_extract`, `hkdf_expand` and `hkdf`, over any Boost.Hash2 hmac whose result is a digest, on the backend the call names or on @ref webcpp::hash::default_kdf_backend. + Every call holds the data-independent-timing guard (`detail::timing_guard`): where the CPU has + DIT, the call sets it and leaves the thread's state as it found it. + Every guard runs before any work, and a guard's refusal leaves the output as it was; a backend's failure zeroes it. @@ -30,6 +33,7 @@ #include #include #include +#include #include #include #include @@ -111,6 +115,7 @@ template template > [[nodiscard]] boost::system::result::type> hkdf_extract( std::span salt_bytes, std::span ikm_bytes) { + detail::timing_guard const timing; if constexpr (!detail::takes_hmac()) { return error::backend_failure; // unreachable: takes_hmac has stopped the build } else { @@ -139,6 +144,7 @@ template hkdf_expand(std::span output_bytes, std::span prk_bytes, std::span info_bytes) { + detail::timing_guard const timing; if constexpr (!detail::takes_hmac()) { return error::backend_failure; // unreachable: takes_hmac has stopped the build } else { @@ -189,6 +195,7 @@ template > std::span salt_bytes, std::span ikm_bytes, std::span info_bytes) { + detail::timing_guard const timing; if constexpr (!detail::takes_hmac()) { return error::backend_failure; // unreachable: takes_hmac has stopped the build } else { diff --git a/include/webcpp/hash/kdf_standards.hpp b/include/webcpp/hash/kdf_standards.hpp index 5c61d55..7905662 100644 --- a/include/webcpp/hash/kdf_standards.hpp +++ b/include/webcpp/hash/kdf_standards.hpp @@ -17,6 +17,9 @@ None of them is for a password (Argon2id is) nor a better choice than HKDF for a new design: they are here to derive the bytes a standard, a smart card or another library derives. + Every call holds the data-independent-timing guard (`detail::timing_guard`): where the CPU has + DIT, the call sets it and leaves the thread's state as it found it. + Every guard runs before any work, and a guard's refusal leaves the output as it was; a backend's failure zeroes it. @@ -39,6 +42,7 @@ #include #include +#include #include #include #include @@ -285,6 +289,7 @@ template > [[nodiscard]] boost::system::result kbkdf(std::span output, std::span key, kbkdf_options const& options = {}) { + detail::timing_guard const timing; if constexpr (!detail::takes_hmac()) { return error::backend_failure; // unreachable: takes_hmac has stopped the build } else { @@ -353,6 +358,7 @@ template > [[nodiscard]] boost::system::result sskdf(std::span output, std::span secret, std::span fixed_info = {}) { + detail::timing_guard const timing; if constexpr (!detail::sskdf_takes()) { return error::backend_failure; // unreachable: sskdf_takes has stopped the build } else { @@ -414,6 +420,7 @@ template > [[nodiscard]] boost::system::result x963kdf(std::span output, std::span secret, std::span shared_info = {}) { + detail::timing_guard const timing; if constexpr (!detail::x963kdf_takes()) { return error::backend_failure; // unreachable: x963kdf_takes has stopped the build } else { diff --git a/include/webcpp/hash/pbkdf2.hpp b/include/webcpp/hash/pbkdf2.hpp index 75fefcf..0bd7f6a 100644 --- a/include/webcpp/hash/pbkdf2.hpp +++ b/include/webcpp/hash/pbkdf2.hpp @@ -8,6 +8,9 @@ PBKDF2, RFC 8018: `pbkdf2`, over any Boost.Hash2 hmac whose result is a digest, on the backend the call names or on @ref webcpp::hash::default_kdf_backend. + Every call holds the data-independent-timing guard (`detail::timing_guard`): where the CPU has + DIT, the call sets it and leaves the thread's state as it found it. + Every guard runs before any work, and a guard's refusal leaves the output as it was; a backend's failure zeroes it. @@ -30,6 +33,7 @@ #include #include #include +#include #include #include #include @@ -124,6 +128,7 @@ template > std::span password_bytes, std::span salt_bytes, std::uint64_t iteration_count) { + detail::timing_guard const timing; if constexpr (!detail::takes_hmac()) { return error::backend_failure; // unreachable: takes_hmac has stopped the build } else { diff --git a/include/webcpp/hash/scrypt.hpp b/include/webcpp/hash/scrypt.hpp index d6c8098..3e1ceca 100644 --- a/include/webcpp/hash/scrypt.hpp +++ b/include/webcpp/hash/scrypt.hpp @@ -9,6 +9,9 @@ `crypto_pwhash_scryptsalsa208sha256_ll`, the default), `backends::openssl` (OpenSSL's "SCRYPT", its own memory limit lifted) and `backends::botan` (Botan's "Scrypt", in part). + Every call holds the data-independent-timing guard (`detail::timing_guard`): where the CPU has + DIT, the call sets it and leaves the thread's state as it found it. + Every guard runs before any work, and a guard's refusal leaves the output as it was; a backend's failure zeroes it. The backend allocates the 128 r (N + p) bytes the costs name. @@ -33,6 +36,7 @@ #include #include +#include #include #include #include @@ -157,6 +161,7 @@ template > std::span password_bytes, std::span salt_bytes, scrypt_parameters const& cost_parameters) { + detail::timing_guard const timing; auto guarded = detail::scrypt_guards(output_bytes.size(), password_bytes.size(), salt_bytes.size(), cost_parameters); if (!guarded) { diff --git a/test/Jamfile b/test/Jamfile index 453d4cf..6e1b29a 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -717,6 +717,15 @@ hash-run timing_keyed : timing_keyed_test.cpp : /third_party//blake3 /third_party//sodium /third_party//blake3_vectors /webcpp//boost_json ; +# The key derivations and password hashes hold detail::timing_guard on every +# backend: timing_keyed covers the default backends'; kbkdf, sskdf and x963kdf, +# and a second cell of the templates, on backends::openssl, here, and bcrypt, +# bcrypt_verify and bcrypt_pbkdf, and a cell of the templates, on +# backends::botan (exceptions on, native and Emscripten). +hash-run timing_keyed_openssl : timing_keyed_openssl_test.cpp + : /webcpp/hash//openssl : native wasip2 wasip3 ; +botan-run timing_keyed_botan : timing_keyed_botan_test.cpp ; + build-project messages ; # The canaries at link time, each C library's absence and another commit of diff --git a/test/timing_keyed_botan_test.cpp b/test/timing_keyed_botan_test.cpp new file mode 100644 index 0000000..2b92fe8 --- /dev/null +++ b/test/timing_keyed_botan_test.cpp @@ -0,0 +1,167 @@ +// 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) + +// bcrypt, bcrypt_verify and bcrypt_pbkdf, which only backends::botan serves, and a cell of each +// other key derivation and password hash on it, hold detail::timing_guard (design D1, D4, D6, +// ruling H10): each enters its own guard first, through the seam, also for a call that a guard +// refuses before the backend, and Botan's boundary, which turns its exceptions into errors, holds +// none. The functions of the default backends are in timing_keyed_test.cpp. + +#include "support/timing_seam.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include + +namespace { + +namespace hash = webcpp::hash; +namespace test = webcpp::test; +namespace digests = webcpp::hash::digests; +namespace kdfs = webcpp::hash::kdfs; +using hash::backends::botan; +using hmac_sha2_256 = hash::hmac_sha2_256; + +std::array const key = [] { + std::array bytes{}; + for (std::size_t i = 0; i < bytes.size(); ++i) { + bytes[i] = static_cast(i + 1); + } + return bytes; +}(); +std::array const info{9, 8, 7, 6, 5, 4, 3, 2, 1}; +std::array const salt{16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1}; + +// bcrypt, bcrypt_verify and bcrypt_pbkdf each enter their own guard, at the lowest cost; a call +// that a guard refuses (a salt of 8 bytes, a malformed string, 0 rounds) enters it too. +void bcrypt_enters() { + std::array made{}; + test::require_enters("hash::bcrypt of cost 4 on botan", [&] { + BOOST_TEST((hash::bcrypt(made, key, salt, {.cost = 4})).has_value()); + }); + std::array again{}; + test::require_enters("hash::bcrypt with the same arguments on botan", [&] { + BOOST_TEST((hash::bcrypt(again, key, salt, {.cost = 4})).has_value()); + }); + BOOST_TEST(made == again); + test::require_enters("hash::bcrypt with a salt of 8 bytes on botan", [&] { + BOOST_TEST( + !(hash::bcrypt(again, key, std::span{salt}.first(8), {.cost = 4})).has_value()); + }); + + std::string_view const text{made.data(), made.size()}; + test::require_enters("hash::bcrypt_verify of the right password on botan", [&] { + auto const checked = hash::bcrypt_verify(key, text); + BOOST_TEST(checked.has_value() && *checked); + }); + test::require_enters("hash::bcrypt_verify of the wrong password on botan", [&] { + auto const checked = hash::bcrypt_verify(salt, text); + BOOST_TEST(checked.has_value() && !*checked); + }); + test::require_enters("hash::bcrypt_verify of a string of the wrong form on botan", [&] { + BOOST_TEST(!hash::bcrypt_verify(key, "not a bcrypt string").has_value()); + }); + + std::array derived{}; + test::require_enters("hash::bcrypt_pbkdf of 1 round on botan", [&] { + BOOST_TEST((hash::bcrypt_pbkdf(derived, key, salt, 1)).has_value()); + }); + test::require_enters("hash::bcrypt_pbkdf of 0 rounds on botan", [&] { + BOOST_TEST(!(hash::bcrypt_pbkdf(derived, key, salt, 0)).has_value()); + }); +} + +// One cell of every other function: the template's guard covers Botan's engine, and no function +// of the backend holds one of its own. +void templates_enter() { + std::array derived{}; + std::array none{}; + using prk_type = hmac_sha2_256::result_type; + std::optional prk; + test::require_enters("hash::hkdf_extract of a salt on botan", [&] { + auto const made = hash::hkdf_extract(salt, key); + if (BOOST_TEST(made.has_value())) { + prk.emplace(*made); + } + }); + if (prk) { + test::require_enters("hash::hkdf_expand of a prk on botan", [&] { + BOOST_TEST((hash::hkdf_expand(derived, *prk, info)).has_value()); + }); + } + test::require_enters("hash::hkdf of a salt on botan", [&] { + BOOST_TEST((hash::hkdf(derived, salt, key, info)).has_value()); + }); + test::require_enters("hash::hkdf with an output of no byte on botan", [&] { + BOOST_TEST(!(hash::hkdf(none, salt, key, info)).has_value()); + }); + test::require_enters("hash::pbkdf2 of 1000 iterations on botan", [&] { + BOOST_TEST((hash::pbkdf2(derived, key, salt, 1000)).has_value()); + }); + test::require_enters("hash::pbkdf2 of 0 iterations on botan", [&] { + BOOST_TEST(!(hash::pbkdf2(derived, key, salt, 0)).has_value()); + }); + test::require_enters("hash::kbkdf of hmac_sha2_256 on botan", [&] { + BOOST_TEST( + (hash::kbkdf(derived, key, {.label = info, .context = salt})) + .has_value()); + }); + test::require_enters("hash::kbkdf with a counter of 7 bits on botan", [&] { + BOOST_TEST( + !(hash::kbkdf(derived, key, {.counter_bits = 7})).has_value()); + }); + test::require_enters("hash::sskdf of sha2_256 on botan", [&] { + BOOST_TEST((hash::sskdf(derived, key, info)).has_value()); + }); + test::require_enters("hash::x963kdf of sha2_256 on botan", [&] { + BOOST_TEST((hash::x963kdf(derived, key, info)).has_value()); + }); + test::require_enters("hash::argon2id of the minimum parameters on botan", [&] { + BOOST_TEST( + (hash::argon2id(derived, key, salt, {.passes = 1, .memory = 8192})).has_value()); + }); + hash::argon2_parameters const family{.passes = 1, .memory_kib = 8}; + test::require_enters("hash::argon2 of argon2d on botan", [&] { + BOOST_TEST((hash::argon2(derived, key, salt, family)).has_value()); + }); + test::require_enters("hash::argon2 of argon2i on botan", [&] { + BOOST_TEST((hash::argon2(derived, key, salt, family)).has_value()); + }); + test::require_enters("hash::argon2 of argon2id on botan", [&] { + BOOST_TEST((hash::argon2(derived, key, salt, family)).has_value()); + }); + test::require_enters("hash::scrypt of N = 16 on botan", [&] { + BOOST_TEST( + (hash::scrypt(derived, key, salt, {.n = 16, .r = 1, .p = 1})).has_value()); + }); + test::require_enters("hash::scrypt of N = 1 on botan", [&] { + BOOST_TEST( + !(hash::scrypt(derived, key, salt, {.n = 1, .r = 1, .p = 1})).has_value()); + }); +} + +} // namespace + +int main() { + bcrypt_enters(); + templates_enter(); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/timing_keyed_openssl_test.cpp b/test/timing_keyed_openssl_test.cpp new file mode 100644 index 0000000..535aa16 --- /dev/null +++ b/test/timing_keyed_openssl_test.cpp @@ -0,0 +1,136 @@ +// 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 key derivations and the password hashes on backends::openssl hold detail::timing_guard +// (design D1, D4, D6): each enters its own guard first, through the seam, also for a call that a +// guard refuses before the backend. The functions the default backends cover are in +// timing_keyed_test.cpp; here are the three that OpenSSL alone serves (kbkdf, sskdf and x963kdf) +// and, as a second cell of each template, hkdf, pbkdf2, argon2id, argon2 and scrypt. + +#include "support/timing_seam.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include + +namespace { + +namespace hash = webcpp::hash; +namespace test = webcpp::test; +namespace digests = webcpp::hash::digests; +namespace kdfs = webcpp::hash::kdfs; +using hash::backends::openssl; +using hmac_sha2_256 = hash::hmac_sha2_256; + +std::array const key = [] { + std::array bytes{}; + for (std::size_t i = 0; i < bytes.size(); ++i) { + bytes[i] = static_cast(i + 1); + } + return bytes; +}(); +std::array const info{9, 8, 7, 6, 5, 4, 3, 2, 1}; +std::array const salt{16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1}; + +// kbkdf, sskdf and x963kdf each enter their own guard; a call that a guard refuses (a counter +// width of 7 bits, an output of no byte) enters it too, and the guard changes no byte. +void standards_enter() { + std::array derived{}; + test::require_enters("hash::kbkdf of hmac_sha2_256 on openssl", [&] { + BOOST_TEST( + (hash::kbkdf(derived, key, {.label = info, .context = salt})) + .has_value()); + }); + test::require_enters("hash::kbkdf with a counter of 7 bits on openssl", [&] { + BOOST_TEST( + !(hash::kbkdf(derived, key, {.counter_bits = 7})).has_value()); + }); + test::require_enters("hash::sskdf of sha2_256 on openssl", [&] { + BOOST_TEST((hash::sskdf(derived, key, info)).has_value()); + }); + std::array none{}; + test::require_enters("hash::sskdf with an output of no byte on openssl", [&] { + BOOST_TEST(!(hash::sskdf(none, key, info)).has_value()); + }); + test::require_enters("hash::x963kdf of sha2_256 on openssl", [&] { + BOOST_TEST((hash::x963kdf(derived, key, info)).has_value()); + }); + test::require_enters("hash::x963kdf with an output of no byte on openssl", [&] { + BOOST_TEST(!(hash::x963kdf(none, key, info)).has_value()); + }); +} + +// The templates the default backends cover, over OpenSSL's engines: the guard of the template +// covers each backend's (H2). +void templates_enter() { + std::array derived{}; + using prk_type = hmac_sha2_256::result_type; + std::optional prk; + test::require_enters("hash::hkdf_extract of a salt on openssl", [&] { + auto const made = hash::hkdf_extract(salt, key); + if (BOOST_TEST(made.has_value())) { + prk.emplace(*made); + } + }); + if (prk) { + test::require_enters("hash::hkdf_expand of a prk on openssl", [&] { + BOOST_TEST( + (hash::hkdf_expand(derived, *prk, info)).has_value()); + }); + } + test::require_enters("hash::hkdf of a salt on openssl", [&] { + BOOST_TEST((hash::hkdf(derived, salt, key, info)).has_value()); + }); + test::require_enters("hash::pbkdf2 of 1000 iterations on openssl", [&] { + BOOST_TEST((hash::pbkdf2(derived, key, salt, 1000)).has_value()); + }); + test::require_enters("hash::pbkdf2 of 0 iterations on openssl", [&] { + BOOST_TEST(!(hash::pbkdf2(derived, key, salt, 0)).has_value()); + }); + test::require_enters("hash::argon2id of the minimum parameters on openssl", [&] { + BOOST_TEST((hash::argon2id(derived, key, salt, {.passes = 1, .memory = 8192})) + .has_value()); + }); + hash::argon2_parameters const family{.passes = 1, .memory_kib = 8}; + test::require_enters("hash::argon2 of argon2d on openssl", [&] { + BOOST_TEST((hash::argon2(derived, key, salt, family)).has_value()); + }); + test::require_enters("hash::argon2 of argon2i on openssl", [&] { + BOOST_TEST((hash::argon2(derived, key, salt, family)).has_value()); + }); + test::require_enters("hash::argon2 of argon2id on openssl", [&] { + BOOST_TEST((hash::argon2(derived, key, salt, family)).has_value()); + }); + test::require_enters("hash::scrypt of N = 16 on openssl", [&] { + BOOST_TEST( + (hash::scrypt(derived, key, salt, {.n = 16, .r = 1, .p = 1})).has_value()); + }); + test::require_enters("hash::scrypt of N = 1 on openssl", [&] { + BOOST_TEST( + !(hash::scrypt(derived, key, salt, {.n = 1, .r = 1, .p = 1})).has_value()); + }); +} + +} // namespace + +int main() { + standards_enter(); + templates_enter(); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/timing_keyed_test.cpp b/test/timing_keyed_test.cpp index c24829e..3bac2e4 100644 --- a/test/timing_keyed_test.cpp +++ b/test/timing_keyed_test.cpp @@ -4,19 +4,26 @@ // accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) -// mac, and the keyed modes of BLAKE2b (digest_of, hasher) and of BLAKE3 (the blake3 class), hold -// detail::timing_guard (design D1, D4): each enters its own guard first, on every target, through -// the seam; a call that is not keyed enters none (D2); a guard changes no byte of any output. -// Where the CPU has DIT, mac leaves the thread's state as it found it. +// mac, the keyed modes of BLAKE2b (digest_of, hasher) and of BLAKE3 (the blake3 class), and the +// key derivations and password hashes of the default backends (hkdf_extract, hkdf_expand, hkdf, +// pbkdf2, blake2b_subkey, argon2id, argon2, scrypt), hold detail::timing_guard (design D1, D4): +// each enters its own guard first, on every target, through the seam, also for a call that a +// guard refuses before the backend; a call that is not keyed enters none (D2); a guard changes no +// byte of any output. Where the CPU has DIT, mac leaves the thread's state as it found it. #include "support/timing_seam.hpp" #include +#include #include +#include #include #include #include +#include #include +#include +#include #include #include "require.hpp" @@ -348,6 +355,125 @@ void blake3_modes() { }); } +using hmac_sha2_256 = hash::hmac_sha2_256; + +std::array const salt16{16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1}; + +// hkdf_extract and hkdf_expand enter their own guards, and hkdf its own first though it computes +// what the other two do; a call refused by a guard (an output of no byte) enters its guard too. +void hkdf_enters() { + using prk_type = hmac_sha2_256::result_type; + std::optional prk; + test::require_enters("hash::hkdf_extract of a salt on hash2", [&] { + auto const made = hash::hkdf_extract(salt16, key); + if (BOOST_TEST(made.has_value())) { + prk.emplace(*made); + } + }); + if (!prk) { + return; + } + std::array okm{}; + test::require_enters("hash::hkdf_expand of a prk on hash2", [&] { + BOOST_TEST( + (hash::hkdf_expand(okm, *prk, input)).has_value()); + }); + test::require_enters("hash::hkdf_expand with a prk of the wrong size on hash2", [&] { + BOOST_TEST(!(hash::hkdf_expand( + okm, std::span{key}.first(5), input)) + .has_value()); + }); + std::array whole{}; + test::require_enters("hash::hkdf of a salt on hash2", [&] { + BOOST_TEST( + (hash::hkdf(whole, salt16, key, input)).has_value()); + }); + // The two steps give what hkdf gives: the guards change no byte. + std::array stepped{}; + auto const extracted = hash::hkdf_extract(salt16, key); + if (BOOST_TEST(extracted.has_value())) { + BOOST_TEST((hash::hkdf_expand(stepped, *extracted, input)) + .has_value()); + BOOST_TEST(stepped == whole); + } + std::array none{}; + test::require_enters("hash::hkdf with an output of no byte on hash2", [&] { + BOOST_TEST( + !(hash::hkdf(none, salt16, key, input)).has_value()); + }); +} + +// pbkdf2 enters its guard, also for an iteration count of 0, and derives the same bytes. +void pbkdf2_enters() { + std::array derived{}; + test::require_enters("hash::pbkdf2 of 1000 iterations on hash2", [&] { + BOOST_TEST( + (hash::pbkdf2(derived, key, salt16, 1000)).has_value()); + }); + std::array again{}; + test::require_enters("hash::pbkdf2 with the same arguments on hash2", [&] { + BOOST_TEST( + (hash::pbkdf2(again, key, salt16, 1000)).has_value()); + }); + BOOST_TEST(derived == again); + test::require_enters("hash::pbkdf2 of 0 iterations on hash2", [&] { + BOOST_TEST( + !(hash::pbkdf2(derived, key, salt16, 0)).has_value()); + }); +} + +// blake2b_subkey, argon2id, argon2 and scrypt on sodium, each also with a parameter refused +// before the backend. +void sodium_derivations_enter() { + std::array const context{'c', 't', 'x', '_', 't', 'e', 's', 't'}; + std::array subkey{}; + test::require_enters("hash::blake2b_subkey on sodium", [&] { + BOOST_TEST((hash::blake2b_subkey(subkey, key, 7, context)).has_value()); + }); + std::array tiny{}; + test::require_enters("hash::blake2b_subkey with an output too small on sodium", [&] { + BOOST_TEST(!(hash::blake2b_subkey(tiny, key, 7, context)).has_value()); + }); + + std::array derived{}; + hash::argon2id_parameters const cheapest{.passes = 1, .memory = 8192}; + test::require_enters("hash::argon2id of the minimum parameters on sodium", [&] { + BOOST_TEST((hash::argon2id(derived, key, salt16, cheapest)).has_value()); + }); + std::array const short_salt{1, 2, 3, 4}; + test::require_enters("hash::argon2id with a salt of the wrong size on sodium", [&] { + BOOST_TEST( + !(hash::argon2id(derived, key, short_salt, cheapest)).has_value()); + }); + + hash::argon2_parameters const family{.passes = 3, .memory_kib = 8}; + test::require_enters("hash::argon2 of argon2id on sodium", [&] { + BOOST_TEST( + (hash::argon2(derived, key, salt16, family)) + .has_value()); + }); + test::require_enters("hash::argon2 of argon2i on sodium", [&] { + BOOST_TEST( + (hash::argon2(derived, key, salt16, family)) + .has_value()); + }); + test::require_enters("hash::argon2 with a salt too short on sodium", [&] { + BOOST_TEST(!(hash::argon2(derived, key, short_salt, + family)) + .has_value()); + }); + + hash::scrypt_parameters const small{.n = 16, .r = 1, .p = 1}; + test::require_enters("hash::scrypt of N = 16 on sodium", [&] { + BOOST_TEST((hash::scrypt(derived, key, salt16, small)).has_value()); + }); + test::require_enters("hash::scrypt of N = 1 on sodium", [&] { + BOOST_TEST(!(hash::scrypt( + derived, key, salt16, hash::scrypt_parameters{.n = 1, .r = 1, .p = 1})) + .has_value()); + }); +} + } // namespace int main() { @@ -358,5 +484,8 @@ int main() { moved_keyed_hasher(); blake3_vectors_unchanged(); blake3_modes(); + hkdf_enters(); + pbkdf2_enters(); + sodium_derivations_enter(); return webcpp::test::exit_status(boost::report_errors()); } From 37640c69f56c45005a26071740d1db410804f505 Mon Sep 17 00:00:00 2001 From: R Date: Sun, 22 Nov 2026 07:56:28 -0300 Subject: [PATCH 06/27] hash: the timing_keyed tests pass clang-tidy: constant keys, HKDF apart from the other derivations, and blake3's move named as its copy --- test/timing_keyed_botan_test.cpp | 17 ++++++++++++----- test/timing_keyed_openssl_test.cpp | 17 ++++++++++++----- test/timing_keyed_test.cpp | 5 +++-- 3 files changed, 27 insertions(+), 12 deletions(-) diff --git a/test/timing_keyed_botan_test.cpp b/test/timing_keyed_botan_test.cpp index 2b92fe8..73cafef 100644 --- a/test/timing_keyed_botan_test.cpp +++ b/test/timing_keyed_botan_test.cpp @@ -40,7 +40,7 @@ namespace kdfs = webcpp::hash::kdfs; using hash::backends::botan; using hmac_sha2_256 = hash::hmac_sha2_256; -std::array const key = [] { +constexpr std::array key = [] { std::array bytes{}; for (std::size_t i = 0; i < bytes.size(); ++i) { bytes[i] = static_cast(i + 1); @@ -89,9 +89,9 @@ void bcrypt_enters() { }); } -// One cell of every other function: the template's guard covers Botan's engine, and no function -// of the backend holds one of its own. -void templates_enter() { +// HKDF's three functions, one cell each: the template's guard covers Botan's engine, and no +// function of the backend holds one of its own. +void hkdf_enters() { std::array derived{}; std::array none{}; using prk_type = hmac_sha2_256::result_type; @@ -113,6 +113,12 @@ void templates_enter() { test::require_enters("hash::hkdf with an output of no byte on botan", [&] { BOOST_TEST(!(hash::hkdf(none, salt, key, info)).has_value()); }); +} + +// The other key derivations and the password hashes over Botan's engines, each entering its +// template's guard, as hkdf_enters' functions do. +void derivations_enter() { + std::array derived{}; test::require_enters("hash::pbkdf2 of 1000 iterations on botan", [&] { BOOST_TEST((hash::pbkdf2(derived, key, salt, 1000)).has_value()); }); @@ -162,6 +168,7 @@ void templates_enter() { int main() { bcrypt_enters(); - templates_enter(); + hkdf_enters(); + derivations_enter(); return webcpp::test::exit_status(boost::report_errors()); } diff --git a/test/timing_keyed_openssl_test.cpp b/test/timing_keyed_openssl_test.cpp index 535aa16..77539d5 100644 --- a/test/timing_keyed_openssl_test.cpp +++ b/test/timing_keyed_openssl_test.cpp @@ -38,7 +38,7 @@ namespace kdfs = webcpp::hash::kdfs; using hash::backends::openssl; using hmac_sha2_256 = hash::hmac_sha2_256; -std::array const key = [] { +constexpr std::array key = [] { std::array bytes{}; for (std::size_t i = 0; i < bytes.size(); ++i) { bytes[i] = static_cast(i + 1); @@ -76,9 +76,9 @@ void standards_enter() { }); } -// The templates the default backends cover, over OpenSSL's engines: the guard of the template -// covers each backend's (H2). -void templates_enter() { +// HKDF's three functions, which the default backends cover too, over OpenSSL's engines: the +// guard of the template covers each backend's (H2). +void hkdf_enters() { std::array derived{}; using prk_type = hmac_sha2_256::result_type; std::optional prk; @@ -97,6 +97,12 @@ void templates_enter() { test::require_enters("hash::hkdf of a salt on openssl", [&] { BOOST_TEST((hash::hkdf(derived, salt, key, info)).has_value()); }); +} + +// The other key derivations and the password hashes over OpenSSL's engines, each entering its +// template's guard, as hkdf_enters' functions do. +void derivations_enter() { + std::array derived{}; test::require_enters("hash::pbkdf2 of 1000 iterations on openssl", [&] { BOOST_TEST((hash::pbkdf2(derived, key, salt, 1000)).has_value()); }); @@ -131,6 +137,7 @@ void templates_enter() { int main() { standards_enter(); - templates_enter(); + hkdf_enters(); + derivations_enter(); return webcpp::test::exit_status(boost::report_errors()); } diff --git a/test/timing_keyed_test.cpp b/test/timing_keyed_test.cpp index 3bac2e4..62bc304 100644 --- a/test/timing_keyed_test.cpp +++ b/test/timing_keyed_test.cpp @@ -72,7 +72,7 @@ void force_dit([[maybe_unused]] bool set) { #endif } -std::array const key = [] { +constexpr std::array key = [] { std::array bytes{}; for (std::size_t i = 0; i < bytes.size(); ++i) { bytes[i] = static_cast(i + 1); @@ -296,7 +296,8 @@ void blake3_modes() { blake3 copy{*keyed}; test::require_enters("blake3::update(void const*) of a copy of a keyed object", [&] { copy.update(static_cast(bytes.data()), 1); }); - blake3 moved{std::move(copy)}; + // blake3 is trivially copyable: its move is its copy, which the check names as a move. + blake3 moved{std::move(copy)}; // NOLINT(performance-move-const-arg) test::require_enters("blake3::update(void const*) of a moved keyed object", [&] { moved.update(static_cast(bytes.data()), 1); }); From ebe18fae913bb75848d8d842e9a19aa30a422806 Mon Sep 17 00:00:00 2001 From: R Date: Sun, 22 Nov 2026 08:23:52 -0300 Subject: [PATCH 07/27] hash: timing_keyed holds its destroyed keyed hasher in a unique_ptr, so that GCC 15 at release reads no uninitialized phase in it --- test/timing_keyed_test.cpp | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/test/timing_keyed_test.cpp b/test/timing_keyed_test.cpp index 62bc304..cf0e10f 100644 --- a/test/timing_keyed_test.cpp +++ b/test/timing_keyed_test.cpp @@ -39,6 +39,7 @@ #include #include #include +#include #include #include #include @@ -208,8 +209,9 @@ void moved_keyed_hasher() { // The destructor of a keyed hasher wipes and holds no guard. auto dying = hash::hasher::make(keyed); if (BOOST_TEST(dying.has_value())) { - std::optional> held; - held.emplace(std::move(*dying)); + // Held by a unique_ptr, not a std::optional, whose reset GCC 15 at -O2 reads as a use of + // an uninitialized phase (-Wmaybe-uninitialized). + auto held = std::make_unique>(std::move(*dying)); test::uncovered("destroying a keyed hasher", [&] { held.reset(); }); } } From 5e2e5d598d8ccee5270f9ea359da7108143012a8 Mon Sep 17 00:00:00 2001 From: R Date: Sun, 22 Nov 2026 08:23:52 -0300 Subject: [PATCH 08/27] hash: a coverage test per backend, driven by the capability table, proves every keyed cell enters its own timing guard and every unkeyed one none --- test/Jamfile | 36 +- test/support/timing_coverage.hpp | 1055 +++++++++++++++++++++++++ test/support/timing_seam.hpp | 24 +- test/timing_coverage_bearssl_test.cpp | 31 + test/timing_coverage_blake3_test.cpp | 120 +++ test/timing_coverage_botan_test.cpp | 38 + test/timing_coverage_hash2_test.cpp | 92 +++ test/timing_coverage_openssl_test.cpp | 36 + test/timing_coverage_sodium_test.cpp | 33 + test/timing_coverage_xkcp_test.cpp | 37 + test/timing_keyed_test.cpp | 2 +- 11 files changed, 1473 insertions(+), 31 deletions(-) create mode 100644 test/support/timing_coverage.hpp create mode 100644 test/timing_coverage_bearssl_test.cpp create mode 100644 test/timing_coverage_blake3_test.cpp create mode 100644 test/timing_coverage_botan_test.cpp create mode 100644 test/timing_coverage_hash2_test.cpp create mode 100644 test/timing_coverage_openssl_test.cpp create mode 100644 test/timing_coverage_sodium_test.cpp create mode 100644 test/timing_coverage_xkcp_test.cpp diff --git a/test/Jamfile b/test/Jamfile index 6e1b29a..fed0a6b 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -695,9 +695,9 @@ hash-run allocation_openssl : allocation_openssl_test.cpp : native wasip2 wasip3 ; # detail::timing_guard sets DIT for its scope where the CPU has it and leaves -# the thread's state as it found it; its seam fires on every target for an engaged -# guard and never for a disengaged one. timing_threads adds a second thread, -# natively, with threads. +# the thread's state as it found it; its seam fires on every target for an +# engaged guard and never for a disengaged one. timing_threads adds a second +# thread, natively, with threads. hash-run timing : timing_test.cpp ; hash-run timing_threads : timing_test.cpp : multi WEBCPP_TEST_TIMING_THREADS : native ; @@ -710,12 +710,12 @@ hash-run timing_unseamed : timing_unseamed_test.cpp ; webcpp.run timing_unseamed_release : timing_unseamed_test.cpp : release WEBCPP_TEST_TIMING_READ_SELF : native ; -# mac and the keyed modes of BLAKE2b (digest_of, hasher with a key) and of BLAKE3 -# (keyed, derive_key and the seeds that key) hold detail::timing_guard; a call -# that is not keyed holds none; no output changes. +# mac and the keyed modes of BLAKE2b (digest_of, hasher with a key) and of +# BLAKE3 (keyed, derive_key and the seeds that key) hold detail::timing_guard; a +# call that is not keyed holds none; no output changes. hash-run timing_keyed : timing_keyed_test.cpp - : /third_party//blake3 /third_party//sodium - /third_party//blake3_vectors /webcpp//boost_json ; + : $(.hash-tables) /third_party//blake3 /third_party//sodium + /third_party//blake3_vectors ; # The key derivations and password hashes hold detail::timing_guard on every # backend: timing_keyed covers the default backends'; kbkdf, sskdf and x963kdf, @@ -726,6 +726,26 @@ hash-run timing_keyed_openssl : timing_keyed_openssl_test.cpp : /webcpp/hash//openssl : native wasip2 wasip3 ; botan-run timing_keyed_botan : timing_keyed_botan_test.cpp ; +# One coverage test per backend, driven by doc/capabilities.json: every keyed +# cell of the backend (support/timing_coverage.hpp: macs, key derivations and +# password hashes, one per hmac a cell lists, and BLAKE2b with a key, the +# blake3 type's keyed modes and bcrypt_verify) enters its own +# detail::timing_guard first; every digest cell without a key, and every +# Boost.Hash2-form type, enters none. A cell the table gains fails until its +# call is added. backends::webcrypto has none (design D6). +hash-run timing_coverage_hash2 : timing_coverage_hash2_test.cpp : $(.hash-tables) ; +hash-run timing_coverage_sodium : timing_coverage_sodium_test.cpp + : $(.hash-tables) /third_party//sodium ; +hash-run timing_coverage_bearssl : timing_coverage_bearssl_test.cpp + : $(.hash-tables) /third_party//bearssl ; +hash-run timing_coverage_openssl : timing_coverage_openssl_test.cpp + : $(.hash-tables) /webcpp/hash//openssl : native wasip2 wasip3 ; +hash-run timing_coverage_xkcp : timing_coverage_xkcp_test.cpp + : $(.hash-tables) /third_party//xkcp ; +hash-run timing_coverage_blake3 : timing_coverage_blake3_test.cpp + : $(.hash-tables) /third_party//blake3 ; +botan-run timing_coverage_botan : timing_coverage_botan_test.cpp : $(.hash-tables) ; + build-project messages ; # The canaries at link time, each C library's absence and another commit of diff --git a/test/support/timing_coverage.hpp b/test/support/timing_coverage.hpp new file mode 100644 index 0000000..a97a83b --- /dev/null +++ b/test/support/timing_coverage.hpp @@ -0,0 +1,1055 @@ +// 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 coverage of detail::timing_guard, driven by the capability table: every keyed cell of a +// backend in doc/capabilities.json enters its own guard first and leaves the thread's DIT as it +// found it, and every digest cell of the backend, called without a key, enters none (design D1, +// D2). Each backend's timing_coverage__test.cpp builds its calls from the helpers here +// and hands them to check_and_run, which fails on a keyed cell of the table with no call and on a +// call that names no keyed cell; then it walks the backend's digest cells through +// uncover_digests. A test includes this header before any hash header. +// +// covered, and the support's shape, are a copy of libs/crypto/test/support/timing_coverage.hpp +// with hash's guard: the duplication is accepted for the reason of detail/timing.hpp's own (hash +// includes nothing of crypto). The keyed cells are the table's (ruling H6): every function of +// the chapters macs, kdfs and password_hashing whose kind is not "type", each backend's cell, one +// per hmac where the cell lists hmacs ("other": a Hash2 hmac the list does not name); plus three +// keyed functions the table holds no cell of, named here with design D1 as the reason: BLAKE2b +// with a key (digest_of and a hasher round) wherever the backend has digests::blake2b, the blake3 +// type's keyed modes on backends::blake3, and bcrypt_verify wherever the backend has bcrypt +// (H12). backends::webcrypto has no coverage test (D6). + +#ifndef WEBCPP_TEST_HASH_SUPPORT_TIMING_COVERAGE_HPP +#define WEBCPP_TEST_HASH_SUPPORT_TIMING_COVERAGE_HPP + +#include "timing_seam.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "data_file.hpp" +#include "defaults.hpp" + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace webcpp::test { + +/** + * Runs `call` and reports an error when it entered no detail::timing_guard, when the first guard + * it entered is not the one of `function` (support/timing_seam.hpp), or when it left the thread's + * DIT other than it found it. + * + * @param name What the call is, `::[ how] on `, as an error names + * it. + * @param function The function whose guard the call must enter first, `::`, + * where the name cannot say it (a member of a class template, overloads). + * @param call The call, with its arguments bound. + */ +template +void covered(std::string const& name, std::string const& function, Call&& call) { + bool const before = webcpp::hash::detail::dit_is_set(); + require_enters(name, function, std::forward(call)); + if (webcpp::hash::detail::dit_is_set() != before) { + std::string const message = name + " left DIT other than it found it"; + BOOST_ERROR(message.c_str()); + } +} + +/** + * `covered`, for a call whose name begins with the function whose guard it must enter first, + * `::::`. + * + * @param name What the call is, `::[ how] on `, as an error names + * it. + * @param call The call, with its arguments bound. + */ +template +void covered(std::string const& name, Call&& call) { + covered(name, name, std::forward(call)); +} + +/** + * Runs `call` and reports an error when it entered a detail::timing_guard: a public function that + * computes on public data alone (a digest without a key, a Hash2 type) holds none (design D2, + * D3). A guard added to one by mistake costs every call, and makes the rule "a guard where a key + * is" harder to check. + * + * @param name What the call is, `::[ how] on `, as an error names + * it. + * @param call The call, with its arguments bound. + */ +template +void uncovered(std::string_view name, Call&& call) { + std::size_t const before = timing_entries; + std::forward(call)(); + if (timing_entries != before) { + std::string const message = + std::string(name) + " entered a detail::timing_guard it should not hold"; + BOOST_ERROR(message.c_str()); + } +} + +/** A backend's coverage calls, by the name of the keyed cell each covers. */ +using coverage_calls = std::map, std::less<>>; + +/** + * The capability table, doc/capabilities.json, read from the directory the define + * `WEBCPP_TEST_HASH_DOC` gives; a file that cannot be read or parsed ends the test, by name. + * + * @return The table. + */ +inline boost::json::value capability_table() { + std::string const path = WEBCPP_TEST_HASH_DOC "/capabilities.json"; + boost::system::error_code ec; + boost::json::value parsed = boost::json::parse(read_text(path), ec); + if (ec || !parsed.is_object()) { + std::cerr << "cannot parse " << path << ": " << ec.message() << '\n'; + std::abort(); + } + return parsed; +} + +/** + * A function's cell on `backend`, or null. + * + * @param function A function of the table, an element of an algorithm's "functions". + * @param backend The backend's name. + * @return The cell, or null where the function has none on the backend. + */ +inline boost::json::value const* cell_of(boost::json::value const& function, + std::string_view backend) { + auto const& backends = function.at("backends").as_object(); + return backends.if_contains(backend); +} + +/** + * Whether the table has a cell of the function or tag `row` on `backend`, in any chapter. + * + * @param table The capability table. + * @param row The function's name as the table spells it (`digests::blake2b`, `bcrypt`). + * @param backend The backend's name. + * @return Whether the cell exists. + */ +inline bool table_has_cell(boost::json::value const& table, std::string_view row, + std::string_view backend) { + for (auto const& algorithm : table.at("algorithms").as_array()) { + for (auto const& function : algorithm.at("functions").as_array()) { + if (function.at("name").as_string() == row && cell_of(function, backend) != nullptr) { + return true; + } + } + } + return false; +} + +/** The name of the keyed cell of BLAKE2b with a key, a keyed function of design D1. */ +inline constexpr std::string_view keyed_blake2b_cell = "digests::blake2b keyed"; +/** The name of the keyed cell of the blake3 type's keyed modes, a keyed function of design D1. */ +inline constexpr std::string_view keyed_blake3_cell = "blake3 keyed"; +/** The name of the keyed cell of bcrypt_verify, a keyed function of design D1 (ruling H12). */ +inline constexpr std::string_view bcrypt_verify_cell = "bcrypt_verify"; + +/** + * The keyed cells of `backend` (ruling H6), in the table's order, then the keyed functions this + * support names with design D1 as the reason. + * + * A cell is named as the table names its function: `` (`scrypt`), `<>` + * for each hmac the cell lists (`hkdf`, `hkdf`), `mac<>` for a tag of + * `mac` (`mac`), `<>` for a variant (`argon2`). + * The keyed functions: `digests::blake2b keyed` (digest_of and a hasher round with a key) + * wherever the table has a cell of digests::blake2b; `blake3 keyed` (the blake3 type's keyed + * modes) wherever it has the blake3 type; `bcrypt_verify` wherever it has bcrypt. + * + * @param backend The backend's name, as the table spells it. + * @return The names. + */ +inline std::vector keyed_cells(std::string_view backend) { + constexpr std::array keyed_chapters{"macs", "kdfs", "password_hashing"}; + auto const table = capability_table(); + std::vector cells; + for (auto const& algorithm_value : table.at("algorithms").as_array()) { + auto const& algorithm = algorithm_value.as_object(); + std::string_view const chapter = algorithm.at("chapter").as_string(); + if (std::ranges::find(keyed_chapters, chapter) == keyed_chapters.end()) { + continue; + } + for (auto const& function_value : algorithm.at("functions").as_array()) { + auto const& function = function_value.as_object(); + std::string_view const kind = function.at("kind").as_string(); + auto const* const cell = cell_of(function_value, backend); + if (kind == "type" || cell == nullptr) { + continue; + } + std::string const name(function.at("name").as_string()); + std::string base = name; + if (kind == "mac") { + base = "mac<" + name + ">"; + } else if (kind == "kdf") { + base = std::string(algorithm.at("name").as_string()) + "<" + name + ">"; + } + auto const& hmacs = cell->as_object().at("hmacs"); + if (hmacs.is_null()) { + cells.push_back(base); + continue; + } + for (auto const& hmac : hmacs.as_array()) { + cells.push_back(base + "<" + std::string(hmac.as_string()) + ">"); + } + } + } + if (table_has_cell(table, "digests::blake2b", backend)) { + cells.emplace_back(keyed_blake2b_cell); + } + if (table_has_cell(table, "blake3", backend)) { + cells.emplace_back(keyed_blake3_cell); + } + if (table_has_cell(table, "bcrypt", backend)) { + cells.emplace_back(bcrypt_verify_cell); + } + return cells; +} + +/** + * Reports each keyed cell of `backend` that `calls` does not cover and each call that names no + * keyed cell of it, then runs every call. + * + * @param backend The backend's name, as the table spells it. + * @param calls The backend's coverage calls. + */ +inline void check_and_run(std::string_view backend, coverage_calls const& calls) { + auto const cells = keyed_cells(backend); + BOOST_TEST(!cells.empty()); + for (auto const& cell : cells) { + if (!calls.contains(cell)) { + std::string const message = + cell + " on " + std::string(backend) + " is a keyed cell with no coverage call"; + BOOST_ERROR(message.c_str()); + } + } + for (auto const& [name, call] : calls) { + if (std::ranges::find(cells, name) == cells.end()) { + std::string const message = + name + " on " + std::string(backend) + " names no keyed cell"; + BOOST_ERROR(message.c_str()); + } + call(); + } +} + +/** + * The digest cells of `backend` (the functions of kind "digest"), in the table's order. + * + * @param backend The backend's name, as the table spells it. + * @return The names of the tags, as `digests::sha2_256`. + */ +inline std::vector digest_cells(std::string_view backend) { + auto const table = capability_table(); + std::vector cells; + for (auto const& algorithm : table.at("algorithms").as_array()) { + for (auto const& function_value : algorithm.at("functions").as_array()) { + auto const& function = function_value.as_object(); + if (function.at("kind").as_string() == "digest" && + cell_of(function_value, backend) != nullptr) { + cells.emplace_back(function.at("name").as_string()); + } + } + } + return cells; +} + +/** Every tag of `digests`, which the dispatch from a digest cell's name to its call reads. */ +using coverage_digest_tags = + std::tuple; +/** The names of `coverage_digest_tags`, in its order, as the table spells them. */ +inline constexpr std::array coverage_digest_names{ + "digests::md5", + "digests::sha1", + "digests::sha2_224", + "digests::sha2_256", + "digests::sha2_384", + "digests::sha2_512", + "digests::sha2_512_224", + "digests::sha2_512_256", + "digests::sha3_224", + "digests::sha3_256", + "digests::sha3_384", + "digests::sha3_512", + "digests::shake_128", + "digests::shake_256", + "digests::keccak_224", + "digests::keccak_256", + "digests::keccak_384", + "digests::keccak_512", + "digests::cshake_128", + "digests::cshake_256", + "digests::kt128", + "digests::kt256", + "digests::turboshake_128", + "digests::turboshake_256", + "digests::tuplehash_128", + "digests::tuplehash_256", + "digests::parallelhash_128", + "digests::parallelhash_256", + "digests::blake2b", + "digests::blake2s_256", + "digests::blake3", + "digests::ripemd_160", + "digests::md5_sha1", + "digests::sm3", + "digests::streebog_256", + "digests::streebog_512", + "digests::whirlpool", + "digests::skein_512", +}; + +/** Every tag of `mac`, which add_keyed_calls walks. */ +using coverage_mac_tags = std::tuple< + hash::macs::hmac, hash::macs::hmac, + hash::macs::hmac, hash::macs::hmac, + hash::macs::hmac, hash::macs::hmac, + hash::macs::hmac, hash::macs::hmac, + hash::macs::hmac, hash::macs::hmac, + hash::macs::hmac, hash::macs::hmac, + hash::macs::hmac, hash::macs::hmac, + hash::macs::hmac, hash::macs::hmac, + hash::macs::hmac, hash::macs::hmac, + hash::macs::hmac, hash::macs::hmac, + hash::macs::hmac, hash::macs::hmac, + hash::macs::hmac, hash::macs::hmac, + hash::macs::hmac, hash::macs::kmac_128, hash::macs::kmac_256, + hash::macs::siphash_2_4, hash::macs::siphash_2_4x, hash::macs::blake2b_mac, + hash::macs::blake2s_mac>; +/** The names of `coverage_mac_tags`, in its order, as the table spells them. */ +inline constexpr std::array coverage_mac_names{ + "macs::hmac", + "macs::hmac", + "macs::hmac", + "macs::hmac", + "macs::hmac", + "macs::hmac", + "macs::hmac", + "macs::hmac", + "macs::hmac", + "macs::hmac", + "macs::hmac", + "macs::hmac", + "macs::hmac", + "macs::hmac", + "macs::hmac", + "macs::hmac", + "macs::hmac", + "macs::hmac", + "macs::hmac", + "macs::hmac", + "macs::hmac", + "macs::hmac", + "macs::hmac", + "macs::hmac", + "macs::hmac", + "macs::kmac_128", + "macs::kmac_256", + "macs::siphash_2_4", + "macs::siphash_2_4x", + "macs::blake2b_mac", + "macs::blake2s_mac", +}; + +/** The variants of `argon2`, which add_keyed_calls walks. */ +using coverage_argon2_tags = + std::tuple; +/** The names of `coverage_argon2_tags`, in its order, as the table spells them. */ +inline constexpr std::array coverage_argon2_names{ + "kdfs::argon2d", + "kdfs::argon2i", + "kdfs::argon2id", +}; + +/** + * Calls `each.template operator()(name)` for each tag of `Tags`, with its name. + * + * @tparam Tags A tuple of tags. + * @param names The tags' names, in the tuple's order. + * @param each The visitor. + */ +template +void for_each_coverage_tag(std::array const& names, Each&& each) { + static_assert(std::tuple_size_v == Size); + [&](std::index_sequence) { + (each.template operator()>(names[Index]), ...); + }(std::make_index_sequence{}); +} + +/** Whether the program has `Tag` on `Backend` (over `Key`, as backend_has_v reads it) and links it. + */ +template +inline constexpr bool coverage_has_v = + hash::backend_has_v && hash::detail::linked_v; + +/** A key of 32 bytes whose bytes differ from one another. */ +inline constexpr std::array coverage_key = [] { + std::array bytes{}; + for (std::size_t i = 0; i < bytes.size(); ++i) { + bytes[i] = static_cast((i * 29) + 3); + } + return bytes; +}(); +/** A salt of 16 bytes, the size every key derivation and password hash takes. */ +inline constexpr std::array coverage_salt = [] { + std::array bytes{}; + for (std::size_t i = 0; i < bytes.size(); ++i) { + bytes[i] = static_cast(bytes.size() - i); + } + return bytes; +}(); +/** The data, or the info of a key derivation. */ +inline constexpr std::array coverage_input{9, 8, 7, 6, 5, 4, 3, 2, 1}; + +/** ` on `, which ends each check's name. */ +template +std::string coverage_on() { + return " on " + std::string(name_of()); +} + +/** ` over on `, which ends the name of each check of a function over `Hmac`. */ +template +std::string coverage_over() { + return " over " + std::string(name_of_hmac()) + coverage_on(); +} + +/** + * `mac` of `Mac` on `Backend`: a tag of the longest size (at most 64 bytes) under the shortest + * key the backend takes, then a tag of no byte, which the guards refuse before the backend. + * + * @param tag The tag's name, as the table spells it. + */ +template +void cover_mac(std::string_view tag) { + using traits = hash::detail::mac_traits; + using engine = hash::detail::mac_engine; + std::string const on = " of " + std::string(tag) + coverage_on(); + std::vector output(std::min(traits::max_output, std::uint64_t{64})); + auto key_size = static_cast(traits::min_key); + while (!engine::accepts(hash::mac_options{}, key_size, output.size()) && key_size < 64) { + ++key_size; + } + std::vector const key(key_size, 0x0b); + covered("hash::mac" + on, [&] { + BOOST_TEST((hash::mac(output, key, coverage_input)).has_value()); + }); + covered("hash::mac with a tag of no byte" + on, [&] { + BOOST_TEST( + (hash::mac(std::span{}, key, coverage_input)).error() == + hash::error::invalid_output_size); + }); +} + +/** + * `hkdf_extract` over `Hmac` on `Backend`. No call of it is refused before the backend but one + * past a backend's own limits, which no backend has small enough to reach here. + */ +template +void cover_hkdf_extract() { + std::string const on = coverage_over(); + covered("hash::hkdf_extract" + on, [&] { + BOOST_TEST((hash::hkdf_extract(coverage_salt, coverage_key)).has_value()); + }); +} + +/** + * `hkdf_expand` over `Hmac` on `Backend`, then with a pseudorandom key of the wrong size. + */ +template +void cover_hkdf_expand() { + std::string const on = coverage_over(); + std::vector const prk(typename Hmac::result_type().size(), 0x0b); + std::array output{}; + covered("hash::hkdf_expand" + on, [&] { + BOOST_TEST((hash::hkdf_expand(output, prk, coverage_input)).has_value()); + }); + covered("hash::hkdf_expand with a prk of the wrong size" + on, [&] { + BOOST_TEST((hash::hkdf_expand(output, std::span(prk).first(prk.size() - 1), + coverage_input)) + .error() == hash::error::invalid_key_size); + }); +} + +/** + * `hkdf` over `Hmac` on `Backend`, then with an output of no byte. + */ +template +void cover_hkdf() { + std::string const on = coverage_over(); + std::array output{}; + covered("hash::hkdf" + on, [&] { + BOOST_TEST((hash::hkdf(output, coverage_salt, coverage_key, coverage_input)) + .has_value()); + }); + covered("hash::hkdf with an output of no byte" + on, [&] { + BOOST_TEST((hash::hkdf(std::span{}, coverage_salt, + coverage_key, coverage_input)) + .error() == hash::error::invalid_output_size); + }); +} + +/** + * `pbkdf2` over `Hmac` on `Backend`, of one iteration, then of none. + */ +template +void cover_pbkdf2() { + std::string const on = coverage_over(); + std::array output{}; + covered("hash::pbkdf2 of 1 iteration" + on, [&] { + BOOST_TEST( + (hash::pbkdf2(output, coverage_key, coverage_salt, 1)).has_value()); + }); + covered("hash::pbkdf2 of 0 iterations" + on, [&] { + BOOST_TEST( + !(hash::pbkdf2(output, coverage_key, coverage_salt, 0)).has_value()); + }); +} + +/** + * `kbkdf` over `Hmac` on `Backend`, then with a counter of 7 bits. + */ +template +void cover_kbkdf() { + std::string const on = coverage_over(); + std::array output{}; + covered("hash::kbkdf" + on, [&] { + BOOST_TEST((hash::kbkdf(output, coverage_key, + {.label = coverage_input, .context = coverage_salt})) + .has_value()); + }); + covered("hash::kbkdf with a counter of 7 bits" + on, [&] { + BOOST_TEST( + !(hash::kbkdf(output, coverage_key, {.counter_bits = 7})).has_value()); + }); +} + +/** + * The calls of the functions over an hmac that `Backend` has over `Hmac`: hkdf_extract, + * hkdf_expand, hkdf, pbkdf2 and kbkdf, each by the name of its cell. + * + * @param calls Where the calls go. + */ +template +void add_hmac_calls(coverage_calls& calls) { + namespace kdfs = hash::kdfs; + std::string const column = "<" + std::string(name_of_hmac()) + ">"; + if constexpr (coverage_has_v) { + calls.emplace("hkdf_extract" + column, [] { cover_hkdf_extract(); }); + } + if constexpr (coverage_has_v) { + calls.emplace("hkdf_expand" + column, [] { cover_hkdf_expand(); }); + } + if constexpr (coverage_has_v) { + calls.emplace("hkdf" + column, [] { cover_hkdf(); }); + } + if constexpr (coverage_has_v) { + calls.emplace("pbkdf2" + column, [] { cover_pbkdf2(); }); + } + if constexpr (coverage_has_v) { + calls.emplace("kbkdf" + column, [] { cover_kbkdf(); }); + } +} + +/** `sskdf` over SHA-256 on `Backend`, then with an output of no byte. */ +template +void cover_sskdf() { + std::string const on = " of sha2_256" + coverage_on(); + std::array output{}; + covered("hash::sskdf" + on, [&] { + BOOST_TEST( + (hash::sskdf(output, coverage_key, coverage_input)) + .has_value()); + }); + covered("hash::sskdf with an output of no byte" + on, [&] { + BOOST_TEST(!(hash::sskdf(std::span{}, + coverage_key, coverage_input)) + .has_value()); + }); +} + +/** `x963kdf` over SHA-256 on `Backend`, then with an output of no byte. */ +template +void cover_x963kdf() { + std::string const on = " of sha2_256" + coverage_on(); + std::array output{}; + covered("hash::x963kdf" + on, [&] { + BOOST_TEST( + (hash::x963kdf(output, coverage_key, coverage_input)) + .has_value()); + }); + covered("hash::x963kdf with an output of no byte" + on, [&] { + BOOST_TEST(!(hash::x963kdf(std::span{}, + coverage_key, coverage_input)) + .has_value()); + }); +} + +/** `blake2b_subkey` on `Backend`, then with an output shorter than the shortest subkey. */ +template +void cover_blake2b_subkey() { + std::string const on = coverage_on(); + std::array const context{'c', 't', 'x', '_', 't', 'e', 's', 't'}; + std::array output{}; + covered("hash::blake2b_subkey" + on, [&] { + BOOST_TEST((hash::blake2b_subkey(output, coverage_key, 7, context)).has_value()); + }); + std::array tiny{}; + covered("hash::blake2b_subkey with an output too small" + on, [&] { + BOOST_TEST(!(hash::blake2b_subkey(tiny, coverage_key, 7, context)).has_value()); + }); +} + +/** `argon2id` on `Backend`, of its least parameters, then with a salt of 4 bytes. */ +template +void cover_argon2id() { + std::string const on = coverage_on(); + hash::argon2id_parameters const cheapest{.passes = 1, .memory = 8192}; + std::array output{}; + covered("hash::argon2id" + on, [&] { + BOOST_TEST( + (hash::argon2id(output, coverage_key, coverage_salt, cheapest)).has_value()); + }); + covered("hash::argon2id with a salt of 4 bytes" + on, [&] { + BOOST_TEST(!(hash::argon2id(output, coverage_key, + std::span(coverage_salt).first(4), cheapest)) + .has_value()); + }); +} + +/** + * `argon2` of `Variant` on `Backend`, of three passes over 8 KiB, then with a salt of 4 bytes. + * + * @param variant The variant's name, as the table spells it. + */ +template +void cover_argon2(std::string_view variant) { + std::string const on = " of " + std::string(variant) + coverage_on(); + hash::argon2_parameters const family{.passes = 3, .memory_kib = 8}; + std::array output{}; + covered("hash::argon2" + on, [&] { + BOOST_TEST((hash::argon2(output, coverage_key, coverage_salt, family)) + .has_value()); + }); + covered("hash::argon2 with a salt of 4 bytes" + on, [&] { + BOOST_TEST(!(hash::argon2(output, coverage_key, + std::span(coverage_salt).first(4), family)) + .has_value()); + }); +} + +/** `scrypt` on `Backend`, of N = 16, then of N = 1, which is no power of two above 1. */ +template +void cover_scrypt() { + std::string const on = coverage_on(); + std::array output{}; + covered("hash::scrypt of N = 16" + on, [&] { + BOOST_TEST( + (hash::scrypt(output, coverage_key, coverage_salt, {.n = 16, .r = 1, .p = 1})) + .has_value()); + }); + covered("hash::scrypt of N = 1" + on, [&] { + BOOST_TEST( + !(hash::scrypt(output, coverage_key, coverage_salt, {.n = 1, .r = 1, .p = 1})) + .has_value()); + }); +} + +/** `bcrypt` on `Backend`, of cost 4, then with a salt of 8 bytes. */ +template +void cover_bcrypt() { + std::string const on = coverage_on(); + std::array output{}; + covered("hash::bcrypt of cost 4" + on, [&] { + BOOST_TEST( + (hash::bcrypt(output, coverage_key, coverage_salt, {.cost = 4})).has_value()); + }); + covered("hash::bcrypt with a salt of 8 bytes" + on, [&] { + BOOST_TEST(!(hash::bcrypt(output, coverage_key, std::span(coverage_salt).first(8), + {.cost = 4})) + .has_value()); + }); +} + +/** + * `bcrypt_verify` on `Backend` (ruling H12): of the right password, of a wrong one, and of a + * string of the wrong form, which the guards refuse before the backend. + */ +template +void cover_bcrypt_verify() { + std::string const on = coverage_on(); + std::array made{}; + if (!BOOST_TEST( + (hash::bcrypt(made, coverage_key, coverage_salt, {.cost = 4})).has_value())) { + return; + } + std::string_view const text{made.data(), made.size()}; + covered("hash::bcrypt_verify of the right password" + on, [&] { + auto const checked = hash::bcrypt_verify(coverage_key, text); + BOOST_TEST(checked.has_value() && *checked); + }); + covered("hash::bcrypt_verify of a wrong password" + on, [&] { + auto const checked = hash::bcrypt_verify(coverage_salt, text); + BOOST_TEST(checked.has_value() && !*checked); + }); + covered("hash::bcrypt_verify of a string of the wrong form" + on, [&] { + BOOST_TEST(!hash::bcrypt_verify(coverage_key, "not a bcrypt string").has_value()); + }); +} + +/** `bcrypt_pbkdf` on `Backend`, of one round, then of none. */ +template +void cover_bcrypt_pbkdf() { + std::string const on = coverage_on(); + std::array output{}; + covered("hash::bcrypt_pbkdf of 1 round" + on, [&] { + BOOST_TEST( + (hash::bcrypt_pbkdf(output, coverage_key, coverage_salt, 1)).has_value()); + }); + covered("hash::bcrypt_pbkdf of 0 rounds" + on, [&] { + BOOST_TEST( + !(hash::bcrypt_pbkdf(output, coverage_key, coverage_salt, 0)).has_value()); + }); +} + +/** + * A hasher round of BLAKE2b with a key on `Backend`: `make`, `update` and `finish`, each entering + * its own guard; on a backend whose cell refuses a key, `make` answers `unsupported_by_backend`. + * + * @param on ` of blake2b with a key on `, which ends each name. + * @param keyed The options, with the key. + * @param takes_key Whether the backend takes a key. + * @return The round's digest, or none when the backend refuses the key or the round failed. + */ +template +std::optional> cover_keyed_blake2b_round( + std::string const& on, hash::digest_options const& keyed, + bool takes_key) { + using hash::digests::blake2b; + std::optional> hashing; + covered("hash::hasher::make" + on, [&] { + auto made = hash::hasher::make(keyed); + if (!takes_key) { + BOOST_TEST(made.error() == hash::error::unsupported_by_backend); + } else if (BOOST_TEST(made.has_value())) { + hashing.emplace(std::move(*made)); + } + }); + if (!hashing) { + return std::nullopt; + } + covered("hash::hasher::update" + on, + [&] { BOOST_TEST(hashing->update(coverage_input).has_value()); }); + std::array pieces{}; + bool finished = false; + covered("hash::hasher::finish" + on, + [&] { finished = BOOST_TEST(hashing->finish(pieces).has_value()); }); + return finished ? std::optional(pieces) : std::nullopt; +} + +/** + * BLAKE2b with a key on `Backend` (design D1): `digest_of`, then a hasher round, `make`, `update` + * and `finish`, the round's digest the one of `digest_of`; on a backend whose cell refuses a key + * (its "partial": `backends::hash2`, `backends::openssl`), `digest_of` and `make` answer + * `unsupported_by_backend` and still enter the guard, which precedes every check. Then + * `digest_of` and `make` with a key of 65 bytes, which the guards refuse before the backend. + */ +template +void cover_keyed_blake2b() { + using hash::digests::blake2b; + std::string const on = " of blake2b with a key" + coverage_on(); + hash::digest_options const keyed{.key = coverage_key}; + bool const takes_key = hash::detail::digest_engine::accepts(keyed); + std::array once{}; + covered("hash::digest_of" + on, [&] { + auto const done = hash::digest_of(once, coverage_input, keyed); + BOOST_TEST(takes_key ? done.has_value() + : done.error() == hash::error::unsupported_by_backend); + }); + auto const pieces = cover_keyed_blake2b_round(on, keyed, takes_key); + BOOST_TEST(pieces.has_value() == takes_key); + if (pieces) { + BOOST_TEST(*pieces == once); + } + std::array const long_key{}; + hash::digest_options const too_long{.key = long_key}; + covered("hash::digest_of with a key of 65 bytes" + on, [&] { + BOOST_TEST((hash::digest_of(once, coverage_input, too_long)).error() == + hash::error::invalid_key_size); + }); + covered("hash::hasher::make with a key of 65 bytes" + on, [&] { + BOOST_TEST((hash::hasher::make(too_long)).error() == + hash::error::invalid_key_size); + }); +} + +/** + * The calls of every keyed cell this support knows that `Backend` has, each by the name of its + * cell (keyed_cells): mac over each tag, the functions over each hmac of the table's columns, + * those over none, argon2's variants, and the keyed functions of design D1 but the blake3 type's, + * which its backend's test adds. A cell the backend has and this support does not know stays + * without a call, which check_and_run reports. + * + * @return The calls. + */ +template +coverage_calls keyed_calls() { + namespace kdfs = hash::kdfs; + coverage_calls calls; + for_each_coverage_tag(coverage_mac_names, [&calls]( + std::string_view tag) { + if constexpr (coverage_has_v) { + calls.emplace("mac<" + std::string(tag) + ">", [tag] { cover_mac(tag); }); + } + }); + [&calls](std::tuple*) { + (add_hmac_calls(calls), ...); + }(static_cast(nullptr)); + if constexpr (coverage_has_v) { + calls.emplace("blake2b_subkey", [] { cover_blake2b_subkey(); }); + } + if constexpr (coverage_has_v) { + calls.emplace("sskdf", [] { cover_sskdf(); }); + } + if constexpr (coverage_has_v) { + calls.emplace("x963kdf", [] { cover_x963kdf(); }); + } + if constexpr (coverage_has_v) { + calls.emplace("argon2id", [] { cover_argon2id(); }); + } + for_each_coverage_tag( + coverage_argon2_names, [&calls](std::string_view variant) { + if constexpr (coverage_has_v) { + calls.emplace("argon2<" + std::string(variant) + ">", + [variant] { cover_argon2(variant); }); + } + }); + if constexpr (coverage_has_v) { + calls.emplace("scrypt", [] { cover_scrypt(); }); + } + if constexpr (coverage_has_v) { + calls.emplace("bcrypt", [] { cover_bcrypt(); }); + calls.emplace(bcrypt_verify_cell, [] { cover_bcrypt_verify(); }); + } + if constexpr (coverage_has_v) { + calls.emplace("bcrypt_pbkdf", [] { cover_bcrypt_pbkdf(); }); + } + if constexpr (coverage_has_v) { + calls.emplace(keyed_blake2b_cell, [] { cover_keyed_blake2b(); }); + } + return calls; +} + +/** + * `Digest` on `Backend` without a key: `digest_of`, then a hasher round, `make`, `update` and + * `finish`, none of which may enter a guard; each succeeds, over an output of the digest's size, + * or of 64 bytes (at most the backend's longest) for a function whose output may be longer. + * + * @param tag The tag's name, as the table spells it. + */ +template +void uncover_digest(std::string_view tag) { + using traits = hash::detail::digest_traits; + std::string const on = " of " + std::string(tag) + coverage_on(); + // The default options, but for ParallelHash's block size, which has no default. + auto const options = [] { + hash::digest_options chosen{}; + if constexpr (requires { chosen.block_size; }) { + chosen.block_size = 8; + } + return chosen; + }(); + std::vector output(std::min({ + traits::max_output(options), + hash::detail::digest_engine::max_output, + std::uint64_t{64}, + })); + uncovered("hash::digest_of" + on, [&] { + BOOST_TEST((hash::digest_of(output, coverage_input, options)).has_value()); + }); + std::optional> hashing; + uncovered("hash::hasher::make" + on, [&] { + auto made = hash::hasher::make(options); + if (BOOST_TEST(made.has_value())) { + hashing.emplace(std::move(*made)); + } + }); + if (!hashing) { + return; + } + uncovered("hash::hasher::update" + on, + [&] { BOOST_TEST(hashing->update(coverage_input).has_value()); }); + uncovered("hash::hasher::finish" + on, + [&] { BOOST_TEST(hashing->finish(output).has_value()); }); +} + +/** + * The unkeyed boundary of `Backend`: every digest cell of the backend in the table, called + * without a key through `digest_of` and a hasher round (uncover_digest), none of which may enter + * a guard. Reports a digest cell this support cannot call, and a digest the backend has that the + * table does not list. + */ +template +void uncover_digests() { + std::string const backend(name_of()); + std::map, std::less<>> calls; + for_each_coverage_tag( + coverage_digest_names, [&calls](std::string_view tag) { + if constexpr (coverage_has_v) { + calls.emplace(tag, [tag] { uncover_digest(tag); }); + } + }); + auto const cells = digest_cells(backend); + BOOST_TEST(!cells.empty()); + for (auto const& cell : cells) { + auto const found = calls.find(cell); + if (found == calls.end()) { + std::string message = cell; + message += " on "; + message += backend; + message += " is a digest cell with no unkeyed call"; + BOOST_ERROR(message.c_str()); + continue; + } + found->second(); + } + for (auto const& [name, call] : calls) { + if (std::ranges::find(cells, name) == cells.end()) { + std::string message = name; + message += " on "; + message += backend; + message += " names no digest cell"; + BOOST_ERROR(message.c_str()); + } + } +} + +/** + * The type cells of `backend` (the Boost.Hash2-form types of kind "type", design D3), in the + * table's order. + * + * @param backend The backend's name, as the table spells it. + * @return The names of the types, as `sha2_256` or `hmac`. + */ +inline std::vector type_cells(std::string_view backend) { + auto const table = capability_table(); + std::vector cells; + for (auto const& algorithm : table.at("algorithms").as_array()) { + for (auto const& function_value : algorithm.at("functions").as_array()) { + auto const& function = function_value.as_object(); + if (function.at("kind").as_string() == "type" && + cell_of(function_value, backend) != nullptr) { + cells.emplace_back(function.at("name").as_string()); + } + } + } + return cells; +} + +/** + * A Boost.Hash2-form type `H` (design D3), which holds no guard however it is seeded: made by its + * default constructor, fed and read, and, where `seeded`, made from a seed of bytes (HMAC's key) + * and from an integer seed, fed and read; no step may enter a guard. + * + * @param name The type's name, as the table spells it, and its backend: ` on `. + * @param seeded Whether to make it from seeds too (not the blake3 type, whose seeds key it). + */ +template +void uncover_type(std::string const& name, bool seeded) { + uncovered(name + ", made, fed and read", [] { + H plain; + plain.update(coverage_input.data(), coverage_input.size()); + static_cast(plain.result()); + }); + if (!seeded) { + return; + } + uncovered(name + ", seeded with bytes, fed and read", [] { + H keyed(coverage_key.data(), coverage_key.size()); + keyed.update(coverage_input.data(), coverage_input.size()); + static_cast(keyed.result()); + }); + uncovered(name + ", seeded with an integer, fed and read", [] { + H keyed(std::uint64_t{7}); + keyed.update(coverage_input.data(), coverage_input.size()); + static_cast(keyed.result()); + }); +} + +/** + * Runs each of `calls`, a backend's unguarded types by name, after reporting each type cell of + * `backend` without a call and each call that names no type cell of it. + * + * @param backend The backend's name, as the table spells it. + * @param calls The calls, by the type's name. + */ +inline void uncover_types(std::string_view backend, coverage_calls const& calls) { + auto const cells = type_cells(backend); + for (auto const& cell : cells) { + if (!calls.contains(cell)) { + std::string const message = + cell + " on " + std::string(backend) + " is a type cell with no unkeyed call"; + BOOST_ERROR(message.c_str()); + } + } + for (auto const& [name, call] : calls) { + if (std::ranges::find(cells, name) == cells.end()) { + std::string const message = + name + " on " + std::string(backend) + " names no type cell"; + BOOST_ERROR(message.c_str()); + } + call(); + } +} + +} // namespace webcpp::test + +#endif // WEBCPP_TEST_HASH_SUPPORT_TIMING_COVERAGE_HPP diff --git a/test/support/timing_seam.hpp b/test/support/timing_seam.hpp index c592f42..9742aed 100644 --- a/test/support/timing_seam.hpp +++ b/test/support/timing_seam.hpp @@ -9,8 +9,8 @@ // function that holds it, on every target, also where DIT does not apply. require_enters then // checks that a call entered a guard, and that the first, the outermost since a guard is its // function's first statement, is the one of the function the check names: a public function that -// forgot its own guard fails, also when it calls another guarded function. uncovered checks the -// converse: a function that calls no backend's code enters no guard. +// forgot its own guard fails, also when it calls another guarded function. The converse, a call +// that enters no guard, is support/timing_coverage.hpp's uncovered. // // This is a copy of libs/crypto/test/support/timing_seam.hpp with hash's macro: the duplication is // accepted for the reason of detail/timing.hpp's own (hash includes nothing of crypto). @@ -283,26 +283,6 @@ void require_enters(std::string_view name, Call&& call) { require_enters(name, name, std::forward(call)); } -/** - * Runs `call` and reports an error when it entered a detail::timing_guard: a public function that - * calls no backend's code holds none (the data-independent-timing change of hash). A guard - * added to one by mistake costs every call, and makes the rule "a guard where the backend runs" - * harder to check. - * - * @param name What the call is, `:: on `, as an error names it. - * @param call The call, with its arguments bound. - */ -template -void uncovered(std::string_view name, Call&& call) { - std::size_t const before = timing_entries; - std::forward(call)(); - if (timing_entries != before) { - std::string const message = - std::string(name) + " entered a detail::timing_guard it should not hold"; - BOOST_ERROR(message.c_str()); - } -} - } // namespace webcpp::test #endif // WEBCPP_TEST_HASH_SUPPORT_TIMING_SEAM_HPP diff --git a/test/timing_coverage_bearssl_test.cpp b/test/timing_coverage_bearssl_test.cpp new file mode 100644 index 0000000..33a78f7 --- /dev/null +++ b/test/timing_coverage_bearssl_test.cpp @@ -0,0 +1,31 @@ +// 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 keyed cell of backends::bearssl enters its own detail::timing_guard first and leaves the +// thread's DIT as it found it, on every target of the backend, also where DIT does not apply, +// each with valid input and with input refused before the backend; every digest cell, called +// without a key, enters none (support/timing_coverage.hpp). +// +// What it covers, by family; the list is doc/capabilities.json's, read at run time, and a cell +// the table gains fails here until the support has its call: +// - mac over hmac for MD5, SHA-1, SHA-224, SHA-256, SHA-384 and SHA-512. +// - hkdf over the six hmacs of those digests. +// - Not guarded: each digest cell, through digest_of and a hasher round. + +#include "support/timing_coverage.hpp" + +#include +#include + +#include + +int main() { + namespace test = webcpp::test; + using webcpp::hash::backends::bearssl; + test::check_and_run("bearssl", test::keyed_calls()); + test::uncover_digests(); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/timing_coverage_blake3_test.cpp b/test/timing_coverage_blake3_test.cpp new file mode 100644 index 0000000..b3b9d62 --- /dev/null +++ b/test/timing_coverage_blake3_test.cpp @@ -0,0 +1,120 @@ +// 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 keyed modes of the blake3 type, the one keyed function of backends::blake3, enter their own +// detail::timing_guard first and leave the thread's DIT as it found it, on every target, also +// where DIT does not apply; its digest cell, called through digest_of and a hasher round, and the +// blake3 type in its plain mode enter none (support/timing_coverage.hpp). +// +// What it covers, by family; the list is doc/capabilities.json's, read at run time, and a cell +// the table gains fails here until the support has its call: +// - The blake3 type keyed (design D1), which the table holds no keyed cell of: keyed and +// derive_key, and the seeds that key (a non-zero integer, bytes), then update (both +// overloads), result, squeeze and reset of a keyed object (ruling H4, H5). +// - Not guarded: digests::blake3, through digest_of and a hasher round; the blake3 type made by +// its default constructor, fed, read, squeezed and reset (design D2, D3). + +#include "support/timing_coverage.hpp" + +#include +#include +#include + +#include + +#include +#include +#include +#include +#include + +namespace { + +namespace test = webcpp::test; +using webcpp::hash::blake3; + +// The member functions of a keyed object, each entering its own guard first; `what` says how the +// object was keyed. +void cover_keyed_members(blake3& keyed, std::string const& what) { + auto const& bytes = test::coverage_input; + test::covered("blake3::update(void const*) of " + what, + [&] { keyed.update(static_cast(bytes.data()), bytes.size()); }); + test::covered("blake3::update(unsigned char const*) of " + what, [&] { + keyed.update(static_cast(bytes.data()), bytes.size()); + }); + test::covered("blake3::result of " + what, [&] { BOOST_TEST(keyed.result().size() == 32); }); + test::covered("blake3::squeeze of " + what, [&] { + std::array out{}; + keyed.squeeze(out, 3); + }); + test::covered("blake3::reset of " + what, [&] { keyed.reset(); }); +} + +// The keyed modes: each factory and each seed that keys, then the members of the object each +// leaves. +void cover_keyed_blake3() { + auto const& bytes = test::coverage_input; + std::optional keyed; + test::covered("blake3::keyed on blake3", + [&] { keyed.emplace(blake3::keyed(test::coverage_key)); }); + if (keyed) { + cover_keyed_members(*keyed, "a keyed object on blake3"); + } + std::optional derived; + test::covered("blake3::derive_key on blake3", + [&] { derived.emplace(blake3::derive_key("webcpp coverage")); }); + if (derived) { + cover_keyed_members(*derived, "a derived object on blake3"); + } + std::optional seeded; + test::covered("blake3::blake3 of a non-zero integer seed on blake3", + [&] { seeded.emplace(std::uint64_t{7}); }); + if (seeded) { + cover_keyed_members(*seeded, "an object of an integer seed on blake3"); + } + std::optional of_bytes; + test::covered("blake3::blake3(unsigned char const*) of a seed of bytes on blake3", [&] { + of_bytes.emplace(static_cast(bytes.data()), bytes.size()); + }); + // The delegating constructor of void const* holds none: the one it delegates to runs first. + test::covered( + "blake3::blake3(unsigned char const*) of a seed of bytes, through void const*, on blake3", + [&] { blake3 const through{static_cast(bytes.data()), bytes.size()}; }); + if (of_bytes) { + cover_keyed_members(*of_bytes, "an object of a seed of bytes on blake3"); + } +} + +// The plain mode, on public data: no step enters a guard. +void uncover_plain_blake3() { + auto const& bytes = test::coverage_input; + test::uncover_type("blake3 on blake3", false); + blake3 plain; + test::uncovered("blake3::squeeze of a plain object on blake3", [&] { + std::array out{}; + plain.squeeze(out, 3); + }); + test::uncovered("blake3::reset of a plain object on blake3", [&] { plain.reset(); }); + test::uncovered("blake3::blake3 of a zero integer seed on blake3", + [&] { blake3 const zero{std::uint64_t{0}}; }); + test::uncovered("blake3::blake3 of a seed of no bytes on blake3", [&] { + blake3 const empty{static_cast(bytes.data()), std::size_t{0}}; + }); +} + +} // namespace + +int main() { + using webcpp::hash::backends::blake3; + auto calls = test::keyed_calls(); + calls.emplace(test::keyed_blake3_cell, cover_keyed_blake3); + test::check_and_run("blake3", calls); + test::uncover_digests(); + test::coverage_calls types; + types.emplace("blake3", uncover_plain_blake3); + test::uncover_types("blake3", types); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/timing_coverage_botan_test.cpp b/test/timing_coverage_botan_test.cpp new file mode 100644 index 0000000..2a99a9b --- /dev/null +++ b/test/timing_coverage_botan_test.cpp @@ -0,0 +1,38 @@ +// 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 keyed cell of backends::botan enters its own detail::timing_guard first and leaves the +// thread's DIT as it found it, on every target of the backend, also where DIT does not apply, +// each with valid input and with input refused before the backend; every digest cell, called +// without a key, enters none (support/timing_coverage.hpp). +// +// What it covers, by family; the list is doc/capabilities.json's, read at run time, and a cell +// the table gains fails here until the support has its call: +// - mac over siphash_2_4, kmac_128, kmac_256, blake2b_mac and hmac for the 23 digests of +// the backend's cells. +// - hkdf_extract, hkdf_expand, hkdf, pbkdf2 and kbkdf over each of the 14 hmacs the cells list; +// sskdf and x963kdf. +// - argon2id; argon2 of argon2d, argon2i and argon2id; scrypt; bcrypt and bcrypt_pbkdf. +// - bcrypt_verify (ruling H12) and BLAKE2b with a key, digest_of and a hasher round (design D1), +// which the table holds no cell of. +// - Not guarded: each digest cell without a key, through digest_of and a hasher round. +// Botan reports its errors by throwing: the test runs with exceptions on, natively and on +// Emscripten, Botan's targets. + +#include "support/timing_coverage.hpp" + +#include +#include + +#include + +int main() { + namespace test = webcpp::test; + using webcpp::hash::backends::botan; + test::check_and_run("botan", test::keyed_calls()); + test::uncover_digests(); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/timing_coverage_hash2_test.cpp b/test/timing_coverage_hash2_test.cpp new file mode 100644 index 0000000..c58432c --- /dev/null +++ b/test/timing_coverage_hash2_test.cpp @@ -0,0 +1,92 @@ +// 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 keyed cell of backends::hash2 enters its own detail::timing_guard first and leaves the +// thread's DIT as it found it, on every target, also where DIT does not apply, each with valid +// input and with input refused before the backend; every digest cell, called without a key, +// enters none; and so does every Boost.Hash2-form type of hmac.hpp and algorithms.hpp, seeded or +// not (design D3) (support/timing_coverage.hpp). +// +// What it covers, by family; the list is doc/capabilities.json's, read at run time, and a cell +// the table gains fails here until the support has its call: +// - mac over siphash_2_4, blake2s_mac and hmac for each digest of the backend's cells. +// - hkdf_extract, hkdf_expand, hkdf and pbkdf2 over each hmac of hmac.hpp and over another Hash2 +// hmac (the column "other"). +// - BLAKE2b with a key: digest_of and a hasher round (design D1). +// - Not guarded: each digest cell without a key, through digest_of and a hasher round; the Hash2 +// types (md5_128 to spooky2_128, siphash_32 and siphash_64, hmac and its aliases). + +#include "support/timing_coverage.hpp" + +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include + +namespace { + +namespace hash = webcpp::hash; +namespace test = webcpp::test; + +// The type rows of the table on hash2: algorithms.hpp's, then hmac.hpp's, hmac over another Hash2 +// hash for "hmac" itself. +using hash2_types = std::tuple< + hash::md5_128, hash::sha1_160, hash::sha2_224, hash::sha2_256, hash::sha2_384, hash::sha2_512, + hash::sha2_512_224, hash::sha2_512_256, hash::sha3_224, hash::sha3_256, hash::sha3_384, + hash::sha3_512, hash::shake_128, hash::shake_256, hash::blake2b_512, hash::blake2s_256, + hash::ripemd_128, hash::ripemd_160, hash::siphash_32, hash::siphash_64, + hash::hmac, hash::hmac_md5_128, hash::hmac_sha1_160, hash::hmac_sha2_224, + hash::hmac_sha2_256, hash::hmac_sha2_384, hash::hmac_sha2_512, hash::hmac_sha2_512_224, + hash::hmac_sha2_512_256, hash::hmac_sha3_224, hash::hmac_sha3_256, hash::hmac_sha3_384, + hash::hmac_sha3_512, hash::hmac_ripemd_128, hash::hmac_ripemd_160, hash::hmac_blake2b_512, + hash::hmac_blake2s_256, hash::fnv1a_32, hash::fnv1a_64, hash::xxhash_32, hash::xxhash_64, + hash::xxh3_128, hash::murmur3_32, hash::murmur3_128, hash::spooky2_128>; +constexpr std::array hash2_type_names{ + "md5_128", "sha1_160", "sha2_224", + "sha2_256", "sha2_384", "sha2_512", + "sha2_512_224", "sha2_512_256", "sha3_224", + "sha3_256", "sha3_384", "sha3_512", + "shake_128", "shake_256", "blake2b_512", + "blake2s_256", "ripemd_128", "ripemd_160", + "siphash_32", "siphash_64", "hmac", + "hmac_md5_128", "hmac_sha1_160", "hmac_sha2_224", + "hmac_sha2_256", "hmac_sha2_384", "hmac_sha2_512", + "hmac_sha2_512_224", "hmac_sha2_512_256", "hmac_sha3_224", + "hmac_sha3_256", "hmac_sha3_384", "hmac_sha3_512", + "hmac_ripemd_128", "hmac_ripemd_160", "hmac_blake2b_512", + "hmac_blake2s_256", "fnv1a_32", "fnv1a_64", + "xxhash_32", "xxhash_64", "xxh3_128", + "murmur3_32", "murmur3_128", "spooky2_128", +}; + +test::coverage_calls type_calls() { + test::coverage_calls calls; + test::for_each_coverage_tag( + hash2_type_names, [&calls](std::string_view name) { + calls.emplace(name, + [name] { test::uncover_type(std::string(name) + " on hash2", true); }); + }); + return calls; +} + +} // namespace + +int main() { + using webcpp::hash::backends::hash2; + test::check_and_run("hash2", test::keyed_calls()); + test::uncover_digests(); + test::uncover_types("hash2", type_calls()); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/timing_coverage_openssl_test.cpp b/test/timing_coverage_openssl_test.cpp new file mode 100644 index 0000000..dcc0ee5 --- /dev/null +++ b/test/timing_coverage_openssl_test.cpp @@ -0,0 +1,36 @@ +// 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 keyed cell of backends::openssl enters its own detail::timing_guard first and leaves the +// thread's DIT as it found it, on every target of the backend, also where DIT does not apply, +// each with valid input and with input refused before the backend; every digest cell, called +// without a key, enters none (support/timing_coverage.hpp). +// +// What it covers, by family; the list is doc/capabilities.json's, read at run time, and a cell +// the table gains fails here until the support has its call: +// - mac over siphash_2_4, siphash_2_4x, kmac_128, kmac_256, blake2b_mac, blake2s_mac and +// hmac for each digest of the backend's cells. +// - hkdf_extract, hkdf_expand, hkdf, pbkdf2 and kbkdf over each hmac of hmac.hpp the cells list +// (all but hmac_ripemd_128); sskdf and x963kdf. +// - argon2id; argon2 of argon2d, argon2i and argon2id; scrypt. +// - BLAKE2b with a key (design D1): digest_of and hasher::make, which the cell refuses +// (unsupported_by_backend) inside the guard. +// - Not guarded: each digest cell without a key, through digest_of and a hasher round. + +#include "support/timing_coverage.hpp" + +#include +#include + +#include + +int main() { + namespace test = webcpp::test; + using webcpp::hash::backends::openssl; + test::check_and_run("openssl", test::keyed_calls()); + test::uncover_digests(); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/timing_coverage_sodium_test.cpp b/test/timing_coverage_sodium_test.cpp new file mode 100644 index 0000000..ff17b98 --- /dev/null +++ b/test/timing_coverage_sodium_test.cpp @@ -0,0 +1,33 @@ +// 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 keyed cell of backends::sodium enters its own detail::timing_guard first and leaves the +// thread's DIT as it found it, on every target of the backend, also where DIT does not apply, +// each with valid input and with input refused before the backend; every digest cell, called +// without a key, enters none (support/timing_coverage.hpp). +// +// What it covers, by family; the list is doc/capabilities.json's, read at run time, and a cell +// the table gains fails here until the support has its call: +// - mac over siphash_2_4, siphash_2_4x, blake2b_mac, hmac and hmac. +// - hkdf_extract, hkdf_expand and hkdf over hmac_sha2_256 and hmac_sha2_512; blake2b_subkey. +// - argon2id; argon2 of argon2i and argon2id; scrypt. +// - BLAKE2b with a key: digest_of and a hasher round (design D1). +// - Not guarded: each digest cell without a key, through digest_of and a hasher round. + +#include "support/timing_coverage.hpp" + +#include +#include + +#include + +int main() { + namespace test = webcpp::test; + using webcpp::hash::backends::sodium; + test::check_and_run("sodium", test::keyed_calls()); + test::uncover_digests(); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/timing_coverage_xkcp_test.cpp b/test/timing_coverage_xkcp_test.cpp new file mode 100644 index 0000000..fdd81ff --- /dev/null +++ b/test/timing_coverage_xkcp_test.cpp @@ -0,0 +1,37 @@ +// 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 keyed cell of backends::xkcp enters its own detail::timing_guard first and leaves the +// thread's DIT as it found it, on every target, also where DIT does not apply, each with valid +// input and with input refused before the backend; every digest cell, called without a key, +// enters none; and so does the keccak_256 type, seeded or not (design D3) +// (support/timing_coverage.hpp). +// +// What it covers, by family; the list is doc/capabilities.json's, read at run time, and a cell +// the table gains fails here until the support has its call: +// - mac over kmac_128 and kmac_256. +// - Not guarded: each digest cell without a key (SHA-3, SHAKE, TurboSHAKE, Keccak, cSHAKE, +// TupleHash, ParallelHash, KangarooTwelve), through digest_of and a hasher round; keccak_256. + +#include "support/timing_coverage.hpp" + +#include +#include +#include + +#include + +int main() { + namespace test = webcpp::test; + using webcpp::hash::backends::xkcp; + test::check_and_run("xkcp", test::keyed_calls()); + test::uncover_digests(); + test::coverage_calls types; + types.emplace("keccak_256", + [] { test::uncover_type("keccak_256 on xkcp", true); }); + test::uncover_types("xkcp", types); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/timing_keyed_test.cpp b/test/timing_keyed_test.cpp index cf0e10f..13bcf0e 100644 --- a/test/timing_keyed_test.cpp +++ b/test/timing_keyed_test.cpp @@ -11,7 +11,7 @@ // guard refuses before the backend; a call that is not keyed enters none (D2); a guard changes no // byte of any output. Where the CPU has DIT, mac leaves the thread's state as it found it. -#include "support/timing_seam.hpp" +#include "support/timing_coverage.hpp" #include #include From bc78c98be8ae1e4dd660f0cb69ffebcc43bb7816 Mon Sep 17 00:00:00 2001 From: R Date: Sun, 22 Nov 2026 08:28:25 -0300 Subject: [PATCH 09/27] hash: the coverage tests state how a new cell gets its call, and each refused call asserts the error of the guard that refuses it --- test/Jamfile | 6 ++- test/support/timing_coverage.hpp | 57 +++++++++++++++------------ test/timing_coverage_bearssl_test.cpp | 6 ++- test/timing_coverage_blake3_test.cpp | 6 ++- test/timing_coverage_botan_test.cpp | 6 ++- test/timing_coverage_hash2_test.cpp | 6 ++- test/timing_coverage_openssl_test.cpp | 6 ++- test/timing_coverage_sodium_test.cpp | 6 ++- test/timing_coverage_xkcp_test.cpp | 6 ++- 9 files changed, 63 insertions(+), 42 deletions(-) diff --git a/test/Jamfile b/test/Jamfile index fed0a6b..643f66f 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -731,8 +731,10 @@ botan-run timing_keyed_botan : timing_keyed_botan_test.cpp ; # password hashes, one per hmac a cell lists, and BLAKE2b with a key, the # blake3 type's keyed modes and bcrypt_verify) enters its own # detail::timing_guard first; every digest cell without a key, and every -# Boost.Hash2-form type, enters none. A cell the table gains fails until its -# call is added. backends::webcrypto has none (design D6). +# Boost.Hash2-form type, enters none. A new cell of a family the support +# knows gets its call from backend_has_v, which capabilities keeps equal to the +# table; a cell of a family or function it does not know fails until its call +# is written. backends::webcrypto has none (design D6). hash-run timing_coverage_hash2 : timing_coverage_hash2_test.cpp : $(.hash-tables) ; hash-run timing_coverage_sodium : timing_coverage_sodium_test.cpp : $(.hash-tables) /third_party//sodium ; diff --git a/test/support/timing_coverage.hpp b/test/support/timing_coverage.hpp index a97a83b..8860706 100644 --- a/test/support/timing_coverage.hpp +++ b/test/support/timing_coverage.hpp @@ -549,8 +549,8 @@ void cover_pbkdf2() { (hash::pbkdf2(output, coverage_key, coverage_salt, 1)).has_value()); }); covered("hash::pbkdf2 of 0 iterations" + on, [&] { - BOOST_TEST( - !(hash::pbkdf2(output, coverage_key, coverage_salt, 0)).has_value()); + BOOST_TEST((hash::pbkdf2(output, coverage_key, coverage_salt, 0)).error() == + hash::error::invalid_iterations); }); } @@ -568,7 +568,8 @@ void cover_kbkdf() { }); covered("hash::kbkdf with a counter of 7 bits" + on, [&] { BOOST_TEST( - !(hash::kbkdf(output, coverage_key, {.counter_bits = 7})).has_value()); + (hash::kbkdf(output, coverage_key, {.counter_bits = 7})).error() == + hash::error::invalid_parameters); }); } @@ -610,9 +611,9 @@ void cover_sskdf() { .has_value()); }); covered("hash::sskdf with an output of no byte" + on, [&] { - BOOST_TEST(!(hash::sskdf(std::span{}, - coverage_key, coverage_input)) - .has_value()); + BOOST_TEST((hash::sskdf(std::span{}, + coverage_key, coverage_input)) + .error() == hash::error::invalid_output_size); }); } @@ -627,9 +628,9 @@ void cover_x963kdf() { .has_value()); }); covered("hash::x963kdf with an output of no byte" + on, [&] { - BOOST_TEST(!(hash::x963kdf(std::span{}, - coverage_key, coverage_input)) - .has_value()); + BOOST_TEST((hash::x963kdf(std::span{}, + coverage_key, coverage_input)) + .error() == hash::error::invalid_output_size); }); } @@ -644,7 +645,8 @@ void cover_blake2b_subkey() { }); std::array tiny{}; covered("hash::blake2b_subkey with an output too small" + on, [&] { - BOOST_TEST(!(hash::blake2b_subkey(tiny, coverage_key, 7, context)).has_value()); + BOOST_TEST((hash::blake2b_subkey(tiny, coverage_key, 7, context)).error() == + hash::error::invalid_output_size); }); } @@ -659,9 +661,9 @@ void cover_argon2id() { (hash::argon2id(output, coverage_key, coverage_salt, cheapest)).has_value()); }); covered("hash::argon2id with a salt of 4 bytes" + on, [&] { - BOOST_TEST(!(hash::argon2id(output, coverage_key, - std::span(coverage_salt).first(4), cheapest)) - .has_value()); + BOOST_TEST((hash::argon2id(output, coverage_key, std::span(coverage_salt).first(4), + cheapest)) + .error() == hash::error::invalid_salt_size); }); } @@ -680,9 +682,9 @@ void cover_argon2(std::string_view variant) { .has_value()); }); covered("hash::argon2 with a salt of 4 bytes" + on, [&] { - BOOST_TEST(!(hash::argon2(output, coverage_key, - std::span(coverage_salt).first(4), family)) - .has_value()); + BOOST_TEST((hash::argon2(output, coverage_key, + std::span(coverage_salt).first(4), family)) + .error() == hash::error::invalid_salt_size); }); } @@ -698,8 +700,8 @@ void cover_scrypt() { }); covered("hash::scrypt of N = 1" + on, [&] { BOOST_TEST( - !(hash::scrypt(output, coverage_key, coverage_salt, {.n = 1, .r = 1, .p = 1})) - .has_value()); + (hash::scrypt(output, coverage_key, coverage_salt, {.n = 1, .r = 1, .p = 1})) + .error() == hash::error::invalid_parameters); }); } @@ -713,9 +715,9 @@ void cover_bcrypt() { (hash::bcrypt(output, coverage_key, coverage_salt, {.cost = 4})).has_value()); }); covered("hash::bcrypt with a salt of 8 bytes" + on, [&] { - BOOST_TEST(!(hash::bcrypt(output, coverage_key, std::span(coverage_salt).first(8), - {.cost = 4})) - .has_value()); + BOOST_TEST((hash::bcrypt(output, coverage_key, std::span(coverage_salt).first(8), + {.cost = 4})) + .error() == hash::error::invalid_salt_size); }); } @@ -741,7 +743,8 @@ void cover_bcrypt_verify() { BOOST_TEST(checked.has_value() && !*checked); }); covered("hash::bcrypt_verify of a string of the wrong form" + on, [&] { - BOOST_TEST(!hash::bcrypt_verify(coverage_key, "not a bcrypt string").has_value()); + BOOST_TEST(hash::bcrypt_verify(coverage_key, "not a bcrypt string").error() == + hash::error::invalid_parameters); }); } @@ -755,8 +758,8 @@ void cover_bcrypt_pbkdf() { (hash::bcrypt_pbkdf(output, coverage_key, coverage_salt, 1)).has_value()); }); covered("hash::bcrypt_pbkdf of 0 rounds" + on, [&] { - BOOST_TEST( - !(hash::bcrypt_pbkdf(output, coverage_key, coverage_salt, 0)).has_value()); + BOOST_TEST((hash::bcrypt_pbkdf(output, coverage_key, coverage_salt, 0)).error() == + hash::error::invalid_iterations); }); } @@ -835,8 +838,10 @@ void cover_keyed_blake2b() { * The calls of every keyed cell this support knows that `Backend` has, each by the name of its * cell (keyed_cells): mac over each tag, the functions over each hmac of the table's columns, * those over none, argon2's variants, and the keyed functions of design D1 but the blake3 type's, - * which its backend's test adds. A cell the backend has and this support does not know stays - * without a call, which check_and_run reports. + * which its backend's test adds. A new cell of a family this support knows gets its call here + * from backend_has_v, which capabilities_test keeps equal to the table; a cell of a family or + * function this support does not know stays without a call, which check_and_run reports until its + * call is written. * * @return The calls. */ diff --git a/test/timing_coverage_bearssl_test.cpp b/test/timing_coverage_bearssl_test.cpp index 33a78f7..b8e7db1 100644 --- a/test/timing_coverage_bearssl_test.cpp +++ b/test/timing_coverage_bearssl_test.cpp @@ -9,8 +9,10 @@ // each with valid input and with input refused before the backend; every digest cell, called // without a key, enters none (support/timing_coverage.hpp). // -// What it covers, by family; the list is doc/capabilities.json's, read at run time, and a cell -// the table gains fails here until the support has its call: +// What it covers, by family; the list is doc/capabilities.json's, read at run time. A new cell of +// a family the support knows gets its call from backend_has_v, which capabilities_test keeps equal +// to the table; a cell of a family or function the support does not know fails here until its +// call is written: // - mac over hmac for MD5, SHA-1, SHA-224, SHA-256, SHA-384 and SHA-512. // - hkdf over the six hmacs of those digests. // - Not guarded: each digest cell, through digest_of and a hasher round. diff --git a/test/timing_coverage_blake3_test.cpp b/test/timing_coverage_blake3_test.cpp index b3b9d62..277c88d 100644 --- a/test/timing_coverage_blake3_test.cpp +++ b/test/timing_coverage_blake3_test.cpp @@ -9,8 +9,10 @@ // where DIT does not apply; its digest cell, called through digest_of and a hasher round, and the // blake3 type in its plain mode enter none (support/timing_coverage.hpp). // -// What it covers, by family; the list is doc/capabilities.json's, read at run time, and a cell -// the table gains fails here until the support has its call: +// What it covers, by family; the list is doc/capabilities.json's, read at run time. A new cell of +// a family the support knows gets its call from backend_has_v, which capabilities_test keeps equal +// to the table; a cell of a family or function the support does not know fails here until its +// call is written: // - The blake3 type keyed (design D1), which the table holds no keyed cell of: keyed and // derive_key, and the seeds that key (a non-zero integer, bytes), then update (both // overloads), result, squeeze and reset of a keyed object (ruling H4, H5). diff --git a/test/timing_coverage_botan_test.cpp b/test/timing_coverage_botan_test.cpp index 2a99a9b..ebcc69c 100644 --- a/test/timing_coverage_botan_test.cpp +++ b/test/timing_coverage_botan_test.cpp @@ -9,8 +9,10 @@ // each with valid input and with input refused before the backend; every digest cell, called // without a key, enters none (support/timing_coverage.hpp). // -// What it covers, by family; the list is doc/capabilities.json's, read at run time, and a cell -// the table gains fails here until the support has its call: +// What it covers, by family; the list is doc/capabilities.json's, read at run time. A new cell of +// a family the support knows gets its call from backend_has_v, which capabilities_test keeps equal +// to the table; a cell of a family or function the support does not know fails here until its +// call is written: // - mac over siphash_2_4, kmac_128, kmac_256, blake2b_mac and hmac for the 23 digests of // the backend's cells. // - hkdf_extract, hkdf_expand, hkdf, pbkdf2 and kbkdf over each of the 14 hmacs the cells list; diff --git a/test/timing_coverage_hash2_test.cpp b/test/timing_coverage_hash2_test.cpp index c58432c..17a9099 100644 --- a/test/timing_coverage_hash2_test.cpp +++ b/test/timing_coverage_hash2_test.cpp @@ -10,8 +10,10 @@ // enters none; and so does every Boost.Hash2-form type of hmac.hpp and algorithms.hpp, seeded or // not (design D3) (support/timing_coverage.hpp). // -// What it covers, by family; the list is doc/capabilities.json's, read at run time, and a cell -// the table gains fails here until the support has its call: +// What it covers, by family; the list is doc/capabilities.json's, read at run time. A new cell of +// a family the support knows gets its call from backend_has_v, which capabilities_test keeps equal +// to the table; a cell of a family or function the support does not know fails here until its +// call is written: // - mac over siphash_2_4, blake2s_mac and hmac for each digest of the backend's cells. // - hkdf_extract, hkdf_expand, hkdf and pbkdf2 over each hmac of hmac.hpp and over another Hash2 // hmac (the column "other"). diff --git a/test/timing_coverage_openssl_test.cpp b/test/timing_coverage_openssl_test.cpp index dcc0ee5..69bcc43 100644 --- a/test/timing_coverage_openssl_test.cpp +++ b/test/timing_coverage_openssl_test.cpp @@ -9,8 +9,10 @@ // each with valid input and with input refused before the backend; every digest cell, called // without a key, enters none (support/timing_coverage.hpp). // -// What it covers, by family; the list is doc/capabilities.json's, read at run time, and a cell -// the table gains fails here until the support has its call: +// What it covers, by family; the list is doc/capabilities.json's, read at run time. A new cell of +// a family the support knows gets its call from backend_has_v, which capabilities_test keeps equal +// to the table; a cell of a family or function the support does not know fails here until its +// call is written: // - mac over siphash_2_4, siphash_2_4x, kmac_128, kmac_256, blake2b_mac, blake2s_mac and // hmac for each digest of the backend's cells. // - hkdf_extract, hkdf_expand, hkdf, pbkdf2 and kbkdf over each hmac of hmac.hpp the cells list diff --git a/test/timing_coverage_sodium_test.cpp b/test/timing_coverage_sodium_test.cpp index ff17b98..a9cb750 100644 --- a/test/timing_coverage_sodium_test.cpp +++ b/test/timing_coverage_sodium_test.cpp @@ -9,8 +9,10 @@ // each with valid input and with input refused before the backend; every digest cell, called // without a key, enters none (support/timing_coverage.hpp). // -// What it covers, by family; the list is doc/capabilities.json's, read at run time, and a cell -// the table gains fails here until the support has its call: +// What it covers, by family; the list is doc/capabilities.json's, read at run time. A new cell of +// a family the support knows gets its call from backend_has_v, which capabilities_test keeps equal +// to the table; a cell of a family or function the support does not know fails here until its +// call is written: // - mac over siphash_2_4, siphash_2_4x, blake2b_mac, hmac and hmac. // - hkdf_extract, hkdf_expand and hkdf over hmac_sha2_256 and hmac_sha2_512; blake2b_subkey. // - argon2id; argon2 of argon2i and argon2id; scrypt. diff --git a/test/timing_coverage_xkcp_test.cpp b/test/timing_coverage_xkcp_test.cpp index fdd81ff..81de519 100644 --- a/test/timing_coverage_xkcp_test.cpp +++ b/test/timing_coverage_xkcp_test.cpp @@ -10,8 +10,10 @@ // enters none; and so does the keccak_256 type, seeded or not (design D3) // (support/timing_coverage.hpp). // -// What it covers, by family; the list is doc/capabilities.json's, read at run time, and a cell -// the table gains fails here until the support has its call: +// What it covers, by family; the list is doc/capabilities.json's, read at run time. A new cell of +// a family the support knows gets its call from backend_has_v, which capabilities_test keeps equal +// to the table; a cell of a family or function the support does not know fails here until its +// call is written: // - mac over kmac_128 and kmac_256. // - Not guarded: each digest cell without a key (SHA-3, SHAKE, TurboSHAKE, Keccak, cSHAKE, // TupleHash, ParallelHash, KangarooTwelve), through digest_of and a hasher round; keccak_256. From e9bab02bd9702927969bfc7023daeca85901523d Mon Sep 17 00:00:00 2001 From: R Date: Sun, 22 Nov 2026 08:35:35 -0300 Subject: [PATCH 10/27] hash: a test proves the asynchronous forms set DIT on the thread that computes, the pool's for a heavy function and the caller's for a cheap one --- test/Jamfile | 13 ++ test/timing_async_test.cpp | 359 +++++++++++++++++++++++++++++++++++++ 2 files changed, 372 insertions(+) create mode 100644 test/timing_async_test.cpp diff --git a/test/Jamfile b/test/Jamfile index 643f66f..154c84d 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -710,6 +710,19 @@ hash-run timing_unseamed : timing_unseamed_test.cpp ; webcpp.run timing_unseamed_release : timing_unseamed_test.cpp : release WEBCPP_TEST_TIMING_READ_SELF : native ; +# The asynchronous forms set DIT on the thread that computes: the pool's for a +# heavy function (the synchronous function's guard, no initiating function holds +# one), the caller's for a cheap one; timing_async_botan the same for Botan's +# heavy forms and async_bcrypt, async_bcrypt_verify and async_bcrypt_pbkdf. +hash-run timing_async : timing_async_test.cpp + : /webcpp/asio//asio /third_party//sodium multi + emscripten:-sPTHREAD_POOL_SIZE=3 + : native emscripten ; +botan-run timing_async_botan : timing_async_test.cpp + : /webcpp/asio//asio multi + WEBCPP_TEST_TIMING_ASYNC_BOTAN + emscripten:-sPTHREAD_POOL_SIZE=3 ; + # mac and the keyed modes of BLAKE2b (digest_of, hasher with a key) and of # BLAKE3 (keyed, derive_key and the seeds that key) hold detail::timing_guard; a # call that is not keyed holds none; no output changes. diff --git a/test/timing_async_test.cpp b/test/timing_async_test.cpp new file mode 100644 index 0000000..fcbdc1b --- /dev/null +++ b/test/timing_async_test.cpp @@ -0,0 +1,359 @@ +// 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 asynchronous forms set DIT on the thread that computes (design D6, ruling H13): every form +// of async.hpp computes by calling its synchronous function, which holds the guard, and no +// initiating function holds one. Through the seam of support/timing_seam.hpp, each heavy form +// (async_pbkdf2, async_argon2id, async_argon2, async_scrypt, and with +// WEBCPP_TEST_TIMING_ASYNC_BOTAN the same on backends::botan with async_bcrypt, async_bcrypt_verify +// and async_bcrypt_pbkdf) on a webcpp::asio::thread_pool of one thread entered the guard of its +// synchronous function first on the pool's thread and none on the calling thread; the cheap ones +// (async_hmac, async_hkdf) entered mac's and hkdf's on the calling thread, during the initiation, +// and none on the pool's; async_digest, unkeyed, entered none on either; and a cancellation before +// the heavy work starts entered none anywhere. After each completion, the pool's thread and the +// calling thread are back to DIT off (where the CPU has it). The threads are synchronised by +// futures and by probes posted to the pool and completed through the io_context, never by sleeps; +// the cancellation holds the pool's only thread in a job of the test, as async_heavy_test does. + +#include "support/timing_seam.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#ifdef WEBCPP_TEST_TIMING_ASYNC_BOTAN +#include +#include +#else +#include +#include +#endif + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef WEBCPP_HASH_HAS_THREADS +#error "timing_async_test is built where the program has threads" +#endif + +namespace asio = webcpp::asio; +namespace hash = webcpp::hash; +namespace test = webcpp::test; +namespace kdfs = webcpp::hash::kdfs; + +namespace { + +#ifdef WEBCPP_TEST_TIMING_ASYNC_BOTAN +using pbkdf2_backend = hash::backends::botan; +using argon2id_backend = hash::backends::botan; +using argon2_backend = hash::backends::botan; +using scrypt_backend = hash::backends::botan; +using bcrypt_backend = hash::backends::botan; +constexpr std::uint32_t argon2_lanes = 2; +#else +using pbkdf2_backend = hash::default_async_backend; +using argon2id_backend = hash::default_backend; +using argon2_backend = hash::default_backend; +using scrypt_backend = hash::default_backend; +constexpr std::uint32_t argon2_lanes = 1; +#endif + +constexpr std::array password{'p', 'a', 's', 's', 'w', 'o', 'r', 'd'}; +constexpr std::array salt{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}; + +// What a thread recorded through the seam, and whether it was back to DIT off when it was read. +struct record { + std::size_t entries = 0; + std::string first; + bool dit_off = false; +}; + +// Resets the seam's two per-thread values and reads DIT, on the calling thread. +void reset_this_thread() { + test::timing_entries = 0; + test::timing_first_entry = nullptr; +} + +record read_this_thread() { + return {.entries = test::timing_entries, + .first = test::timing_first_entry != nullptr ? test::timing_first_entry : "", + .dit_off = !hash::detail::dit_is_set()}; +} + +// Runs a probe on the pool's thread and waits for its answer through a future. +template +auto on_pool(asio::thread_pool& pool, Probe probe) { + std::promise answer; + auto future = answer.get_future(); + asio::post(pool, [&answer, &probe] { answer.set_value(probe()); }); + return future.get(); +} + +void reset_pool_thread(asio::thread_pool& pool) { + on_pool(pool, [] { + reset_this_thread(); + return true; + }); +} + +record read_pool_thread(asio::thread_pool& pool) { + return on_pool(pool, [] { return read_this_thread(); }); +} + +// What a completion saw. +struct completion { + bool called = false; + boost::system::error_code code{}; + bool same = false; +}; + +// A handler bound to the context, that records the completion. +auto recording_handler(asio::io_context& context, completion& seen) { + return asio::bind_executor(context.get_executor(), + [&seen](boost::system::error_code code, auto... same) { + seen.called = true; + seen.code = code; + ((seen.same = same), ...); + }); +} + +void run_to_completion(asio::io_context& context) { + context.restart(); + context.run(); // lint-run: the test's event loop +} + +// Reports `message` as an error when `ok` is false. +void expect(bool ok, std::string const& message) { + if (!ok) { + BOOST_ERROR(message.c_str()); + } +} + +// Whether a record's first guard is the synchronous function's. +bool entered_first(record const& seen, std::string_view function) { + return !seen.first.empty() && test::names_function(seen.first, test::function_named(function)); +} + +// A heavy form: the pool's thread enters the guard of `function` first, the calling thread none, +// and both threads are back to DIT off after the completion. +template +void heavy(std::string_view name, std::string_view function, asio::io_context& context, + asio::thread_pool& pool, Start start) { + reset_pool_thread(pool); + reset_this_thread(); + completion seen; + start(recording_handler(context, seen)); + run_to_completion(context); + record const caller = read_this_thread(); + record const worker = read_pool_thread(pool); + std::string const label(name); + expect(seen.called, label); + expect(!seen.code, label + ": " + seen.code.message()); + expect(worker.entries >= 1, label); + expect(entered_first(worker, function), label + " entered " + worker.first); + expect(caller.entries == 0, + label + ": " + std::to_string(caller.entries) + " guards entered on the wrong thread"); + expect(worker.dit_off, label); + expect(caller.dit_off, label); +} + +// A cheap form on a synchronous backend: the calling thread enters the guard of `function` first +// during the initiation, the pool's thread none. +template +void cheap(std::string_view name, std::string_view function, asio::io_context& context, + asio::thread_pool& pool, Start start) { + reset_pool_thread(pool); + reset_this_thread(); + completion seen; + start(recording_handler(context, seen)); + run_to_completion(context); + record const caller = read_this_thread(); + record const worker = read_pool_thread(pool); + std::string const label(name); + expect(seen.called, label); + expect(!seen.code, label + ": " + seen.code.message()); + expect(caller.entries >= 1, label); + expect(entered_first(caller, function), label + " entered " + caller.first); + expect(worker.entries == 0, + label + ": " + std::to_string(worker.entries) + " guards entered on the wrong thread"); + expect(caller.dit_off, label); + expect(worker.dit_off, label); +} + +void check_heavy(asio::io_context& context, asio::thread_pool& pool) { + auto work = pool.get_executor(); + std::array output{}; + + heavy("async_pbkdf2", "hash::pbkdf2", context, pool, [&](auto handler) { + hash::async_pbkdf2(work, output, password, salt, 100, + std::move(handler)); + }); + heavy("async_argon2id", "hash::argon2id", context, pool, [&](auto handler) { + hash::async_argon2id(work, output, password, salt, + {.passes = 2, .memory = 65536}, std::move(handler)); + }); + heavy("async_argon2", "hash::argon2", context, pool, [&](auto handler) { + hash::async_argon2, + kdfs::argon2id, kdfs::argon2i>, + argon2_backend>(work, output, password, salt, + {.passes = 3, .memory_kib = 64, .lanes = argon2_lanes}, + std::move(handler)); + }); + heavy("async_scrypt", "hash::scrypt", context, pool, [&](auto handler) { + hash::async_scrypt(work, output, password, salt, + {.n = 1024, .r = 8, .p = 1}, std::move(handler)); + }); +#ifdef WEBCPP_TEST_TIMING_ASYNC_BOTAN + std::array stored{}; + heavy("async_bcrypt", "hash::bcrypt", context, pool, [&](auto handler) { + hash::async_bcrypt(work, stored, password, salt, {.cost = 4}, + std::move(handler)); + }); + heavy("async_bcrypt_verify", "hash::bcrypt_verify", context, pool, [&](auto handler) { + hash::async_bcrypt_verify( + work, password, std::string_view(stored.data(), stored.size()), std::move(handler)); + }); + heavy("async_bcrypt_pbkdf", "hash::bcrypt_pbkdf", context, pool, [&](auto handler) { + hash::async_bcrypt_pbkdf(work, output, password, salt, 4, + std::move(handler)); + }); +#endif +} + +#ifndef WEBCPP_TEST_TIMING_ASYNC_BOTAN +void check_cheap(asio::io_context& context, asio::thread_pool& pool) { + auto loop = context.get_executor(); + std::array output{}; + std::array key{}; + key.fill(0x0b); + + cheap("async_hmac", "hash::mac", context, pool, [&](auto handler) { + hash::async_hmac(loop, output, key, password, std::move(handler)); + }); + cheap("async_hkdf", "hash::hkdf", context, pool, [&](auto handler) { + hash::async_hkdf(loop, output, salt, key, password, + std::move(handler)); + }); + + // async_digest is unkeyed: no thread enters a guard. + reset_pool_thread(pool); + reset_this_thread(); + completion seen; + hash::async_digest(loop, output, password, + recording_handler(context, seen)); + run_to_completion(context); + record const caller = read_this_thread(); + record const worker = read_pool_thread(pool); + BOOST_TEST(seen.called); + BOOST_TEST(!seen.code); + BOOST_TEST_EQ(caller.entries, 0u); + BOOST_TEST_EQ(worker.entries, 0u); +} +#endif + +// A cancellation before the work starts: the pool's only thread is held by a job of the test, so +// that each work is queued and never started; the completion arrives at once on the context, the +// work is skipped when the thread is released, and no thread entered a guard. +void check_cancelled_before(asio::io_context& context) { + asio::thread_pool busy(1); + std::promise release; + auto const released = release.get_future().share(); + std::atomic blocking{false}; + asio::post(busy, [&blocking, released] { + reset_this_thread(); + blocking = true; + released.wait(); + }); + while (!blocking) { + std::this_thread::yield(); + } + reset_this_thread(); + auto work = busy.get_executor(); + std::array output{}; + auto const cancelled = [&](auto start) { + asio::cancellation_signal signal; + completion seen; + start(asio::bind_cancellation_slot(signal.slot(), recording_handler(context, seen))); + signal.emit(asio::cancellation_type::terminal); + run_to_completion(context); + BOOST_TEST(seen.called); + BOOST_TEST(seen.code == asio::error::operation_aborted); + }; + cancelled([&](auto handler) { + hash::async_pbkdf2(work, output, password, salt, 100, + std::move(handler)); + }); + cancelled([&](auto handler) { + hash::async_argon2id(work, output, password, salt, + {.passes = 2, .memory = 65536}, std::move(handler)); + }); + cancelled([&](auto handler) { + hash::async_scrypt(work, output, password, salt, + {.n = 1024, .r = 8, .p = 1}, std::move(handler)); + }); +#ifdef WEBCPP_TEST_TIMING_ASYNC_BOTAN + std::array stored{}; + cancelled([&](auto handler) { + hash::async_bcrypt(work, stored, password, salt, {.cost = 4}, + std::move(handler)); + }); + cancelled([&](auto handler) { + hash::async_bcrypt_pbkdf(work, output, password, salt, 4, + std::move(handler)); + }); +#endif + release.set_value(); + // The probe queues behind every skipped work on the pool's only thread. + record const worker = read_pool_thread(busy); + BOOST_TEST_EQ(worker.entries, 0u); + BOOST_TEST_EQ(read_this_thread().entries, 0u); + busy.join(); +} + +} // namespace + +int main() { + asio::io_context context; + { + asio::thread_pool pool(1); + check_heavy(context, pool); +#ifndef WEBCPP_TEST_TIMING_ASYNC_BOTAN + check_cheap(context, pool); +#endif + pool.join(); + } + check_cancelled_before(context); + return webcpp::test::exit_status(boost::report_errors()); +} From f6c30710cde8352a02baed847f846c4f46a81a07 Mon Sep 17 00:00:00 2001 From: R Date: Sun, 22 Nov 2026 08:37:59 -0300 Subject: [PATCH 11/27] hash: the timing_async cancellation case waits on a promise for the held pool thread, never a yield loop --- test/timing_async_test.cpp | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/test/timing_async_test.cpp b/test/timing_async_test.cpp index fcbdc1b..88786b1 100644 --- a/test/timing_async_test.cpp +++ b/test/timing_async_test.cpp @@ -53,14 +53,12 @@ #include #include -#include #include #include #include #include #include #include -#include #include #include @@ -290,15 +288,14 @@ void check_cancelled_before(asio::io_context& context) { asio::thread_pool busy(1); std::promise release; auto const released = release.get_future().share(); - std::atomic blocking{false}; + std::promise blocking; + auto const holding = blocking.get_future(); asio::post(busy, [&blocking, released] { reset_this_thread(); - blocking = true; + blocking.set_value(); released.wait(); }); - while (!blocking) { - std::this_thread::yield(); - } + holding.wait(); reset_this_thread(); auto work = busy.get_executor(); std::array output{}; From 8b0f6d9af9e92db1258b3c5d2dae24f1eb4feb2e Mon Sep 17 00:00:00 2001 From: R Date: Sun, 22 Nov 2026 09:05:38 -0300 Subject: [PATCH 12/27] hash: the guard's cost measured in release and the pages say which functions set DIT and which do not --- AGENTS.md | 8 + bench/Jamfile | 15 +- bench/collect.py | 278 +++++++++++++++++++++++++++++-- bench/timing.cpp | 248 +++++++++++++++++++++++++++ doc/async.adoc | 10 ++ doc/backends.adoc | 22 +++ doc/changelog.adoc | 2 +- doc/digests.adoc | 28 +++- doc/kdfs.adoc | 8 + doc/llms.txt | 2 + doc/macs.adoc | 12 ++ doc/measurements.throughput.json | 40 ++++- doc/password_hashing.adoc | 9 + doc/performance.adoc | 55 +++++- 14 files changed, 715 insertions(+), 22 deletions(-) create mode 100644 bench/timing.cpp diff --git a/AGENTS.md b/AGENTS.md index 1f77c6e..590a5d8 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -23,5 +23,13 @@ specific to hash. decoding); a moved pin carries that commit. A moved pin is a change of its own (rule 12). - A test is declared through `hash-run` in `test/Jamfile`, which runs it with exceptions and without. +- Every function that computes on a key, a password or a key derivation's secret input holds + `detail::timing_guard` as its first statement (`timing{engaged}` where the arguments decide + whether the call is keyed); unkeyed digests and Boost.Hash2's types by alias hold none. A new + keyed function, or a keyed cell that `doc/capabilities.json` gains (a MAC, a key derivation, a + password hash, on any backend), holds the guard and gets its call in that backend's + `test/timing_coverage__test.cpp`, which fails until it does. `detail/timing.hpp` is a + copy of webcpp::crypto's `detail/timing.hpp` (hash cannot depend on crypto): a change to one is + made to both, and crypto's `test/timing_hash_interop_test.cpp` runs the two together. - `include/webcpp/hash/detail/canary.h` is a C header: it is in neither the headers-alone list nor `meta/include-boundaries.json`. diff --git a/bench/Jamfile b/bench/Jamfile index b206c0c..7574060 100644 --- a/bench/Jamfile +++ b/bench/Jamfile @@ -4,7 +4,8 @@ # accompanying file LICENSE_1_0.txt or copy at # https://www.boost.org/LICENSE_1_0.txt) -# The throughput of PBKDF2-HMAC-SHA-512 at 1,000,000 iterations (spec 4.3). +# The throughput of PBKDF2-HMAC-SHA-512 at 1,000,000 iterations (spec 4.3), +# and the cost of the timing guard (timing.cpp). # pbkdf2_sha512_key is the correctness test of the measured program: each # variant's derived key against an independent value, on every target, never # failing on a time. The measurements themselves are made by collect.py, which @@ -38,6 +39,18 @@ webcpp.run pbkdf2_sha512_key : pbkdf2_sha512.cpp : $(.requirements) ; exe pbkdf2_sha512 : pbkdf2_sha512.cpp : $(.requirements) release ; explicit pbkdf2_sha512 ; +# The cost of detail::timing_guard, the scope every keyed function runs in +# (doc/performance.adoc). timing_check is the correctness test of the measured +# program, run in every lane of test/: the measurement at 10^3 iterations, its +# line's form and the thread's DIT checked. It needs no backend: +# detail/timing.hpp alone. +webcpp.run timing_check : timing.cpp : speed ; + +# The same program at variant=release, the one collect.py --timing measures, +# natively and by hand (doc/performance.adoc); no lane measures it. +exe timing : timing.cpp : release speed ; +explicit timing ; + # The allocation counts of doc/allocation.adoc (spec section 7.7), from release # builds only: the programs of test/allocation_test.cpp, # test/allocation_openssl_test.cpp and test/allocation_botan_test.cpp built at diff --git a/bench/collect.py b/bench/collect.py index feb0c9b..1b76c36 100755 --- a/bench/collect.py +++ b/bench/collect.py @@ -5,19 +5,24 @@ # accompanying file LICENSE_1_0.txt or copy at # https://www.boost.org/LICENSE_1_0.txt) -"""Measures bench/pbkdf2_sha512.cpp on each target and renders its data. +"""Measures bench/pbkdf2_sha512.cpp on each target and bench/timing.cpp natively, and renders +their data. collect.py --exe native= --exe wasip2= ... --invocations 5 \ + --timing \ --data doc/measurements.throughput.json --page doc/performance.adoc Run from the superproject's root (the launchers' paths, tools/boost/asio-wasip2/run.sh and its wasip3 twin, are relative to it), with the programs bench/Jamfile builds at -variant=release optimization=speed; --data and --page are relative to the same root, as -libs/hash/doc/... . +variant=release optimization=speed (`b2 libs/hash/bench//pbkdf2_sha512` on each target and +`b2 libs/hash/bench//timing` natively); --data and --page are relative to the same root, as +libs/hash/doc/... . `--timing` alone, without `--exe`, measures the guard and keeps the data's +throughput; `--exe` alone measures the throughput and keeps the data's guard. -The table is built only from release builds: a program whose build directory, b2's +The page is built only from release builds: a program whose build directory, b2's bench///..., is not variant=release, or does not say, is refused before -anything runs, and `--render-only` refuses data whose build is not BUILD. +anything runs, and `--render-only` refuses data whose build, or whose guard's build, is not +BUILD. Each case (a variant on a target) is run INVOCATIONS times, round-robin over the cases so that a change of load on the shared machine falls on all of them alike; @@ -26,6 +31,19 @@ maximum of every single run. A time never fails this script: only a wrong key, or a program that does not run, does. `--render-only` rewrites the page from the data. + +The timing guard's cost (detail::timing_guard, which every keyed function holds and which sets +64-bit ARM's DIT where the CPU has it) is `timing --measure`'s one line: whether the guard sets +DIT on this machine, and the nanoseconds a guard adds to a call entered from a thread whose DIT +is clear, from one where it is already set, and a disengaged guard's (an unkeyed call of a +function keyed by its arguments), each the median of five runs of 10^7 guards minus an empty +loop's, with the fastest and slowest run. The data keeps it under "timing_guard" with the date +(UTC's), the machine and the load; the page renders it as a paragraph and a table after the +throughput. A line or a "timing_guard" that is not the form this script writes (an older +program's, a key missing or of another type) is refused with a message naming what is wrong, +before anything is written. `--provisional` marks the guard's figures as provisional, measured +on a shared, loaded machine and to be measured again in a final pass on a quiet one, which the +page says; measuring the guard without it clears the mark. """ import argparse @@ -37,10 +55,12 @@ import sys from pathlib import Path -# What the table is built from, and only from: bench/Jamfile's pbkdf2_sha512, at variant=release. +# What the page is built from, and only from: bench/Jamfile's pbkdf2_sha512 and timing, at +# variant=release. BUILD = "variant=release optimization=speed" RELEASE_ONLY = ( - "the table is built only from release builds: bench/Jamfile's pbkdf2_sha512 at " + BUILD + "the page is built only from release builds: bench/Jamfile's pbkdf2_sha512 and timing at " + + BUILD ) LAUNCHERS = { @@ -75,7 +95,8 @@ def variant_of(exe): def check_release(exes): - """Exits naming each program not built at variant=release, before anything runs.""" + """Exits naming each program not built at variant=release, before anything runs; exes maps + a target, or "timing" for the guard's program, to its path.""" others = [] for target, exe in exes.items(): variant = variant_of(exe) @@ -190,10 +211,181 @@ def measure(exes, invocations): } +NUMBER = (int, float) +# bench/timing.cpp's line, and the "timing_guard" this script writes from it: each key's type, or +# the shape of a nested object. +TIMING_LINE_SHAPE = {"dit": bool, "clear": NUMBER, "set": NUMBER, "disengaged": NUMBER, + "clear_fastest": NUMBER, "clear_slowest": NUMBER, "set_fastest": NUMBER, + "set_slowest": NUMBER, "disengaged_fastest": NUMBER, + "disengaged_slowest": NUMBER, "iterations": int, "runs": int, + "target": str, "compiler": str} +TIMING_SHAPE = {"date": str, "build": str, "target": str, "compiler": str, "iterations": int, + "runs": int, "dit": bool, "provisional": bool, + "machine": {"cpu": str, "architecture": str, "cores": int, "os": str}, + "load_average_before_after": [[NUMBER]], + **{f"{part}{spread}_ns": NUMBER for part in ("clear", "set", "disengaged") + for spread in ("", "_fastest", "_slowest")}} + + +def wrong(value, shape, where): + """The first place in value that shape requires and value lacks or holds otherwise, named as + a path from where; None when value has the shape. A one-element list is a non-empty list of + that shape; a bool is never a number.""" + if isinstance(shape, dict): + if not isinstance(value, dict): + return f"{where} (not an object)" + for key, inner in shape.items(): + if key not in value: + return f"{where}.{key} (missing)" + found = wrong(value[key], inner, f"{where}.{key}") + if found is not None: + return found + return None + if isinstance(shape, list): + if not isinstance(value, list) or not value: + return f"{where} (not a list, or empty)" + return next((found for index, item in enumerate(value) + if (found := wrong(item, shape[0], f"{where}[{index}]")) is not None), None) + types = shape if isinstance(shape, tuple) else (shape,) + if isinstance(value, bool) and bool not in types: + return where + return None if isinstance(value, types) else where + + +def utc_today(): + """Today's date in UTC, the date the guard's measurement states.""" + return datetime.datetime.now(datetime.timezone.utc).date().isoformat() + + +def measure_timing(exe, provisional): + """The guard's cost, timing --measure's line, natively, with when, where and under what load + it was measured; exits naming what is wrong when the program fails or its line is not the + form this script reads.""" + command = [exe, "--measure"] + loads = [os.getloadavg()] + done = subprocess.run(command, capture_output=True, text=True, check=False) + loads.append(os.getloadavg()) + if done.returncode != 0: + sys.exit(f"collect.py: timing --measure: exit {done.returncode}\n" + f"{done.stdout}{done.stderr}") + lines = done.stdout.strip().splitlines() + try: + line = json.loads(lines[-1]) if lines else None + except ValueError: + line = None + found = wrong(line, TIMING_LINE_SHAPE, "line") if line is not None else "line (not JSON)" + # TIMING_LINE_SHAPE is an object's, so wrong finds nothing only in a dict; the isinstance + # states that to the type checker. + if found is not None or not isinstance(line, dict): + printed = lines[-1] if lines else "" + sys.exit(f"collect.py: timing --measure printed {printed!r}, which is not the form " + f"collect.py reads: {found} is wrong; build bench/Jamfile's timing again from " + "this tree") + return { + "measurement": "the nanoseconds detail::timing_guard adds to a call, bench/timing.cpp", + "date": utc_today(), + "machine": { + "cpu": sysctl("machdep.cpu.brand_string") or platform.processor() or platform.machine(), + "architecture": platform.machine(), + "cores": os.cpu_count() or 1, + "os": f"{platform.system()} {platform.release()}", + }, + "load_average_before_after": [list(loads[0]), list(loads[1])], + "build": BUILD, + "target": line["target"], + "compiler": line["compiler"], + "iterations": line["iterations"], + "runs": line["runs"], + "dit": line["dit"], + **{f"{part}{spread}_ns": line[f"{part}{spread}"] + for part in ("clear", "set", "disengaged") for spread in ("", "_fastest", "_slowest")}, + "provisional": provisional, + } + + def fmt_load(load): return "/".join(f"{x:.0f}" for x in load) +def fmt_ns(value): + """Nanoseconds as the page shows them: one decimal, a figure that rounds to zero or below it + shown as 0.0, the empty loop's noise.""" + return "0.0" if round(value, 1) <= 0 else f"{value:.1f}" + + +# What the page says above the guard's table when its figures are provisional (--provisional). +PROVISIONAL = ( + "NOTE: these figures are provisional. They were measured on a shared machine under load " + "(the load averages above), and are measured again in a final measurement pass on a quiet " + "machine, once the work in progress has merged; read them as an upper bound." +) + + +def render_timing(timing): + """The guard's paragraph and table, from the data's "timing_guard", or the line saying it is + not measured yet.""" + lines = [ + "[#hash-performance-timing]", + "=== The timing guard's cost", + "", + "Every keyed function (a MAC, a key derivation, a password hash, a keyed mode of", + "BLAKE2b or BLAKE3) runs inside `detail::timing_guard`, which on 64-bit ARM under", + "macOS, iOS, Linux and Android, where the CPU has FEAT_DIT, sets DIT (data-independent", + "timing) for the call and restores the thread's state after it", + "(<>): one `mrs`, and where DIT was clear, two `msr` each", + "followed by an `isb`. Elsewhere (x86, WebAssembly, Windows on ARM64) it executes no", + "instruction. A function keyed by its arguments, called without a key, holds a", + "disengaged guard, which reads its flag and does nothing else.", + "", + ] + if timing is None: + return lines + ["Not measured yet.", ""] + machine_info = timing["machine"] + sets = ("The guard sets DIT on this machine." if timing["dit"] else + "The guard does not set DIT on this machine (no FEAT_DIT, or a target it does not " + "cover): every row is the loop's noise.") + load = timing["load_average_before_after"] + lines += [ + f"Measured natively on {timing['date']} (UTC) on {machine_info['cpu']}", + f"({machine_info['architecture']}), {machine_info['os']}, built with {timing['build']}", + f"by {timing['compiler']} (bench/timing.cpp): each row is the median of", + f"{timing['runs']} runs of {timing['iterations']:,} guards around a store, with the", + "fastest and slowest run beside it, each minus the median of the same loop without the", + "guard, in nanoseconds per call; a figure that rounds to zero or below, the loop's", + "noise, shows as 0.0.", + f"{sets} The machine's 1, 5 and 15 minute load averages were {fmt_load(load[0])}", + f"before and {fmt_load(load[1])} after, on {machine_info['cores']} cores.", + "", + ] + if timing["provisional"]: + lines += [PROVISIONAL, ""] + rows = ( + ("clear", "clear, as a program that sets nothing has it", + "reads DIT, sets it, and clears it on the way out"), + ("set", "already set, by the program or by an outer guard", + "reads DIT and leaves it set"), + ("disengaged", "any: a function keyed by its arguments, called without a key", + "reads its flag and does nothing else"), + ) + lines += [ + '[cols="2,4,1,1,1",options="header"]', + "|===", + "| The thread's DIT on entry | What the guard does | Median (ns) | Fastest (ns) " + "| Slowest (ns)", + ] + for part, entry, does in rows: + lines += [ + "", + f"| {entry}", + f"| {does}", + f"| {fmt_ns(timing[part + '_ns'])}", + f"| {fmt_ns(timing[part + '_fastest_ns'])}", + f"| {fmt_ns(timing[part + '_slowest_ns'])}", + ] + lines += ["|===", ""] + return lines + + def render(data, page): machine_info = data["machine"] cases = {(c["variant"], c["target"]): c for c in data["cases"]} @@ -207,7 +399,13 @@ def render(data, page): "// Generated by bench/collect.py from doc/measurements.throughput.json: do not edit.", "", "[#hash-performance]", - "== PBKDF2-HMAC-SHA-512 throughput", + "== Performance", + "", + "PBKDF2-HMAC-SHA-512's throughput per backend, and what the timing guard adds to a", + "keyed call, each measured from release builds.", + "", + "[#hash-performance-pbkdf2]", + "=== PBKDF2-HMAC-SHA-512 throughput", "", "How long each backend takes to derive 64 bytes by PBKDF2-HMAC-SHA-512 at 1,000,000", "iterations, on each target where the backend exists. The figure that matters to a", @@ -261,28 +459,74 @@ def render(data, page): "the library.", "", ] + lines += render_timing(data.get("timing_guard")) with open(page, "w", encoding="utf-8") as f: f.write("\n".join(lines)) +def read_release_data(path): + """The data at path; exits when it cannot be read, or when it, or its guard's measurement, + was not built at BUILD or is not the form this script writes.""" + try: + with open(path, encoding="utf-8") as f: + data = json.load(f) + except (OSError, ValueError) as error: + sys.exit(f"collect.py: {path} cannot be read ({error}); --timing alone and --render-only " + "read the data that --exe wrote") + if not isinstance(data, dict) or data.get("build") != BUILD: + build = data.get("build") if isinstance(data, dict) else None + sys.exit(f"collect.py: {path} was measured with build {build}, not {BUILD}: " + f"{RELEASE_ONLY}") + timing = data.get("timing_guard") + if timing is not None: + if not isinstance(timing, dict) or timing.get("build") != BUILD: + build = timing.get("build") if isinstance(timing, dict) else None + sys.exit(f"collect.py: {path}'s timing guard was measured with build {build}, not " + f"{BUILD}: {RELEASE_ONLY}") + found = wrong(timing, TIMING_SHAPE, "data.timing_guard") + if found is not None: + sys.exit(f"collect.py: {path} is not the data collect.py writes: {found} is wrong; " + "measure the guard again with --timing") + return data + + def main(): - parser = argparse.ArgumentParser(description="Measures bench/pbkdf2_sha512.cpp on each target.") + parser = argparse.ArgumentParser( + description="Measures bench/pbkdf2_sha512.cpp on each target and bench/timing.cpp.") parser.add_argument("--exe", action="append", default=[], metavar="TARGET=PATH") parser.add_argument("--invocations", type=int, default=5) parser.add_argument("--data", required=True) parser.add_argument("--page", required=True) + parser.add_argument("--timing", metavar="PATH", + help="bench/Jamfile's timing at variant=release, run natively") + parser.add_argument("--provisional", action="store_true", + help="with --timing: mark the guard's figures as measured under load, to " + "be measured again") parser.add_argument("--render-only", action="store_true") args = parser.parse_args() + if args.provisional and args.timing is None: + sys.exit("collect.py: --provisional marks the guard's figures: give it with --timing") if args.render_only: - with open(args.data, encoding="utf-8") as f: - data = json.load(f) - if data.get("build") != BUILD: - sys.exit(f"collect.py: {args.data} was measured with build {data.get('build')}, not " - f"{BUILD}: {RELEASE_ONLY}") + data = read_release_data(args.data) else: exes = dict(item.split("=", 1) for item in args.exe) - check_release(exes) - data = measure(exes, args.invocations) + if not exes and args.timing is None: + sys.exit("collect.py: nothing to measure: give --exe, --timing or --render-only") + check_release({**exes, **({"timing": args.timing} if args.timing else {})}) + kept = read_release_data(args.data) if (not exes or args.timing is None) and \ + Path(args.data).exists() else None + if exes: + data = measure(exes, args.invocations) + # The guard's cost is kept until it is measured again. + if kept is not None and kept.get("timing_guard") is not None: + data["timing_guard"] = kept["timing_guard"] + elif kept is not None: + data = kept + else: + sys.exit(f"collect.py: {args.data} does not exist; --timing alone keeps the data's " + "throughput, which --exe writes") + if args.timing is not None: + data["timing_guard"] = measure_timing(args.timing, args.provisional) with open(args.data, "w", encoding="utf-8") as f: json.dump(data, f, indent=2) f.write("\n") diff --git a/bench/timing.cpp b/bench/timing.cpp new file mode 100644 index 0000000..802c49e --- /dev/null +++ b/bench/timing.cpp @@ -0,0 +1,248 @@ +// 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 cost of detail::timing_guard, the scope every keyed public function of hash runs in (a MAC, +// a key derivation, a password hash, a keyed mode of BLAKE2b or BLAKE3), which sets 64-bit ARM's +// DIT (data-independent timing) bit where the CPU has it and restores the thread's state after +// it. bench/timing.cpp of webcpp::crypto measures crypto's copy of the guard the same way. +// +// Run as `timing --measure`, it times, in one process, 10^7 iterations each of an empty loop body, +// of a guard entered from a thread whose DIT is clear (it sets DIT and clears it again), of a +// guard entered with DIT already set (it reads DIT and leaves it; the program sets DIT for that +// part with the same `msr` as the guard, and clears it after), and of a disengaged guard (what an +// unkeyed call of a function that is keyed by its arguments pays: the flag, read from memory as a +// member is, and a branch), five runs of each, interleaved, and prints one JSON line: +// `{"dit": true|false, "clear": , "set": , "disengaged": , ...}`, each cost the +// median of its runs minus the empty loop's median, in nanoseconds per guard, then each part's +// fastest and slowest run (minus the same median), the iterations, the runs, the target and the +// compiler. "dit" says whether the guard sets DIT here (a target it covers, on a CPU that has it); +// where it does not, the guard executes no instruction and the costs are the loop's noise. Both +// modes fail when the process starts with DIT set, or when the thread's DIT is not as the guard +// must leave it after a part. Run with no argument, it is the correctness test: the same +// measurement at 10^3 iterations, whose line must also have that form, and whose "dit" must be +// what the library reads. A measurement never fails on its time; bench/collect.py --timing runs +// it and writes doc/performance.adoc. + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace detail = webcpp::hash::detail; + +namespace { + +#ifdef WEBCPP_TARGET_WASIP2 +constexpr std::string_view target = "wasip2"; +#elif defined(WEBCPP_TARGET_WASIP3) +constexpr std::string_view target = "wasip3"; +#elif defined(WEBCPP_TARGET_EMSCRIPTEN) +constexpr std::string_view target = "emscripten"; +#else +constexpr std::string_view target = "native"; +#endif + +// The compiler, as it names itself: MSVC defines no __VERSION__. +#ifdef __VERSION__ +constexpr std::string_view compiler = __VERSION__; +#elif defined(_MSC_FULL_VER) +#define WEBCPP_HASH_BENCH_STRING(x) #x +#define WEBCPP_HASH_BENCH_VERSION(x) WEBCPP_HASH_BENCH_STRING(x) +constexpr std::string_view compiler = "MSVC " WEBCPP_HASH_BENCH_VERSION(_MSC_FULL_VER); +#else +constexpr std::string_view compiler = "unknown"; +#endif + +// The iterations of a measured run, and of the correctness test's. +constexpr std::uint64_t measured_iterations = 10'000'000; +constexpr std::uint64_t checked_iterations = 1'000; + +// The runs of each part; their median is the part's time. +constexpr std::size_t runs = 5; + +// Whether the guard sets DIT on this target and CPU. +bool guard_sets_dit() noexcept { +#ifdef WEBCPP_HASH_DETAIL_TIMING_COVERED + return detail::cpu_has_dit(); +#else + return false; +#endif +} + +// Sets or clears this thread's DIT where the guard would, as a program that asks for it does. +void force_dit([[maybe_unused]] bool set) noexcept { +#ifdef WEBCPP_HASH_DETAIL_TIMING_COVERED + if (detail::cpu_has_dit()) { + detail::write_dit(set ? detail::dit_bit : 0); + } +#endif +} + +// The nanoseconds of one iteration of body, over iterations of it. +template +double nanoseconds_per_iteration(std::uint64_t iterations, Body body) { + auto const start = std::chrono::steady_clock::now(); + for (std::uint64_t i = 0; i < iterations; ++i) { + body(i); + } + std::chrono::duration const elapsed = + std::chrono::steady_clock::now() - start; + return elapsed.count() / static_cast(iterations); +} + +// A part's runs, each less the empty loop's median: their median, fastest and slowest. +struct summary { + double median = 0; + double fastest = 0; + double slowest = 0; +}; + +summary summarise(std::array values, double loop) { + std::ranges::sort(values); + return { + .median = values[runs / 2] - loop, + .fastest = values.front() - loop, + .slowest = values.back() - loop, + }; +} + +// What one measurement gives: the guard's three costs, and whether DIT was as the guard must leave +// it before and after each part. +struct result { + summary clear; + summary set; + summary disengaged; + bool restored = true; +}; + +result measure(std::uint64_t iterations) { + std::array empty{}; + std::array clear{}; + std::array set{}; + std::array disengaged{}; + // A process that starts with DIT set would measure the set part twice. + bool restored = !detail::dit_is_set(); + // Written by every iteration of every part, so that no loop is removed or merged. + std::uint64_t volatile sink = 0; + // The disengaged guard's flag, read at each iteration as a keyed function reads its member. + bool volatile keyed = false; + for (std::size_t run = 0; run < runs; ++run) { + empty[run] = nanoseconds_per_iteration(iterations, [&sink](std::uint64_t i) { sink = i; }); + clear[run] = nanoseconds_per_iteration(iterations, [&sink](std::uint64_t i) { + detail::timing_guard const guard; + sink = i; + }); + restored = restored && !detail::dit_is_set(); + force_dit(true); + set[run] = nanoseconds_per_iteration(iterations, [&sink](std::uint64_t i) { + detail::timing_guard const guard; + sink = i; + }); + restored = restored && detail::dit_is_set() == guard_sets_dit(); + force_dit(false); + restored = restored && !detail::dit_is_set(); + disengaged[run] = nanoseconds_per_iteration(iterations, [&sink, &keyed](std::uint64_t i) { + detail::timing_guard const guard{keyed}; + sink = i; + }); + restored = restored && !detail::dit_is_set(); + } + double const loop = summarise(empty, 0).median; + return { + .clear = summarise(clear, loop), + .set = summarise(set, loop), + .disengaged = summarise(disengaged, loop), + .restored = restored, + }; +} + +// Writes the JSON line of a measurement into line; the number of characters, or -1. +int format(std::span line, result const& measured, std::uint64_t iterations) { + return std::snprintf( + line.data(), line.size(), + R"({"dit": %s, "clear": %.3f, "set": %.3f, "disengaged": %.3f, "clear_fastest": %.3f, )" + R"("clear_slowest": %.3f, "set_fastest": %.3f, "set_slowest": %.3f, )" + R"("disengaged_fastest": %.3f, "disengaged_slowest": %.3f, )" + R"("iterations": %llu, "runs": %zu, "target": "%.*s", "compiler": "%.*s"})", + guard_sets_dit() ? "true" : "false", measured.clear.median, measured.set.median, + measured.disengaged.median, measured.clear.fastest, measured.clear.slowest, + measured.set.fastest, measured.set.slowest, measured.disengaged.fastest, + measured.disengaged.slowest, static_cast(iterations), runs, + static_cast(target.size()), target.data(), static_cast(compiler.size()), + compiler.data()); +} + +// Skips prefix at the start of text, or returns null when text does not start with it. +char const* skip(char const* text, std::string_view prefix) { + return text != nullptr && std::string_view(text).starts_with(prefix) ? text + prefix.size() + : nullptr; +} + +// Reads a finite number at the start of text into value; what follows it, or null. +char const* number(char const* text, double& value) { + if (text == nullptr) { + return nullptr; + } + char* end = nullptr; + value = std::strtod(text, &end); + return end != text && std::isfinite(value) ? end : nullptr; +} + +// Whether line opens with the form collect.py reads: "dit" as the library reads it, then the three +// costs as finite numbers. +bool well_formed(char const* line) { + double clear = 0; + double set = 0; + double disengaged = 0; + char const* rest = + skip(line, guard_sets_dit() ? R"({"dit": true, "clear": )" : R"({"dit": false, "clear": )"); + rest = number(skip(number(rest, clear), R"(, "set": )"), set); + rest = number(skip(rest, R"(, "disengaged": )"), disengaged); + return skip(rest, R"(, "clear_fastest": )") != nullptr; +} + +int usage() { + static_cast(std::fprintf(stderr, "usage: timing [--measure]\n")); + return 2; +} + +} // namespace + +int main(int argument_count, char** arguments) { + std::span const given(arguments, static_cast(argument_count)); + bool const measuring = given.size() == 2 && std::string_view(given[1]) == "--measure"; + if (given.size() != 1 && !measuring) { + return usage(); + } + std::uint64_t const iterations = measuring ? measured_iterations : checked_iterations; + result const measured = measure(iterations); + std::array line{}; + int const written = format(line, measured, iterations); + if (written < 0 || static_cast(written) >= line.size()) { + static_cast(std::fprintf(stderr, "timing: the line does not fit\n")); + return 1; + } + std::printf("%s\n", line.data()); + if (!measured.restored) { + static_cast(std::fprintf( + stderr, "timing: the thread's DIT was set at the start or not restored by a guard\n")); + } + if (measuring) { + return measured.restored ? 0 : 1; + } + bool const formed = well_formed(line.data()); + std::printf("form %s\nstate restored %s\n", formed ? "ok" : "FAILED", + measured.restored ? "ok" : "FAILED"); + return formed && measured.restored ? 0 : 1; +} diff --git a/doc/async.adoc b/doc/async.adoc index bc748b7..b6cfe4a 100644 --- a/doc/async.adoc +++ b/doc/async.adoc @@ -43,6 +43,16 @@ Each runs, by default, on the synchronous function's backend (<>): `backends::webcrypto`, the browser's WebCrypto, is used only when the type names it, on Emscripten (<>). +An asynchronous function sets DIT (data-independent timing) where its +synchronous function does (<>), on the thread that +computes: a heavy function's synchronous function runs on a thread of the +executor's pool, inside its own guard, and gives that thread its DIT back +when it returns; a cheap one's runs at once on the calling thread, inside its +guard. The initiating function holds no guard of its own, and +`async_digest` computes an unkeyed digest, which sets none. On +`backends::webcrypto` the browser's JavaScript engine computes, on a target +where the guard does nothing, and nothing is added. + [#hash-async-heavy] === The heavy functions on another thread diff --git a/doc/backends.adoc b/doc/backends.adoc index b2d2d40..d0fd2e2 100644 --- a/doc/backends.adoc +++ b/doc/backends.adoc @@ -1806,6 +1806,28 @@ states about its constant time. The backends: | native, emscripten |=== +[#hash-backends-dit] +=== Data-independent timing (DIT) + +64-bit ARM's DIT (data-independent timing) bit, PSTATE.DIT, makes the instructions Arm lists take a time independent of their data, and Apple requires it of constant-time code (link:https://developer.apple.com/documentation/xcode/writing-arm64-code-for-apple-platforms#Enable-DIT-for-constant-time-cryptographic-operations[Apple, enable DIT for constant-time cryptographic operations]). None of the libraries hash calls sets it, so hash does: every function that computes on a key, a password or a key derivation's secret input runs its whole body inside `detail::timing_guard`, on every backend, which on 64-bit ARM under macOS, iOS, Linux and Android, where the CPU has FEAT_DIT (`hw.optional.arm.FEAT_DIT` on Apple's systems, `HWCAP_DIT` on Linux), sets DIT for the call and returns with the thread's DIT as it found it: clear when it was clear, set when the program set it itself (Apple's `timingsafe_enable_if_supported`) or an outer call did. An error and an exception leave it as found too, and DIT is a thread's own state, so a call never changes another thread's. A program does nothing. Elsewhere the guard executes no instruction: on x86 the counterpart, DOITM, is a register only the kernel writes; on WebAssembly the engine decides; on Windows on ARM64 no documented way to ask whether the CPU has FEAT_DIT was found, and DIT's instructions trap on a CPU without it. + +The functions that set DIT, on every backend of their cells: + +* MACs: `mac`, `mac`, `mac`, `mac`, `mac`, `mac`, `mac>`, `mac>`, `mac>`, `mac>`, `mac>`, `mac>`, `mac>`, `mac>`, `mac>`, `mac>`, `mac>`, `mac>`, `mac>`, `mac>`, `mac>`, `mac>`, `mac>`, `mac>`, `mac>`, `mac>`, `mac>`, `mac>`, `mac>` and `mac>`. +* Key derivation: `hkdf_extract`, `hkdf_expand`, `hkdf`, `pbkdf2`, `blake2b_subkey`, `kbkdf`, `sskdf` and `x963kdf`. +* Password hashing: `argon2id`, `argon2`, `argon2`, `argon2`, `scrypt`, `bcrypt` and `bcrypt_pbkdf`. +* Keyed by their arguments: `digest_of` and `hasher` (`make`, `update`, `finish`) when the options carry a key; the `blake3` class in its keyed, key-derivation and seeded keyed modes (a non-empty byte seed, a non-zero integer seed: BLAKE3's keyed hash): `keyed`, `derive_key`, those constructors, and `update`, `result`, `squeeze` and `reset` of such an object; `bcrypt_verify`. Called without a key, they hold a disengaged guard, which reads its flag and does nothing else. + +The functions that do not: + +* Unkeyed digests and extendable-output functions, through `digest_of`, `hasher` and the types of Boost.Hash2's form (`keccak_256`, `blake3` in its plain mode): their input is not a secret by their contract (a program that derives from a secret uses a MAC or a key derivation, which set DIT); they are the streaming case, where a guard per `update` of every checksum would cost a real fraction of a short chunk for no secret; and the same algorithm is also Boost.Hash2's own type by alias, which hash cannot guard, so that guarding one spelling would make the protection depend on the spelling. +* Boost.Hash2's types by alias, `siphash_32`, `siphash_64`, `hmac`, `hmac_md5_128`, `hmac_sha1_160`, `hmac_sha2_224`, `hmac_sha2_256`, `hmac_sha2_384`, `hmac_sha2_512`, `hmac_sha2_512_224`, `hmac_sha2_512_256`, `hmac_sha3_224`, `hmac_sha3_256`, `hmac_sha3_384`, `hmac_sha3_512`, `hmac_ripemd_128`, `hmac_ripemd_160`, `hmac_blake2b_512` and `hmac_blake2s_256`: they are Boost.Hash2's own classes, and a guard inside them would need a type of hash's in place of the alias. An HMAC with DIT is `mac>`, which runs the same Boost.Hash2 code on `backends::hash2` inside its guard; a program that calls `hmac` directly sets DIT itself. HKDF and PBKDF2 on `backends::hash2` run Boost.Hash2's `hmac` inside their own guard. +* The initiating functions of `async.hpp`: they check sizes and post, and the synchronous function they call sets DIT on the thread that computes, a thread of the work executor's pool for a heavy function, the caller's for a cheap one (<>). On `backends::webcrypto` the browser's JavaScript engine computes, and nothing is added. + +A coverage test per backend (`test/timing_coverage__test.cpp`) reads this table and fails when a keyed cell of its backend has no call, when a call enters no guard, when the first guard it enters is not its own function's, or when it leaves DIT otherwise than it found it; it checks that the unkeyed functions enter none. The guard is hash's own copy of webcpp::crypto's, which depends on hash: a change to one is a change to the other, and crypto's test `timing_hash_interop_test` runs both nested, in either order. + +What the guard adds to a call, measured from a release build, is in <>. + === The default backends The backend a call that names none uses, on every target, whatever the program links (<>): diff --git a/doc/changelog.adoc b/doc/changelog.adoc index c7e2768..d51316a 100644 --- a/doc/changelog.adoc +++ b/doc/changelog.adoc @@ -17,7 +17,7 @@ of every version are on webcpp's index page. // tag::unreleased[] * Added the library: Boost.Hash2's algorithms and HMAC under webcpp::hash's names, keccak_256 (Ethereum's Keccak-256 over XKCP), blake3 (keyed, key derivation, extendable output), every result `+[[nodiscard]]+`. -* Added HKDF (RFC 5869) and PBKDF2 (RFC 8018) over Boost.Hash2's hmacs on hash2; argon2id (RFC 9106) with libsodium's presets, scrypt (RFC 7914) and argon2's Argon2i and Argon2id on sodium. +* Added HKDF (RFC 5869) and PBKDF2 (RFC 8018) on hash2, argon2id (RFC 9106) with libsodium's presets, scrypt (RFC 7914) and argon2's Argon2i on sodium; keyed calls set DIT on arm64. * Added backends::openssl (OpenSSL 3.5.9; native, wasip2, wasip3), named in the call: its digests, MACs and key derivations. * Added backends::botan: Botan 3.14.1's hashes, MACs, key derivations and bcrypt, with exceptions. * Added backends::sodium's HKDF over HMAC-SHA-256/512, BLAKE2b with key, salt, personalisation and length, keyed BLAKE2b (macs::blake2b_mac), SipHash-2-4, SipHash-2-4x, blake2b_subkey, SHA-256/512, SHA3-256/512, SHAKE, TurboSHAKE with its domain byte, and HMAC-SHA-256/512. diff --git a/doc/digests.adoc b/doc/digests.adoc index 520cc1d..aa8802e 100644 --- a/doc/digests.adoc +++ b/doc/digests.adoc @@ -25,6 +25,23 @@ finds another input with the digest of a given one). A digest of 256 bits gives 128-bit collision resistance, which no computer will reach; the "Security" column below gives each function's. +A digest sets no DIT. hash sets 64-bit ARM's DIT (data-independent timing) +around every call that computes on a key, a password or a key derivation's +secret input (<>), and a digest's input is not a secret by +its contract: a program that must keep a value secret and derive from it uses +a MAC or a key derivation. A digest is also the streaming case, called once +per chunk, often per network read, where a guard per call would cost every +checksum a real part of a short chunk's time for no secret +(<>); and the same algorithm is also Boost.Hash2's +own type by alias, which hash cannot guard, so that a guard on one spelling +would make the protection depend on the spelling. The keyed modes are MACs +and set DIT: `digest_of` and `hasher` of `digests::blake2b` when the options +carry a key (<>), and `blake3` in its keyed, +key-derivation and seeded keyed modes (<>). Boost.Hash2's +`blake2b_512` and `blake2s_256` constructed with a key are its own types by +alias and set none: for a keyed BLAKE2 with DIT, use `mac` +or `digests::blake2b` with a key. + include::generated/compare-digests.adoc[] [#hash-sha2] @@ -423,7 +440,9 @@ same way on every side, since the library does not guess a padding. * *A key is a secret, the salt and personalisation are not.* For a MAC, use a random key of 16 to 64 bytes from `webcpp::crypto::random_device`, compare tags with `webcpp::crypto::equal`, and prefer `mac` -(<>); a key of 0 bytes is the unkeyed hash. +(<>); a key of 0 bytes is the unkeyed hash. With a +key, `digest_of` and each of `make`, `update` and `finish` of a `hasher` set +DIT around the call (<>); without one, none does. * *`backends::hash2` has BLAKE2b-512 alone.* Named in the call, it answers `unsupported_by_backend` to a shorter output, a key, a salt or a personalisation, rather than ignore one. @@ -470,6 +489,13 @@ The key material goes through `update`. * *The seeded constructor is a keyed hash.* `blake3(seed_value)` and `blake3(input_data, input_size)` exist for Boost.Hash2's HashAlgorithm form and key the hash with the seed; for a MAC, call `keyed` with a 32-byte key. +* *A keyed object sets DIT around each call; a plain one does not.* `keyed`, +`derive_key` and the seeded constructors with a seed that keys the hash (a +non-empty byte seed, a non-zero integer seed) set DIT +(<>), and so do `update`, `result`, `squeeze` and `reset` +of the object they make; the plain hash sets none. The flag that says which +is part of the object: 1,928 bytes on 64-bit targets, BLAKE3's state of 1,912 +bytes, the count of bytes `result()` returned and the flag. * *`blake3` does not wipe itself.* Like Hash2's types, it holds the key in its state until it is destroyed; a program that needs the key gone writes over the object. diff --git a/doc/kdfs.adoc b/doc/kdfs.adoc index 298477c..f0a6923 100644 --- a/doc/kdfs.adoc +++ b/doc/kdfs.adoc @@ -31,6 +31,14 @@ alone, and the key derivations of standards on OpenSSL or Botan, which are never a default: the call names one (<>). Each backend gives the same bytes for the same inputs: the tests check them against each other on random inputs on every target. +Every key derivation computes on a secret, and sets 64-bit ARM's DIT +(data-independent timing) around each call, on every backend, where the CPU +has it, leaving the thread's DIT as it found it (<>): +`hkdf_extract`, `hkdf_expand`, `hkdf`, `pbkdf2`, `blake2b_subkey`, `kbkdf`, +`sskdf` and `x963kdf`. `hkdf` enters one guard and runs the whole derivation +inside it, and HKDF and PBKDF2 on `backends::hash2` run Boost.Hash2's `hmac` +there too. + include::generated/compare-kdfs.adoc[] [#hash-hkdf] diff --git a/doc/llms.txt b/doc/llms.txt index 62dd4f9..c13a366 100644 --- a/doc/llms.txt +++ b/doc/llms.txt @@ -4,6 +4,8 @@ Primitives only: protocol steps (BIP39, hash160, EIP-55, Nostr ids, NIP-44) are what a domain library builds from these functions; the guide shows them as examples, never as this library's API. +Timing: every MAC, key derivation and password hash, and BLAKE2b's and BLAKE3's keyed modes, set 64-bit ARM's DIT (data-independent timing) around each call where the CPU has it, on every backend, and leave the thread's DIT as they found it; unkeyed digests and Boost.Hash2's hmac by alias do not, so an HMAC with DIT is mac>. [Section](https://webcpporg.github.io/libs/hash/#hash-backends-dit) + - [The guide](https://webcpporg.github.io/libs/hash/): every chapter, example and table - [Choose by use case](https://webcpporg.github.io/libs/hash/#hash-choose): a decision table, need to function, backend and example diff --git a/doc/macs.adoc b/doc/macs.adoc index 108552e..1b825ea 100644 --- a/doc/macs.adoc +++ b/doc/macs.adoc @@ -18,6 +18,12 @@ nor change a message and keep its tag. A MAC does not hide the message, and it does not prove to a third party who wrote it (both sides hold the key); that is a signature's job, webcpp::crypto's. +`mac` sets 64-bit ARM's DIT (data-independent timing) around each call, on +every backend, where the CPU has it, and leaves the thread's DIT as it found +it: a program does nothing (<>). Boost.Hash2's types that +hash names by alias, `hmac` and its `hmac_*` aliases, `siphash_32` and +`siphash_64`, set none (<>). + include::generated/compare-macs.adoc[] [#hash-hmac] @@ -60,6 +66,12 @@ first, which gives it no more strength. lets an attacker change the headers, the recipient or the order of messages; put a version, the context and a counter or timestamp inside the authenticated bytes, with an unambiguous encoding (lengths, not separators). +* *`hmac` and its aliases set no DIT; `mac` does.* They are Boost.Hash2's +own classes, which hash names by alias, and a guard inside them would need a +type of hash's in place of the one a program shares with Boost.Hash2's code. +For an HMAC with DIT on 64-bit ARM, call `mac>`, which runs the +same Boost.Hash2 code on `backends::hash2` inside its guard, or set DIT around +the computation yourself (Apple's `timingsafe_enable_if_supported`). * *Truncate only on purpose.* A tag cut to 16 bytes still gives 128 bits against forgery; one cut to 4 bytes gives an attacker a one-in-four-billion chance per try, which a busy server can reach. diff --git a/doc/measurements.throughput.json b/doc/measurements.throughput.json index 174cffe..f86e098 100644 --- a/doc/measurements.throughput.json +++ b/doc/measurements.throughput.json @@ -267,5 +267,43 @@ "max_ms": 1004.75, "key_correct": true } - ] + ], + "timing_guard": { + "measurement": "the nanoseconds detail::timing_guard adds to a call, bench/timing.cpp", + "date": "2026-11-22", + "machine": { + "cpu": "Apple M5 Max", + "architecture": "arm64", + "cores": 18, + "os": "Darwin 27.0.0" + }, + "load_average_before_after": [ + [ + 61.44970703125, + 270.64794921875, + 332.67626953125 + ], + [ + 61.44970703125, + 270.64794921875, + 332.67626953125 + ] + ], + "build": "variant=release optimization=speed", + "target": "native", + "compiler": "Apple LLVM 21.0.0 (clang-2100.4.1.1)", + "iterations": 10000000, + "runs": 5, + "dit": true, + "clear_ns": 45.418, + "clear_fastest_ns": 44.81, + "clear_slowest_ns": 48.771, + "set_ns": 0.711, + "set_fastest_ns": 0.646, + "set_slowest_ns": 0.755, + "disengaged_ns": -0.006, + "disengaged_fastest_ns": -0.013, + "disengaged_slowest_ns": 0.099, + "provisional": true + } } diff --git a/doc/password_hashing.adoc b/doc/password_hashing.adoc index c047c9a..90fdc4f 100644 --- a/doc/password_hashing.adoc +++ b/doc/password_hashing.adoc @@ -26,6 +26,15 @@ default, and on OpenSSL or Botan where the call names `backends::openssl` or `backends::botan`. bcrypt and bcrypt_pbkdf, which only Botan has, close the chapter (<>). +Every function of this chapter, `bcrypt_verify` included, sets 64-bit ARM's +DIT (data-independent timing) around each call, on every backend, where the +CPU has it, and leaves the thread's DIT as it found it +(<>). DIT makes the time of the instructions Arm lists +independent of their data; it does not change what a function reads: Argon2d +and scrypt read memory at addresses that depend on the password, and bcrypt's +Blowfish indexes its tables by secret data, as each upstream states +(<>). + include::generated/compare-password-hashing.adoc[] [#hash-argon2id] diff --git a/doc/performance.adoc b/doc/performance.adoc index 2fd1ac3..1d1543c 100644 --- a/doc/performance.adoc +++ b/doc/performance.adoc @@ -7,7 +7,13 @@ // Generated by bench/collect.py from doc/measurements.throughput.json: do not edit. [#hash-performance] -== PBKDF2-HMAC-SHA-512 throughput +== Performance + +PBKDF2-HMAC-SHA-512's throughput per backend, and what the timing guard adds to a +keyed call, each measured from release builds. + +[#hash-performance-pbkdf2] +=== PBKDF2-HMAC-SHA-512 throughput How long each backend takes to derive 64 bytes by PBKDF2-HMAC-SHA-512 at 1,000,000 iterations, on each target where the backend exists. The figure that matters to a @@ -113,3 +119,50 @@ Every case derived the independent value (Python's hashlib.pbkdf2_hmac) on every backends::openssl does not exist on Emscripten; libsodium has no PBKDF2, so its row measures its HMAC-SHA-512 in PBKDF2's loop, written in the benchmark and never part of the library. + +[#hash-performance-timing] +=== The timing guard's cost + +Every keyed function (a MAC, a key derivation, a password hash, a keyed mode of +BLAKE2b or BLAKE3) runs inside `detail::timing_guard`, which on 64-bit ARM under +macOS, iOS, Linux and Android, where the CPU has FEAT_DIT, sets DIT (data-independent +timing) for the call and restores the thread's state after it +(<>): one `mrs`, and where DIT was clear, two `msr` each +followed by an `isb`. Elsewhere (x86, WebAssembly, Windows on ARM64) it executes no +instruction. A function keyed by its arguments, called without a key, holds a +disengaged guard, which reads its flag and does nothing else. + +Measured natively on 2026-11-22 (UTC) on Apple M5 Max +(arm64), Darwin 27.0.0, built with variant=release optimization=speed +by Apple LLVM 21.0.0 (clang-2100.4.1.1) (bench/timing.cpp): each row is the median of +5 runs of 10,000,000 guards around a store, with the +fastest and slowest run beside it, each minus the median of the same loop without the +guard, in nanoseconds per call; a figure that rounds to zero or below, the loop's +noise, shows as 0.0. +The guard sets DIT on this machine. The machine's 1, 5 and 15 minute load averages were 61/271/333 +before and 61/271/333 after, on 18 cores. + +NOTE: these figures are provisional. They were measured on a shared machine under load (the load averages above), and are measured again in a final measurement pass on a quiet machine, once the work in progress has merged; read them as an upper bound. + +[cols="2,4,1,1,1",options="header"] +|=== +| The thread's DIT on entry | What the guard does | Median (ns) | Fastest (ns) | Slowest (ns) + +| clear, as a program that sets nothing has it +| reads DIT, sets it, and clears it on the way out +| 45.4 +| 44.8 +| 48.8 + +| already set, by the program or by an outer guard +| reads DIT and leaves it set +| 0.7 +| 0.6 +| 0.8 + +| any: a function keyed by its arguments, called without a key +| reads its flag and does nothing else +| 0.0 +| 0.0 +| 0.1 +|=== From 0b0bfeb554ef2e10d5bae028e71fc3e6543c9cc3 Mon Sep 17 00:00:00 2001 From: R Date: Sun, 22 Nov 2026 09:13:17 -0300 Subject: [PATCH 13/27] hash: the DIT pages name the built platforms and synchronous backends, bcrypt_verify among the password hashes, and collect.py dates every measurement in UTC and replaces data it cannot keep --- bench/collect.py | 73 ++++++++++++++++++++++----------------- doc/backends.adoc | 8 ++--- doc/changelog.adoc | 2 +- doc/kdfs.adoc | 6 ++-- doc/llms.txt | 2 +- doc/macs.adoc | 6 ++-- doc/password_hashing.adoc | 8 ++--- 7 files changed, 58 insertions(+), 47 deletions(-) diff --git a/bench/collect.py b/bench/collect.py index 1b76c36..e29923b 100755 --- a/bench/collect.py +++ b/bench/collect.py @@ -33,17 +33,18 @@ the data. The timing guard's cost (detail::timing_guard, which every keyed function holds and which sets -64-bit ARM's DIT where the CPU has it) is `timing --measure`'s one line: whether the guard sets -DIT on this machine, and the nanoseconds a guard adds to a call entered from a thread whose DIT -is clear, from one where it is already set, and a disengaged guard's (an unkeyed call of a -function keyed by its arguments), each the median of five runs of 10^7 guards minus an empty -loop's, with the fastest and slowest run. The data keeps it under "timing_guard" with the date -(UTC's), the machine and the load; the page renders it as a paragraph and a table after the -throughput. A line or a "timing_guard" that is not the form this script writes (an older -program's, a key missing or of another type) is refused with a message naming what is wrong, -before anything is written. `--provisional` marks the guard's figures as provisional, measured -on a shared, loaded machine and to be measured again in a final pass on a quiet one, which the -page says; measuring the guard without it clears the mark. +64-bit ARM's DIT where the CPU has it) is `timing --measure`'s one line: whether the guard sets DIT +on this machine, and the nanoseconds a guard adds to a call entered from a thread whose DIT is +clear, from one where it is already set, and a disengaged guard's (an unkeyed call of a function +keyed by its arguments), each the median of five runs of 10^7 guards minus an empty loop's, with the +fastest and slowest run. The data keeps it under "timing_guard" with the date, the machine and the +load (every date of the data is UTC's); the page renders it as a paragraph and a table after the +throughput. A line or a "timing_guard" that is not the form this script writes (an older program's, +a key missing or of another type) is refused with a message naming what is wrong, before anything is +written. `--provisional` marks the guard's figures as provisional, measured on a shared, loaded +machine and to be measured again in a final pass on a quiet one, which the page says; measuring the +guard without it clears the mark. `--exe` alone keeps the data's guard when the data is what this +script writes, and otherwise replaces the data, saying the guard was not kept. """ import argparse @@ -201,7 +202,7 @@ def measure(exes, invocations): peak = max(loads[0][0], loads[1][0]) return { "measurement": "pbkdf2-hmac-sha-512, 1,000,000 iterations, 64 bytes", - "date": datetime.date.today().isoformat(), + "date": utc_today(), "machine": machine(), "load_average_before_after": [list(loads[0]), list(loads[1])], "loaded": peak > cores, @@ -253,7 +254,7 @@ def wrong(value, shape, where): def utc_today(): - """Today's date in UTC, the date the guard's measurement states.""" + """Today's date in UTC, the date every measurement of the page states.""" return datetime.datetime.now(datetime.timezone.utc).date().isoformat() @@ -464,29 +465,36 @@ def render(data, page): f.write("\n".join(lines)) -def read_release_data(path): - """The data at path; exits when it cannot be read, or when it, or its guard's measurement, - was not built at BUILD or is not the form this script writes.""" +def release_data(path): + """The data at path and None, or None and what is wrong with it: it cannot be read, or it, or + its guard's measurement, was not built at BUILD or is not the form this script writes.""" try: with open(path, encoding="utf-8") as f: data = json.load(f) except (OSError, ValueError) as error: - sys.exit(f"collect.py: {path} cannot be read ({error}); --timing alone and --render-only " - "read the data that --exe wrote") + return None, (f"{path} cannot be read ({error}); --timing alone and --render-only read " + "the data that --exe wrote") if not isinstance(data, dict) or data.get("build") != BUILD: build = data.get("build") if isinstance(data, dict) else None - sys.exit(f"collect.py: {path} was measured with build {build}, not {BUILD}: " - f"{RELEASE_ONLY}") + return None, f"{path} was measured with build {build}, not {BUILD}: {RELEASE_ONLY}" timing = data.get("timing_guard") if timing is not None: if not isinstance(timing, dict) or timing.get("build") != BUILD: build = timing.get("build") if isinstance(timing, dict) else None - sys.exit(f"collect.py: {path}'s timing guard was measured with build {build}, not " - f"{BUILD}: {RELEASE_ONLY}") + return None, (f"{path}'s timing guard was measured with build {build}, not {BUILD}: " + f"{RELEASE_ONLY}") found = wrong(timing, TIMING_SHAPE, "data.timing_guard") if found is not None: - sys.exit(f"collect.py: {path} is not the data collect.py writes: {found} is wrong; " - "measure the guard again with --timing") + return None, (f"{path} is not the data collect.py writes: {found} is wrong; measure " + "the guard again with --timing") + return data, None + + +def read_release_data(path): + """The data at path; exits naming what is wrong with it (release_data).""" + data, fault = release_data(path) + if data is None: + sys.exit(f"collect.py: {fault}") return data @@ -513,15 +521,18 @@ def main(): if not exes and args.timing is None: sys.exit("collect.py: nothing to measure: give --exe, --timing or --render-only") check_release({**exes, **({"timing": args.timing} if args.timing else {})}) - kept = read_release_data(args.data) if (not exes or args.timing is None) and \ - Path(args.data).exists() else None if exes: data = measure(exes, args.invocations) - # The guard's cost is kept until it is measured again. - if kept is not None and kept.get("timing_guard") is not None: - data["timing_guard"] = kept["timing_guard"] - elif kept is not None: - data = kept + # The guard's cost is kept until it is measured again; data this script cannot keep + # is replaced by the new throughput, without a guard, and says so. + if args.timing is None and Path(args.data).exists(): + kept, fault = release_data(args.data) + if fault is not None: + print(f"collect.py: the guard is not kept: {fault}", file=sys.stderr) + elif kept is not None and kept.get("timing_guard") is not None: + data["timing_guard"] = kept["timing_guard"] + elif Path(args.data).exists(): + data = read_release_data(args.data) else: sys.exit(f"collect.py: {args.data} does not exist; --timing alone keeps the data's " "throughput, which --exe writes") diff --git a/doc/backends.adoc b/doc/backends.adoc index d0fd2e2..661e177 100644 --- a/doc/backends.adoc +++ b/doc/backends.adoc @@ -1809,14 +1809,14 @@ states about its constant time. The backends: [#hash-backends-dit] === Data-independent timing (DIT) -64-bit ARM's DIT (data-independent timing) bit, PSTATE.DIT, makes the instructions Arm lists take a time independent of their data, and Apple requires it of constant-time code (link:https://developer.apple.com/documentation/xcode/writing-arm64-code-for-apple-platforms#Enable-DIT-for-constant-time-cryptographic-operations[Apple, enable DIT for constant-time cryptographic operations]). None of the libraries hash calls sets it, so hash does: every function that computes on a key, a password or a key derivation's secret input runs its whole body inside `detail::timing_guard`, on every backend, which on 64-bit ARM under macOS, iOS, Linux and Android, where the CPU has FEAT_DIT (`hw.optional.arm.FEAT_DIT` on Apple's systems, `HWCAP_DIT` on Linux), sets DIT for the call and returns with the thread's DIT as it found it: clear when it was clear, set when the program set it itself (Apple's `timingsafe_enable_if_supported`) or an outer call did. An error and an exception leave it as found too, and DIT is a thread's own state, so a call never changes another thread's. A program does nothing. Elsewhere the guard executes no instruction: on x86 the counterpart, DOITM, is a register only the kernel writes; on WebAssembly the engine decides; on Windows on ARM64 no documented way to ask whether the CPU has FEAT_DIT was found, and DIT's instructions trap on a CPU without it. +64-bit ARM's DIT (data-independent timing) bit, PSTATE.DIT, makes the instructions Arm lists take a time independent of their data, and Apple requires it of constant-time code (link:https://developer.apple.com/documentation/xcode/writing-arm64-code-for-apple-platforms#Enable-DIT-for-constant-time-cryptographic-operations[Apple, enable DIT for constant-time cryptographic operations]). None of the libraries hash calls sets it, so hash does: every function that computes on a key, a password or a key derivation's secret input runs its whole body inside `detail::timing_guard`, on every synchronous backend, which on 64-bit ARM under macOS, iOS, Linux and Android, where the CPU has FEAT_DIT (`hw.optional.arm.FEAT_DIT` on Apple's systems, `HWCAP_DIT` on Linux), sets DIT for the call and returns with the thread's DIT as it found it: clear when it was clear, set when the program set it itself (Apple's `timingsafe_enable_if_supported`) or an outer call did. An error and an exception leave it as found too, and DIT is a thread's own state, so a call never changes another thread's. A program does nothing. Elsewhere the guard executes no instruction: on x86 the counterpart, DOITM, is a register only the kernel writes; on WebAssembly the engine decides; on Windows on ARM64 no documented way to ask whether the CPU has FEAT_DIT was found, and DIT's instructions trap on a CPU without it. -The functions that set DIT, on every backend of their cells: +The functions that set DIT, on every synchronous backend of their cells: * MACs: `mac`, `mac`, `mac`, `mac`, `mac`, `mac`, `mac>`, `mac>`, `mac>`, `mac>`, `mac>`, `mac>`, `mac>`, `mac>`, `mac>`, `mac>`, `mac>`, `mac>`, `mac>`, `mac>`, `mac>`, `mac>`, `mac>`, `mac>`, `mac>`, `mac>`, `mac>`, `mac>`, `mac>` and `mac>`. * Key derivation: `hkdf_extract`, `hkdf_expand`, `hkdf`, `pbkdf2`, `blake2b_subkey`, `kbkdf`, `sskdf` and `x963kdf`. -* Password hashing: `argon2id`, `argon2`, `argon2`, `argon2`, `scrypt`, `bcrypt` and `bcrypt_pbkdf`. -* Keyed by their arguments: `digest_of` and `hasher` (`make`, `update`, `finish`) when the options carry a key; the `blake3` class in its keyed, key-derivation and seeded keyed modes (a non-empty byte seed, a non-zero integer seed: BLAKE3's keyed hash): `keyed`, `derive_key`, those constructors, and `update`, `result`, `squeeze` and `reset` of such an object; `bcrypt_verify`. Called without a key, they hold a disengaged guard, which reads its flag and does nothing else. +* Password hashing: `argon2id`, `argon2`, `argon2`, `argon2`, `scrypt`, `bcrypt`, `bcrypt_verify` and `bcrypt_pbkdf`. +* Keyed by their arguments: `digest_of` and `hasher` (`make`, `update`, `finish`) when the options carry a key; the `blake3` class in its keyed, key-derivation and seeded keyed modes (a non-empty byte seed, a non-zero integer seed: BLAKE3's keyed hash): `keyed`, `derive_key`, those constructors, and `update`, `result`, `squeeze` and `reset` of such an object. Called without a key, they hold a disengaged guard, which reads its flag and does nothing else. The functions that do not: diff --git a/doc/changelog.adoc b/doc/changelog.adoc index d51316a..e1330aa 100644 --- a/doc/changelog.adoc +++ b/doc/changelog.adoc @@ -17,7 +17,7 @@ of every version are on webcpp's index page. // tag::unreleased[] * Added the library: Boost.Hash2's algorithms and HMAC under webcpp::hash's names, keccak_256 (Ethereum's Keccak-256 over XKCP), blake3 (keyed, key derivation, extendable output), every result `+[[nodiscard]]+`. -* Added HKDF (RFC 5869) and PBKDF2 (RFC 8018) on hash2, argon2id (RFC 9106) with libsodium's presets, scrypt (RFC 7914) and argon2's Argon2i on sodium; keyed calls set DIT on arm64. +* Added HKDF (RFC 5869) and PBKDF2 (RFC 8018) on hash2, argon2id (RFC 9106), scrypt and argon2's Argon2i and Argon2id on sodium; keyed calls set DIT on arm64 Apple and Linux. * Added backends::openssl (OpenSSL 3.5.9; native, wasip2, wasip3), named in the call: its digests, MACs and key derivations. * Added backends::botan: Botan 3.14.1's hashes, MACs, key derivations and bcrypt, with exceptions. * Added backends::sodium's HKDF over HMAC-SHA-256/512, BLAKE2b with key, salt, personalisation and length, keyed BLAKE2b (macs::blake2b_mac), SipHash-2-4, SipHash-2-4x, blake2b_subkey, SHA-256/512, SHA3-256/512, SHAKE, TurboSHAKE with its domain byte, and HMAC-SHA-256/512. diff --git a/doc/kdfs.adoc b/doc/kdfs.adoc index f0a6923..c89d1d8 100644 --- a/doc/kdfs.adoc +++ b/doc/kdfs.adoc @@ -31,9 +31,9 @@ alone, and the key derivations of standards on OpenSSL or Botan, which are never a default: the call names one (<>). Each backend gives the same bytes for the same inputs: the tests check them against each other on random inputs on every target. -Every key derivation computes on a secret, and sets 64-bit ARM's DIT -(data-independent timing) around each call, on every backend, where the CPU -has it, leaving the thread's DIT as it found it (<>): +Every key derivation computes on a secret, and sets DIT (data-independent +timing) around each call, on every synchronous backend, on 64-bit ARM under +Apple's systems and Linux where the CPU has FEAT_DIT, leaving the thread's DIT as it found it (<>): `hkdf_extract`, `hkdf_expand`, `hkdf`, `pbkdf2`, `blake2b_subkey`, `kbkdf`, `sskdf` and `x963kdf`. `hkdf` enters one guard and runs the whole derivation inside it, and HKDF and PBKDF2 on `backends::hash2` run Boost.Hash2's `hmac` diff --git a/doc/llms.txt b/doc/llms.txt index c13a366..e3b0366 100644 --- a/doc/llms.txt +++ b/doc/llms.txt @@ -4,7 +4,7 @@ Primitives only: protocol steps (BIP39, hash160, EIP-55, Nostr ids, NIP-44) are what a domain library builds from these functions; the guide shows them as examples, never as this library's API. -Timing: every MAC, key derivation and password hash, and BLAKE2b's and BLAKE3's keyed modes, set 64-bit ARM's DIT (data-independent timing) around each call where the CPU has it, on every backend, and leave the thread's DIT as they found it; unkeyed digests and Boost.Hash2's hmac by alias do not, so an HMAC with DIT is mac>. [Section](https://webcpporg.github.io/libs/hash/#hash-backends-dit) +Timing: every MAC, key derivation and password hash, and BLAKE2b's and BLAKE3's keyed modes, set DIT (data-independent timing) around each call on 64-bit ARM under Apple's systems and Linux where the CPU has FEAT_DIT, on every synchronous backend, and leave the thread's DIT as they found it; unkeyed digests and Boost.Hash2's hmac by alias do not, so an HMAC with DIT is mac>. [Section](https://webcpporg.github.io/libs/hash/#hash-backends-dit) - [The guide](https://webcpporg.github.io/libs/hash/): every chapter, example and table - [Choose by use case](https://webcpporg.github.io/libs/hash/#hash-choose): a decision table, need to function, backend and example diff --git a/doc/macs.adoc b/doc/macs.adoc index 1b825ea..f43adc7 100644 --- a/doc/macs.adoc +++ b/doc/macs.adoc @@ -18,9 +18,9 @@ nor change a message and keep its tag. A MAC does not hide the message, and it does not prove to a third party who wrote it (both sides hold the key); that is a signature's job, webcpp::crypto's. -`mac` sets 64-bit ARM's DIT (data-independent timing) around each call, on -every backend, where the CPU has it, and leaves the thread's DIT as it found -it: a program does nothing (<>). Boost.Hash2's types that +`mac` sets DIT (data-independent timing) around each call, on every +synchronous backend, on 64-bit ARM under Apple's systems and Linux where the +CPU has FEAT_DIT, and leaves the thread's DIT as it found it: a program does nothing (<>). Boost.Hash2's types that hash names by alias, `hmac` and its `hmac_*` aliases, `siphash_32` and `siphash_64`, set none (<>). diff --git a/doc/password_hashing.adoc b/doc/password_hashing.adoc index 90fdc4f..9acac3a 100644 --- a/doc/password_hashing.adoc +++ b/doc/password_hashing.adoc @@ -26,10 +26,10 @@ default, and on OpenSSL or Botan where the call names `backends::openssl` or `backends::botan`. bcrypt and bcrypt_pbkdf, which only Botan has, close the chapter (<>). -Every function of this chapter, `bcrypt_verify` included, sets 64-bit ARM's -DIT (data-independent timing) around each call, on every backend, where the -CPU has it, and leaves the thread's DIT as it found it -(<>). DIT makes the time of the instructions Arm lists +Every function of this chapter, `bcrypt_verify` included, sets DIT +(data-independent timing) around each call, on every synchronous backend, on +64-bit ARM under Apple's systems and Linux where the CPU has FEAT_DIT, and +leaves the thread's DIT as it found it (<>). DIT makes the time of the instructions Arm lists independent of their data; it does not change what a function reads: Argon2d and scrypt read memory at addresses that depend on the password, and bcrypt's Blowfish indexes its tables by secret data, as each upstream states From 2b6614925d0bfec87e3ee360f05bddff72dd4a81 Mon Sep 17 00:00:00 2001 From: R Date: Sun, 22 Nov 2026 09:28:24 -0300 Subject: [PATCH 14/27] hash: timing_during observes DIT set while hkdf_extract, hkdf_expand, hkdf, pbkdf2, mac and async_pbkdf2 compute, through a Hash2-form probe under their hmac --- test/Jamfile | 9 ++ test/timing_during_test.cpp | 295 ++++++++++++++++++++++++++++++++++++ 2 files changed, 304 insertions(+) create mode 100644 test/timing_during_test.cpp diff --git a/test/Jamfile b/test/Jamfile index 154c84d..5c28150 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -723,6 +723,15 @@ botan-run timing_async_botan : timing_async_test.cpp WEBCPP_TEST_TIMING_ASYNC_BOTAN emscripten:-sPTHREAD_POOL_SIZE=3 ; +# DIT is set while a keyed function computes: a Hash2-form probe records DIT at +# each update under the hmac of hkdf_extract, hkdf_expand, hkdf, pbkdf2 and mac; +# timing_during_async the same through async_pbkdf2, on the pool's thread. +hash-run timing_during : timing_during_test.cpp ; +hash-run timing_during_async : timing_during_test.cpp + : /webcpp/asio//asio multi WEBCPP_TEST_TIMING_DURING_ASYNC + emscripten:-sPTHREAD_POOL_SIZE=2 + : native emscripten ; + # mac and the keyed modes of BLAKE2b (digest_of, hasher with a key) and of # BLAKE3 (keyed, derive_key and the seeds that key) hold detail::timing_guard; a # call that is not keyed holds none; no output changes. diff --git a/test/timing_during_test.cpp b/test/timing_during_test.cpp new file mode 100644 index 0000000..e5f373f --- /dev/null +++ b/test/timing_during_test.cpp @@ -0,0 +1,295 @@ +// 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 set while a keyed function computes (design D1; spec scenario "A password derived on +// Apple silicon"): a Boost.Hash2-form hash, dit_probe, records at each update whether DIT was set +// and whether a detail::timing_guard had been entered, and runs as the hash under the hmac of +// hkdf_extract, hkdf_expand, hkdf and pbkdf2 on backends::hash2, and of mac on a stand-in backend +// whose HMAC-SHA-256 is backends::hash2's over the probe. From a thread with DIT clear, every +// update the probe saw ran after a guard was entered and, where the CPU has DIT, with DIT set (and +// clear where it has none); the thread finds DIT clear after the call. A guard that the engine +// call precedes, or one written as a temporary, fails here. With WEBCPP_TEST_TIMING_DURING_ASYNC, +// the same through async_pbkdf2 on a webcpp::asio::thread_pool of one thread, the probe's record +// read on the pool's thread, which computes. + +#include "support/timing_seam.hpp" + +#include +#include +#include +#include +#include +#include +#ifdef WEBCPP_TEST_TIMING_DURING_ASYNC +#include + +#include +#include +#include +#include + +#include + +#include +#endif +#include + +#include +#include + +#include +#include +#include +#include +#include + +namespace webcpp::test { +namespace { + +/** What dit_probe saw on this thread since probe_reset. */ +struct probe_record { + /** The updates it ran. */ + std::size_t updates = 0; + /** The updates it ran with DIT clear. */ + std::size_t updates_clear = 0; + /** The updates it ran before any detail::timing_guard was entered. */ + std::size_t updates_unguarded = 0; +}; + +/** What dit_probe saw on this thread. */ +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables): what the probe records +thread_local probe_record probe_seen; + +/** Clears the probe's record and the seam's counter of this thread. */ +void probe_reset() noexcept { + probe_seen = {}; + timing_entries = 0; + timing_first_entry = nullptr; +} + +/** + * SHA-256 in Boost.Hash2's form whose every update records, before it hashes, whether DIT is set + * and whether a detail::timing_guard has been entered on this thread since probe_reset. + */ +class dit_probe { +public: + /** The block size, SHA-256's. */ + static constexpr std::size_t block_size = boost::hash2::sha2_256::block_size; + /** The result, SHA-256's. */ + using result_type = boost::hash2::sha2_256::result_type; + + /** SHA-256 unseeded. */ + dit_probe() = default; + + /** + * SHA-256 seeded by an integer, as Hash2's. + * + * @param seed The seed. + */ + explicit dit_probe(std::uint64_t seed) : inner_(seed) {} + + /** + * SHA-256 seeded by bytes, as Hash2's. + * + * @param seed The seed. @param size Its size. + */ + dit_probe(void const* seed, std::size_t size) : inner_(seed, size) {} + + /** + * Records the update, then hashes `size` bytes at `data`. + * + * @param data The bytes. @param size Their number. + */ + void update(void const* data, std::size_t size) { + ++probe_seen.updates; + if (!webcpp::hash::detail::dit_is_set()) { + ++probe_seen.updates_clear; + } + if (timing_entries == 0) { + ++probe_seen.updates_unguarded; + } + inner_.update(data, size); + } + + /** @return SHA-256's result. */ + result_type result() { return inner_.result(); } + +private: + boost::hash2::sha2_256 inner_; +}; + +/** A backend whose HMAC-SHA-256 is backends::hash2's over dit_probe. */ +struct dit_probe_backend {}; + +} // namespace +} // namespace webcpp::test + +namespace webcpp::hash::detail { + +/** HMAC-SHA-256 on the probe's backend: backends::hash2's engine, over dit_probe. */ +template <> +struct mac_engine> + : hash2_hmac_engine {}; + +} // namespace webcpp::hash::detail + +namespace { + +namespace hash = webcpp::hash; +namespace test = webcpp::test; +namespace backends = webcpp::hash::backends; + +using probe_hmac = hash::hmac; + +constexpr std::array key{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}; +constexpr std::array salt{16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1}; +constexpr std::array info{'c', 'o', 'n', 't', 'e', 'x', 't', 0}; + +/** + * 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. + */ +void force_dit([[maybe_unused]] bool set) { +#ifdef WEBCPP_HASH_DETAIL_TIMING_COVERED + if (!hash::detail::cpu_has_dit()) { + return; + } + hash::detail::write_dit(set ? hash::detail::dit_bit : 0); +#endif +} + +// Reports, by `name`, a probe that never ran, an update before any guard, an update with DIT +// other than the CPU gives under a guard, or a thread left with DIT set. +void check_record(std::string const& name, test::probe_record const& seen, bool dit_set_after) { + if (seen.updates == 0) { + BOOST_ERROR((name + ": the probe never ran").c_str()); + return; + } + if (seen.updates_unguarded != 0) { + BOOST_ERROR((name + ": " + std::to_string(seen.updates_unguarded) + " of " + + std::to_string(seen.updates) + " updates ran before any guard") + .c_str()); + } + std::size_t const expected_clear = hash::detail::cpu_has_dit() ? 0 : seen.updates; + if (seen.updates_clear != expected_clear) { + BOOST_ERROR((name + ": " + std::to_string(seen.updates_clear) + " of " + + std::to_string(seen.updates) + " updates ran with DIT clear") + .c_str()); + } + if (dit_set_after) { + BOOST_ERROR((name + ": DIT left set").c_str()); + } +} + +// Runs `call` from a thread with DIT clear, then checks what the probe saw during it. +template +void during(std::string const& name, Call call) { + force_dit(false); + test::probe_reset(); + call(); + check_record(name, test::probe_seen, hash::detail::dit_is_set()); +} + +void synchronous() { + during("hkdf_extract", [] { + BOOST_TEST((hash::hkdf_extract(salt, key)).has_value()); + }); + auto const prk = hash::hkdf_extract(salt, key); + if (!BOOST_TEST(prk.has_value())) { + return; + } + std::array okm{}; + during("hkdf_expand", [&] { + BOOST_TEST((hash::hkdf_expand(okm, *prk, info)).has_value()); + }); + during("hkdf", [&] { + BOOST_TEST((hash::hkdf(okm, salt, key, info)).has_value()); + }); + std::array derived{}; + during("pbkdf2", [&] { + BOOST_TEST((hash::pbkdf2(derived, key, salt, 3)).has_value()); + }); + // The probe computes SHA-256: pbkdf2 over it gives the bytes of pbkdf2 over hmac_sha2_256. + std::array plain{}; + BOOST_TEST( + (hash::pbkdf2(plain, key, salt, 3)).has_value()); + BOOST_TEST(derived == plain); + + std::array tag{}; + during("mac", [&] { + BOOST_TEST((hash::mac, test::dit_probe_backend>( + tag, key, info)) + .has_value()); + }); + std::array plain_tag{}; + BOOST_TEST((hash::mac, backends::hash2>(plain_tag, + key, info)) + .has_value()); + BOOST_TEST(tag == plain_tag); +} + +#ifdef WEBCPP_TEST_TIMING_DURING_ASYNC +namespace asio = webcpp::asio; + +// Runs `probe` on the pool's thread and waits for its answer through a future. +template +auto on_pool(asio::thread_pool& pool, Probe probe) { + std::promise answer; + auto future = answer.get_future(); + asio::post(pool, [&answer, &probe] { answer.set_value(probe()); }); + return future.get(); +} + +// async_pbkdf2 on a pool of one thread: the probe ran there, under the guard, with DIT set where +// the CPU has it; the record is read on the pool's thread after the completion. +void on_the_pool() { + asio::io_context context; + asio::thread_pool pool(1); + on_pool(pool, [] { + force_dit(false); + test::probe_reset(); + return true; + }); + test::probe_reset(); + std::array derived{}; + bool called = false; + boost::system::error_code code; + hash::async_pbkdf2( + pool.get_executor(), derived, key, salt, 3, + asio::bind_executor(context.get_executor(), [&](boost::system::error_code done) { + called = true; + code = done; + })); + context.run(); // lint-run: the test's event loop + BOOST_TEST(called); + BOOST_TEST(!code); + + // What the pool's thread recorded, and whether it was left with DIT set. + struct pool_state { + test::probe_record seen; + bool dit_set = false; + }; + + auto const worker = on_pool(pool, [] { + return pool_state{.seen = test::probe_seen, .dit_set = hash::detail::dit_is_set()}; + }); + check_record("async_pbkdf2 on the pool's thread", worker.seen, worker.dit_set); + // The calling thread computed nothing. + BOOST_TEST_EQ(test::probe_seen.updates, 0u); + BOOST_TEST(!hash::detail::dit_is_set()); + pool.join(); +} +#endif + +} // namespace + +int main() { + synchronous(); +#ifdef WEBCPP_TEST_TIMING_DURING_ASYNC + on_the_pool(); +#endif + return webcpp::test::exit_status(boost::report_errors()); +} From 1323a0f7ef87c6f3bb4d39888977d9bf0e2fd779 Mon Sep 17 00:00:00 2001 From: R Date: Sun, 22 Nov 2026 09:39:22 -0300 Subject: [PATCH 15/27] hash: the seam support's example names hash::hkdf_extract, the scope a check matches --- test/support/timing_seam.hpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/support/timing_seam.hpp b/test/support/timing_seam.hpp index 9742aed..a2354d3 100644 --- a/test/support/timing_seam.hpp +++ b/test/support/timing_seam.hpp @@ -81,7 +81,7 @@ struct named_function { * `(`, or by a space and words that say how it is called. * * The scope is the component before the identifier, empty when there is none. A check named - * `hkdf::hkdf_extract of a salt on hash2` names `hkdf::hkdf_extract`; + * `hash::hkdf_extract of a salt on hash2` names `hash::hkdf_extract`; * `blake3::update(void` names `blake3::update` with a parameter list that holds `void`. * * @param spelled The function as a check spells it. From 74d3fea80182f273def855e547f553f08cdd6f33 Mon Sep 17 00:00:00 2001 From: R Date: Sun, 22 Nov 2026 09:39:22 -0300 Subject: [PATCH 16/27] hash: blake3_test pins the documented sizes, 1,912 bytes of BLAKE3's state and 1,928 of the blake3 class on 64-bit targets --- test/blake3_test.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/test/blake3_test.cpp b/test/blake3_test.cpp index a3203ad..a4c1718 100644 --- a/test/blake3_test.cpp +++ b/test/blake3_test.cpp @@ -35,6 +35,10 @@ static_assert(std::is_copy_assignable_v); static_assert(blake3::block_size == 64); static_assert(blake3::key_size == 32); static_assert(std::is_same_v>); +// The size the documentation states (blake3.hpp, digests.adoc): BLAKE3's state of 1,912 bytes, a +// count and the keyed flag, 1,928 bytes on 64-bit targets; and BLAKE3's own state, 1,912. +static_assert(sizeof(void*) != 8 || sizeof(blake3_hasher) == 1912); +static_assert(sizeof(void*) != 8 || sizeof(blake3) == 1928); // n bytes of BLAKE3's keyed hash under key, of message, from position on, through the C API. template From b2d423c4b9a83821ddb48448598355c90e7855d0 Mon Sep 17 00:00:00 2001 From: R Date: Sun, 22 Nov 2026 09:39:22 -0300 Subject: [PATCH 17/27] hash: the coverage tests run every keyed cell again from a thread that set DIT itself, and take whether BLAKE2b takes a key from the table, the engine checked against it --- test/support/timing_coverage.hpp | 77 +++++++++++++++++++++++++++----- test/timing_keyed_test.cpp | 17 +------ 2 files changed, 69 insertions(+), 25 deletions(-) diff --git a/test/support/timing_coverage.hpp b/test/support/timing_coverage.hpp index 8860706..a45b590 100644 --- a/test/support/timing_coverage.hpp +++ b/test/support/timing_coverage.hpp @@ -67,6 +67,21 @@ namespace webcpp::test { +/** + * Sets or clears DIT for this thread, as a program can, so that a test starts from a known state; + * only where the CPU has DIT, since the instruction traps on a CPU without it. + * + * @param set Whether to set DIT. + */ +inline void force_dit([[maybe_unused]] bool set) noexcept { +#ifdef WEBCPP_HASH_DETAIL_TIMING_COVERED + if (!webcpp::hash::detail::cpu_has_dit()) { + return; + } + webcpp::hash::detail::write_dit(set ? webcpp::hash::detail::dit_bit : 0); +#endif +} + /** * Runs `call` and reports an error when it entered no detail::timing_guard, when the first guard * it entered is not the one of `function` (support/timing_seam.hpp), or when it left the thread's @@ -83,7 +98,8 @@ void covered(std::string const& name, std::string const& function, Call&& call) bool const before = webcpp::hash::detail::dit_is_set(); require_enters(name, function, std::forward(call)); if (webcpp::hash::detail::dit_is_set() != before) { - std::string const message = name + " left DIT other than it found it"; + std::string const message = name + (before ? " left DIT clear, though it found it set" + : " left DIT set, though it found it clear"); BOOST_ERROR(message.c_str()); } } @@ -175,6 +191,32 @@ inline bool table_has_cell(boost::json::value const& table, std::string_view row return false; } +/** + * Whether the table's cell of `digests::blake2b` on `backend` takes a key: the cell exists, and its + * "partial", when it has one, does not list "a key" among what the backend refuses. + * + * @param backend The backend's name. + * @return Whether the table says the backend takes a key. + */ +inline bool table_blake2b_takes_key(std::string_view backend) { + auto const table = capability_table(); + for (auto const& algorithm : table.at("algorithms").as_array()) { + for (auto const& function : algorithm.at("functions").as_array()) { + if (function.at("name").as_string() != "digests::blake2b") { + continue; + } + auto const* const cell = cell_of(function, backend); + if (cell == nullptr) { + return false; + } + auto const* const partial = cell->as_object().if_contains("partial"); + return partial == nullptr || !partial->is_string() || + std::string_view(partial->as_string()).find("a key") == std::string_view::npos; + } + } + return false; +} + /** The name of the keyed cell of BLAKE2b with a key, a keyed function of design D1. */ inline constexpr std::string_view keyed_blake2b_cell = "digests::blake2b keyed"; /** The name of the keyed cell of the blake3 type's keyed modes, a keyed function of design D1. */ @@ -244,7 +286,9 @@ inline std::vector keyed_cells(std::string_view backend) { /** * Reports each keyed cell of `backend` that `calls` does not cover and each call that names no - * keyed cell of it, then runs every call. + * keyed cell of it, then runs every call from a thread with DIT clear, and again from one that set + * DIT itself (where the CPU has DIT), as a program can: `covered` checks that each call leaves the + * thread's DIT as it found it, clear and set. The thread's DIT is clear after. * * @param backend The backend's name, as the table spells it. * @param calls The backend's coverage calls. @@ -259,14 +303,22 @@ inline void check_and_run(std::string_view backend, coverage_calls const& calls) BOOST_ERROR(message.c_str()); } } - for (auto const& [name, call] : calls) { - if (std::ranges::find(cells, name) == cells.end()) { + for (auto const& entry : calls) { + if (std::ranges::find(cells, entry.first) == cells.end()) { std::string const message = - name + " on " + std::string(backend) + " names no keyed cell"; + entry.first + " on " + std::string(backend) + " names no keyed cell"; BOOST_ERROR(message.c_str()); } - call(); } + force_dit(false); + for (auto const& entry : calls) { + entry.second(); + } + force_dit(true); + for (auto const& entry : calls) { + entry.second(); + } + force_dit(false); } /** @@ -801,16 +853,21 @@ std::optional> cover_keyed_blake2b_round( /** * BLAKE2b with a key on `Backend` (design D1): `digest_of`, then a hasher round, `make`, `update` * and `finish`, the round's digest the one of `digest_of`; on a backend whose cell refuses a key - * (its "partial": `backends::hash2`, `backends::openssl`), `digest_of` and `make` answer - * `unsupported_by_backend` and still enter the guard, which precedes every check. Then - * `digest_of` and `make` with a key of 65 bytes, which the guards refuse before the backend. + * (its "partial" lists "a key": `backends::hash2`, `backends::openssl`; the engine must agree), + * `digest_of` and `make` answer `unsupported_by_backend` and still enter the guard, which precedes + * every check. Then `digest_of` and `make` with a key of 65 bytes, which the guards refuse before + * the backend. */ template void cover_keyed_blake2b() { using hash::digests::blake2b; std::string const on = " of blake2b with a key" + coverage_on(); hash::digest_options const keyed{.key = coverage_key}; - bool const takes_key = hash::detail::digest_engine::accepts(keyed); + // The table says whether the backend takes a key; the engine must agree, so that a backend + // that stopped taking one fails here rather than passing through the refusal's branch. + bool const takes_key = table_blake2b_takes_key(name_of()); + bool const engine_takes_key = hash::detail::digest_engine::accepts(keyed); + BOOST_TEST_EQ(engine_takes_key, takes_key); std::array once{}; covered("hash::digest_of" + on, [&] { auto const done = hash::digest_of(once, coverage_input, keyed); diff --git a/test/timing_keyed_test.cpp b/test/timing_keyed_test.cpp index 13bcf0e..ecd1fc3 100644 --- a/test/timing_keyed_test.cpp +++ b/test/timing_keyed_test.cpp @@ -60,19 +60,6 @@ using webcpp::hash::blake3; using hmac_sha256 = macs::hmac; using blake2b_options = hash::digest_options; -/** - * Sets or clears DIT for this thread, as a program can, so that a test starts from a known state; - * only where the CPU has DIT, since the instruction traps on a CPU without it. - */ -void force_dit([[maybe_unused]] bool set) { -#ifdef WEBCPP_HASH_DETAIL_TIMING_COVERED - if (!detail::cpu_has_dit()) { - return; - } - detail::write_dit(set ? detail::dit_bit : 0); -#endif -} - constexpr std::array key = [] { std::array bytes{}; for (std::size_t i = 0; i < bytes.size(); ++i) { @@ -109,11 +96,11 @@ void mac_enters() { // Where the CPU has DIT: mac leaves it set when the program set it, and clear when it was clear. void mac_leaves_set_state() { std::array tag{}; - force_dit(true); + test::force_dit(true); BOOST_TEST_EQ(detail::dit_is_set(), detail::cpu_has_dit()); BOOST_TEST((hash::mac(tag, key, input)).has_value()); BOOST_TEST_EQ(detail::dit_is_set(), detail::cpu_has_dit()); - force_dit(false); + test::force_dit(false); BOOST_TEST(!detail::dit_is_set()); BOOST_TEST((hash::mac(tag, key, input)).has_value()); BOOST_TEST(!detail::dit_is_set()); From 09015e089acd6578f076fc7ccc36a4713ab304f1 Mon Sep 17 00:00:00 2001 From: R Date: Sun, 22 Nov 2026 09:39:23 -0300 Subject: [PATCH 18/27] hash: timing_async asserts async_bcrypt_verify's answer and checks heavy and cheap forms through one function --- test/timing_async_test.cpp | 72 ++++++++++++++++++++------------------ 1 file changed, 37 insertions(+), 35 deletions(-) diff --git a/test/timing_async_test.cpp b/test/timing_async_test.cpp index 88786b1..212e78a 100644 --- a/test/timing_async_test.cpp +++ b/test/timing_async_test.cpp @@ -105,9 +105,11 @@ void reset_this_thread() { } record read_this_thread() { - return {.entries = test::timing_entries, - .first = test::timing_first_entry != nullptr ? test::timing_first_entry : "", - .dit_off = !hash::detail::dit_is_set()}; + return { + .entries = test::timing_entries, + .first = test::timing_first_entry != nullptr ? test::timing_first_entry : "", + .dit_off = !hash::detail::dit_is_set(), + }; } // Runs a probe on the pool's thread and waits for its answer through a future. @@ -164,11 +166,15 @@ bool entered_first(record const& seen, std::string_view function) { return !seen.first.empty() && test::names_function(seen.first, test::function_named(function)); } -// A heavy form: the pool's thread enters the guard of `function` first, the calling thread none, -// and both threads are back to DIT off after the completion. +// The thread a form computes on: the pool's for a heavy form, the caller's (during the +// initiation) for a cheap one on a synchronous backend. +enum class computes_on { pool, caller }; + +// A form computing on `where`: that thread enters the guard of `function` first, the other none, +// and both threads are back to DIT off after the completion. Returns what the completion saw. template -void heavy(std::string_view name, std::string_view function, asio::io_context& context, - asio::thread_pool& pool, Start start) { +completion form_on(computes_on where, std::string_view name, std::string_view function, + asio::io_context& context, asio::thread_pool& pool, Start start) { reset_pool_thread(pool); reset_this_thread(); completion seen; @@ -176,38 +182,32 @@ void heavy(std::string_view name, std::string_view function, asio::io_context& c run_to_completion(context); record const caller = read_this_thread(); record const worker = read_pool_thread(pool); + record const& computing = where == computes_on::pool ? worker : caller; + record const& other = where == computes_on::pool ? caller : worker; std::string const label(name); expect(seen.called, label); expect(!seen.code, label + ": " + seen.code.message()); - expect(worker.entries >= 1, label); - expect(entered_first(worker, function), label + " entered " + worker.first); - expect(caller.entries == 0, - label + ": " + std::to_string(caller.entries) + " guards entered on the wrong thread"); + expect(computing.entries >= 1, label); + expect(entered_first(computing, function), label + " entered " + computing.first); + expect(other.entries == 0, + label + ": " + std::to_string(other.entries) + " guards entered on the wrong thread"); expect(worker.dit_off, label); expect(caller.dit_off, label); + return seen; } -// A cheap form on a synchronous backend: the calling thread enters the guard of `function` first -// during the initiation, the pool's thread none. +// A heavy form: the pool's thread computes. template -void cheap(std::string_view name, std::string_view function, asio::io_context& context, - asio::thread_pool& pool, Start start) { - reset_pool_thread(pool); - reset_this_thread(); - completion seen; - start(recording_handler(context, seen)); - run_to_completion(context); - record const caller = read_this_thread(); - record const worker = read_pool_thread(pool); - std::string const label(name); - expect(seen.called, label); - expect(!seen.code, label + ": " + seen.code.message()); - expect(caller.entries >= 1, label); - expect(entered_first(caller, function), label + " entered " + caller.first); - expect(worker.entries == 0, - label + ": " + std::to_string(worker.entries) + " guards entered on the wrong thread"); - expect(caller.dit_off, label); - expect(worker.dit_off, label); +completion heavy(std::string_view name, std::string_view function, asio::io_context& context, + asio::thread_pool& pool, Start start) { + return form_on(computes_on::pool, name, function, context, pool, std::move(start)); +} + +// A cheap form on a synchronous backend: the calling thread computes, during the initiation. +template +completion cheap(std::string_view name, std::string_view function, asio::io_context& context, + asio::thread_pool& pool, Start start) { + return form_on(computes_on::caller, name, function, context, pool, std::move(start)); } void check_heavy(asio::io_context& context, asio::thread_pool& pool) { @@ -239,10 +239,12 @@ void check_heavy(asio::io_context& context, asio::thread_pool& pool) { hash::async_bcrypt(work, stored, password, salt, {.cost = 4}, std::move(handler)); }); - heavy("async_bcrypt_verify", "hash::bcrypt_verify", context, pool, [&](auto handler) { - hash::async_bcrypt_verify( - work, password, std::string_view(stored.data(), stored.size()), std::move(handler)); - }); + auto const verified = + heavy("async_bcrypt_verify", "hash::bcrypt_verify", context, pool, [&](auto handler) { + hash::async_bcrypt_verify( + work, password, std::string_view(stored.data(), stored.size()), std::move(handler)); + }); + expect(verified.same, "async_bcrypt_verify: the password does not match its own hash"); heavy("async_bcrypt_pbkdf", "hash::bcrypt_pbkdf", context, pool, [&](auto handler) { hash::async_bcrypt_pbkdf(work, output, password, salt, 4, std::move(handler)); From 481b75b77cc9c28d6d2fc5a7bd8ef8ed158b36eb Mon Sep 17 00:00:00 2001 From: R Date: Sun, 22 Nov 2026 09:39:23 -0300 Subject: [PATCH 19/27] hash: timing_botan_failure shows Botan throwing inside a guard answers backend_failure and leaves DIT as found, from clear and from set --- test/Jamfile | 5 ++ test/timing_botan_failure_test.cpp | 108 +++++++++++++++++++++++++++++ 2 files changed, 113 insertions(+) create mode 100644 test/timing_botan_failure_test.cpp diff --git a/test/Jamfile b/test/Jamfile index 5c28150..1056c25 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -747,6 +747,11 @@ hash-run timing_keyed : timing_keyed_test.cpp hash-run timing_keyed_openssl : timing_keyed_openssl_test.cpp : /webcpp/hash//openssl : native wasip2 wasip3 ; botan-run timing_keyed_botan : timing_keyed_botan_test.cpp ; +# Botan failing inside a guard (a name it does not know, through the seam of +# botan_failure): mac, hkdf_extract, hkdf_expand, hkdf and pbkdf2 enter their +# own guard, answer backend_failure and leave DIT as they found it. +botan-run timing_botan_failure : timing_botan_failure_test.cpp + : "\"WEBCPP_HASH_DETAIL_TEST_BOTAN_NAME=\\\"NO-SUCH-HASH\\\"\"" ; # One coverage test per backend, driven by doc/capabilities.json: every keyed # cell of the backend (support/timing_coverage.hpp: macs, key derivations and diff --git a/test/timing_botan_failure_test.cpp b/test/timing_botan_failure_test.cpp new file mode 100644 index 0000000..cc83616 --- /dev/null +++ b/test/timing_botan_failure_test.cpp @@ -0,0 +1,108 @@ +// 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 failure of Botan inside a guard (design D1, ruling H10): through the seam +// WEBCPP_HASH_DETAIL_TEST_BOTAN_NAME, which the test's Jamfile defines to "NO-SUCH-HASH", Botan's +// create_or_throw throws Lookup_Error inside detail::botan_boundary, after the public function's +// detail::timing_guard is entered; the boundary answers backend_failure, and the guard's scope +// ends by that return. Each of mac, hkdf_extract, hkdf_expand, hkdf and pbkdf2 enters its own +// guard first and leaves the thread's DIT as it found it, from a thread with DIT clear and from +// one that set DIT itself (where the CPU has DIT). + +#include "support/timing_seam.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include +#include +#include + +#ifndef WEBCPP_HASH_DETAIL_TEST_BOTAN_NAME +#error "the test's Jamfile defines WEBCPP_HASH_DETAIL_TEST_BOTAN_NAME" +#endif + +namespace { + +namespace hash = webcpp::hash; +namespace test = webcpp::test; +using hash::backends::botan; +using hmac = hash::hmac_sha2_256; + +/** + * 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. + */ +void force_dit([[maybe_unused]] bool set) { +#ifdef WEBCPP_HASH_DETAIL_TIMING_COVERED + if (!hash::detail::cpu_has_dit()) { + return; + } + hash::detail::write_dit(set ? hash::detail::dit_bit : 0); +#endif +} + +std::array const abc{0x61, 0x62, 0x63}; +std::array const salt{1}; +std::array const key{2}; + +bool backend_failed(boost::system::result const& outcome) { + return outcome.has_error() && outcome.error() == hash::error::backend_failure; +} + +// Each call, from DIT set as `set` says: its own guard first, backend_failure, DIT as found. +void fails_inside_guard(bool set) { + force_dit(set); + bool const before = hash::detail::dit_is_set(); + std::string const from = set ? " from DIT set" : " from DIT clear"; + auto const restored = [&](std::string const& name) { + if (hash::detail::dit_is_set() != before) { + BOOST_ERROR((name + from + " left DIT other than it found it").c_str()); + } + }; + std::array output{}; + test::require_enters("hash::mac of hmac_sha2_256 on botan", [&] { + BOOST_TEST(backend_failed( + hash::mac, botan>(output, key, abc))); + }); + restored("mac"); + test::require_enters("hash::hkdf_extract on botan", [&] { + auto const prk = hash::hkdf_extract(salt, abc); + BOOST_TEST(prk.has_error() && prk.error() == hash::error::backend_failure); + }); + restored("hkdf_extract"); + test::require_enters("hash::hkdf_expand on botan", [&] { + BOOST_TEST(backend_failed(hash::hkdf_expand(output, key, abc))); + }); + restored("hkdf_expand"); + test::require_enters("hash::hkdf on botan", [&] { + BOOST_TEST(backend_failed(hash::hkdf(output, salt, abc, abc))); + }); + restored("hkdf"); + test::require_enters("hash::pbkdf2 on botan", [&] { + BOOST_TEST(backend_failed(hash::pbkdf2(output, abc, salt, 2))); + }); + restored("pbkdf2"); + force_dit(false); +} + +} // namespace + +int main() { + fails_inside_guard(false); + fails_inside_guard(true); + BOOST_TEST(!hash::detail::dit_is_set()); + return webcpp::test::exit_status(boost::report_errors()); +} From 5cbd7a9a4e863a5f812f28d5998a9f668fb6f51c Mon Sep 17 00:00:00 2001 From: R Date: Sun, 22 Nov 2026 09:39:59 -0300 Subject: [PATCH 20/27] hash: the MACs chapter and the DIT section name mac as SipHash with DIT, and the section names timing_during and the coverage tests' pass from DIT set --- doc/backends.adoc | 4 ++-- doc/macs.adoc | 3 ++- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/doc/backends.adoc b/doc/backends.adoc index 661e177..9958790 100644 --- a/doc/backends.adoc +++ b/doc/backends.adoc @@ -1821,10 +1821,10 @@ The functions that set DIT, on every synchronous backend of their cells: The functions that do not: * Unkeyed digests and extendable-output functions, through `digest_of`, `hasher` and the types of Boost.Hash2's form (`keccak_256`, `blake3` in its plain mode): their input is not a secret by their contract (a program that derives from a secret uses a MAC or a key derivation, which set DIT); they are the streaming case, where a guard per `update` of every checksum would cost a real fraction of a short chunk for no secret; and the same algorithm is also Boost.Hash2's own type by alias, which hash cannot guard, so that guarding one spelling would make the protection depend on the spelling. -* Boost.Hash2's types by alias, `siphash_32`, `siphash_64`, `hmac`, `hmac_md5_128`, `hmac_sha1_160`, `hmac_sha2_224`, `hmac_sha2_256`, `hmac_sha2_384`, `hmac_sha2_512`, `hmac_sha2_512_224`, `hmac_sha2_512_256`, `hmac_sha3_224`, `hmac_sha3_256`, `hmac_sha3_384`, `hmac_sha3_512`, `hmac_ripemd_128`, `hmac_ripemd_160`, `hmac_blake2b_512` and `hmac_blake2s_256`: they are Boost.Hash2's own classes, and a guard inside them would need a type of hash's in place of the alias. An HMAC with DIT is `mac>`, which runs the same Boost.Hash2 code on `backends::hash2` inside its guard; a program that calls `hmac` directly sets DIT itself. HKDF and PBKDF2 on `backends::hash2` run Boost.Hash2's `hmac` inside their own guard. +* Boost.Hash2's types by alias, `siphash_32`, `siphash_64`, `hmac`, `hmac_md5_128`, `hmac_sha1_160`, `hmac_sha2_224`, `hmac_sha2_256`, `hmac_sha2_384`, `hmac_sha2_512`, `hmac_sha2_512_224`, `hmac_sha2_512_256`, `hmac_sha3_224`, `hmac_sha3_256`, `hmac_sha3_384`, `hmac_sha3_512`, `hmac_ripemd_128`, `hmac_ripemd_160`, `hmac_blake2b_512` and `hmac_blake2s_256`: they are Boost.Hash2's own classes, and a guard inside them would need a type of hash's in place of the alias. An HMAC with DIT is `mac>`, which runs the same Boost.Hash2 code on `backends::hash2` inside its guard, and a SipHash with DIT is `mac`; a program that calls `hmac` or `siphash_64` directly sets DIT itself. HKDF and PBKDF2 on `backends::hash2` run Boost.Hash2's `hmac` inside their own guard. * The initiating functions of `async.hpp`: they check sizes and post, and the synchronous function they call sets DIT on the thread that computes, a thread of the work executor's pool for a heavy function, the caller's for a cheap one (<>). On `backends::webcrypto` the browser's JavaScript engine computes, and nothing is added. -A coverage test per backend (`test/timing_coverage__test.cpp`) reads this table and fails when a keyed cell of its backend has no call, when a call enters no guard, when the first guard it enters is not its own function's, or when it leaves DIT otherwise than it found it; it checks that the unkeyed functions enter none. The guard is hash's own copy of webcpp::crypto's, which depends on hash: a change to one is a change to the other, and crypto's test `timing_hash_interop_test` runs both nested, in either order. +A coverage test per backend (`test/timing_coverage__test.cpp`) reads this table and fails when a keyed cell of its backend has no call, when a call enters no guard, when the first guard it enters is not its own function's, or when it leaves DIT otherwise than it found it, from a thread with DIT clear and from one that set it; it checks that the unkeyed functions enter none. `test/timing_during_test.cpp` reads DIT while HKDF, PBKDF2 and `mac` compute, through a hash that records it at each update, on the calling thread and on an `async_pbkdf2` pool's. The guard is hash's own copy of webcpp::crypto's, which depends on hash: a change to one is a change to the other, and crypto's test `timing_hash_interop_test` runs both nested, in either order. What the guard adds to a call, measured from a release build, is in <>. diff --git a/doc/macs.adoc b/doc/macs.adoc index f43adc7..f438017 100644 --- a/doc/macs.adoc +++ b/doc/macs.adoc @@ -22,7 +22,8 @@ is a signature's job, webcpp::crypto's. synchronous backend, on 64-bit ARM under Apple's systems and Linux where the CPU has FEAT_DIT, and leaves the thread's DIT as it found it: a program does nothing (<>). Boost.Hash2's types that hash names by alias, `hmac` and its `hmac_*` aliases, `siphash_32` and -`siphash_64`, set none (<>). +`siphash_64`, set none (<>): for HMAC with DIT, call +`mac>`, and for SipHash with DIT, `mac`. include::generated/compare-macs.adoc[] From e519946a3c2bff778a6d2e506212a0e2707ccbfe Mon Sep 17 00:00:00 2001 From: R Date: Sun, 22 Nov 2026 09:45:34 -0300 Subject: [PATCH 21/27] hash: force_dit is defined once, in support/timing_dit.hpp, which carries the seam and which the timing tests and the coverage support include --- test/support/timing_coverage.hpp | 17 +------------- test/support/timing_dit.hpp | 37 ++++++++++++++++++++++++++++++ test/timing_botan_failure_test.cpp | 19 +++------------ test/timing_during_test.cpp | 19 +++------------ test/timing_test.cpp | 31 ++++++++----------------- 5 files changed, 53 insertions(+), 70 deletions(-) create mode 100644 test/support/timing_dit.hpp diff --git a/test/support/timing_coverage.hpp b/test/support/timing_coverage.hpp index a45b590..1e8502b 100644 --- a/test/support/timing_coverage.hpp +++ b/test/support/timing_coverage.hpp @@ -25,7 +25,7 @@ #ifndef WEBCPP_TEST_HASH_SUPPORT_TIMING_COVERAGE_HPP #define WEBCPP_TEST_HASH_SUPPORT_TIMING_COVERAGE_HPP -#include "timing_seam.hpp" +#include "timing_dit.hpp" #include #include @@ -67,21 +67,6 @@ namespace webcpp::test { -/** - * Sets or clears DIT for this thread, as a program can, so that a test starts from a known state; - * only where the CPU has DIT, since the instruction traps on a CPU without it. - * - * @param set Whether to set DIT. - */ -inline void force_dit([[maybe_unused]] bool set) noexcept { -#ifdef WEBCPP_HASH_DETAIL_TIMING_COVERED - if (!webcpp::hash::detail::cpu_has_dit()) { - return; - } - webcpp::hash::detail::write_dit(set ? webcpp::hash::detail::dit_bit : 0); -#endif -} - /** * Runs `call` and reports an error when it entered no detail::timing_guard, when the first guard * it entered is not the one of `function` (support/timing_seam.hpp), or when it left the thread's diff --git a/test/support/timing_dit.hpp b/test/support/timing_dit.hpp new file mode 100644 index 0000000..7882c63 --- /dev/null +++ b/test/support/timing_dit.hpp @@ -0,0 +1,37 @@ +// 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 detail::timing_guard (support/timing_seam.hpp) and a test's control of the thread's +// DIT: force_dit sets or clears it, as a program can, so that a test starts from a known state. +// Like the seam, a test includes this header before any hash header. + +#ifndef WEBCPP_TEST_HASH_SUPPORT_TIMING_DIT_HPP +#define WEBCPP_TEST_HASH_SUPPORT_TIMING_DIT_HPP + +#include "timing_seam.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. + * + * @param set Whether to set DIT. + */ +inline void force_dit([[maybe_unused]] bool set) noexcept { +#ifdef WEBCPP_HASH_DETAIL_TIMING_COVERED + if (!webcpp::hash::detail::cpu_has_dit()) { + return; + } + webcpp::hash::detail::write_dit(set ? webcpp::hash::detail::dit_bit : 0); +#endif +} + +} // namespace webcpp::test + +#endif // WEBCPP_TEST_HASH_SUPPORT_TIMING_DIT_HPP diff --git a/test/timing_botan_failure_test.cpp b/test/timing_botan_failure_test.cpp index cc83616..a747a06 100644 --- a/test/timing_botan_failure_test.cpp +++ b/test/timing_botan_failure_test.cpp @@ -12,7 +12,7 @@ // guard first and leaves the thread's DIT as it found it, from a thread with DIT clear and from // one that set DIT itself (where the CPU has DIT). -#include "support/timing_seam.hpp" +#include "support/timing_dit.hpp" #include #include @@ -41,19 +41,6 @@ namespace test = webcpp::test; using hash::backends::botan; using hmac = hash::hmac_sha2_256; -/** - * 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. - */ -void force_dit([[maybe_unused]] bool set) { -#ifdef WEBCPP_HASH_DETAIL_TIMING_COVERED - if (!hash::detail::cpu_has_dit()) { - return; - } - hash::detail::write_dit(set ? hash::detail::dit_bit : 0); -#endif -} - std::array const abc{0x61, 0x62, 0x63}; std::array const salt{1}; std::array const key{2}; @@ -64,7 +51,7 @@ bool backend_failed(boost::system::result const& outcome) { // Each call, from DIT set as `set` says: its own guard first, backend_failure, DIT as found. void fails_inside_guard(bool set) { - force_dit(set); + test::force_dit(set); bool const before = hash::detail::dit_is_set(); std::string const from = set ? " from DIT set" : " from DIT clear"; auto const restored = [&](std::string const& name) { @@ -95,7 +82,7 @@ void fails_inside_guard(bool set) { BOOST_TEST(backend_failed(hash::pbkdf2(output, abc, salt, 2))); }); restored("pbkdf2"); - force_dit(false); + test::force_dit(false); } } // namespace diff --git a/test/timing_during_test.cpp b/test/timing_during_test.cpp index e5f373f..1a872f5 100644 --- a/test/timing_during_test.cpp +++ b/test/timing_during_test.cpp @@ -15,7 +15,7 @@ // the same through async_pbkdf2 on a webcpp::asio::thread_pool of one thread, the probe's record // read on the pool's thread, which computes. -#include "support/timing_seam.hpp" +#include "support/timing_dit.hpp" #include #include @@ -148,19 +148,6 @@ constexpr std::array key{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 constexpr std::array salt{16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1}; constexpr std::array info{'c', 'o', 'n', 't', 'e', 'x', 't', 0}; -/** - * 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. - */ -void force_dit([[maybe_unused]] bool set) { -#ifdef WEBCPP_HASH_DETAIL_TIMING_COVERED - if (!hash::detail::cpu_has_dit()) { - return; - } - hash::detail::write_dit(set ? hash::detail::dit_bit : 0); -#endif -} - // Reports, by `name`, a probe that never ran, an update before any guard, an update with DIT // other than the CPU gives under a guard, or a thread left with DIT set. void check_record(std::string const& name, test::probe_record const& seen, bool dit_set_after) { @@ -187,7 +174,7 @@ void check_record(std::string const& name, test::probe_record const& seen, bool // Runs `call` from a thread with DIT clear, then checks what the probe saw during it. template void during(std::string const& name, Call call) { - force_dit(false); + test::force_dit(false); test::probe_reset(); call(); check_record(name, test::probe_seen, hash::detail::dit_is_set()); @@ -249,7 +236,7 @@ void on_the_pool() { asio::io_context context; asio::thread_pool pool(1); on_pool(pool, [] { - force_dit(false); + test::force_dit(false); test::probe_reset(); return true; }); diff --git a/test/timing_test.cpp b/test/timing_test.cpp index 7acc90e..448991c 100644 --- a/test/timing_test.cpp +++ b/test/timing_test.cpp @@ -12,7 +12,7 @@ // (timing_threads, native, with threads), a guard on one thread leaves another's DIT clear. A copy // of libs/crypto/test/timing_test.cpp with hash's names and the engaged flag. -#include "support/timing_seam.hpp" +#include "support/timing_dit.hpp" #include #include @@ -46,19 +46,6 @@ void forwarding_function() { } // namespace seam_probe -/** - * Sets or clears DIT for this thread, as a program can, so that a test starts from a known state; - * only where the CPU has DIT, since the instruction traps on a CPU without it. - */ -void force_dit([[maybe_unused]] bool set) { -#ifdef WEBCPP_HASH_DETAIL_TIMING_COVERED - if (!detail::cpu_has_dit()) { - return; - } - detail::write_dit(set ? detail::dit_bit : 0); -#endif -} - // Constructing a guard raises the seam's count by exactly one, on every target. void seam_fires() { std::size_t const before = webcpp::test::timing_entries; @@ -139,7 +126,7 @@ void names_function_spellings() { // From clear: set inside a guard, clear after it. Where the guard does not apply, never set. void guard_sets_and_clears() { - force_dit(false); + webcpp::test::force_dit(false); BOOST_TEST(!detail::dit_is_set()); { detail::timing_guard const guard; @@ -150,20 +137,20 @@ void guard_sets_and_clears() { // From set, as a program sets it: still set after a guard. void guard_leaves_set_bit() { - force_dit(true); + webcpp::test::force_dit(true); BOOST_TEST_EQ(detail::dit_is_set(), detail::cpu_has_dit()); { detail::timing_guard const guard; BOOST_TEST_EQ(detail::dit_is_set(), detail::cpu_has_dit()); } BOOST_TEST_EQ(detail::dit_is_set(), detail::cpu_has_dit()); - force_dit(false); + webcpp::test::force_dit(false); BOOST_TEST(!detail::dit_is_set()); } // From clear: set inside both guards and after the inner one, clear after the outer one. void nested_guards() { - force_dit(false); + webcpp::test::force_dit(false); { detail::timing_guard const outer; { @@ -183,20 +170,20 @@ void nested_guards() { // A guard constructed with false fires no seam and touches nothing, whichever state it finds. void disengaged_does_nothing() { std::size_t const before = webcpp::test::timing_entries; - force_dit(false); + webcpp::test::force_dit(false); { detail::timing_guard const guard{false}; BOOST_TEST_EQ(webcpp::test::timing_entries, before); BOOST_TEST(!detail::dit_is_set()); } BOOST_TEST(!detail::dit_is_set()); - force_dit(true); + webcpp::test::force_dit(true); { detail::timing_guard const guard{false}; BOOST_TEST_EQ(detail::dit_is_set(), detail::cpu_has_dit()); } BOOST_TEST_EQ(detail::dit_is_set(), detail::cpu_has_dit()); - force_dit(false); + webcpp::test::force_dit(false); BOOST_TEST(!detail::dit_is_set()); } @@ -205,7 +192,7 @@ void disengaged_does_nothing() { // started before the guard, so that it cannot inherit the state at its creation (Linux's clone // copies PSTATE), and reads it only once the guard is entered. void other_thread_untouched() { - force_dit(false); + webcpp::test::force_dit(false); std::promise guard_entered; std::promise other_reading; std::thread other([entered = guard_entered.get_future(), &other_reading]() mutable { From af15c408888e55990a1fcc61b38551c4a11e8508 Mon Sep 17 00:00:00 2001 From: R Date: Sun, 22 Nov 2026 10:31:21 -0300 Subject: [PATCH 22/27] hash: timing_async declares cheap only where it is called, outside the Botan twin, so clang-tidy finds no unused template --- test/timing_async_test.cpp | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/test/timing_async_test.cpp b/test/timing_async_test.cpp index 212e78a..24eed50 100644 --- a/test/timing_async_test.cpp +++ b/test/timing_async_test.cpp @@ -203,13 +203,6 @@ completion heavy(std::string_view name, std::string_view function, asio::io_cont return form_on(computes_on::pool, name, function, context, pool, std::move(start)); } -// A cheap form on a synchronous backend: the calling thread computes, during the initiation. -template -completion cheap(std::string_view name, std::string_view function, asio::io_context& context, - asio::thread_pool& pool, Start start) { - return form_on(computes_on::caller, name, function, context, pool, std::move(start)); -} - void check_heavy(asio::io_context& context, asio::thread_pool& pool) { auto work = pool.get_executor(); std::array output{}; @@ -253,6 +246,13 @@ void check_heavy(asio::io_context& context, asio::thread_pool& pool) { } #ifndef WEBCPP_TEST_TIMING_ASYNC_BOTAN +// A cheap form on a synchronous backend: the calling thread computes, during the initiation. +template +completion cheap(std::string_view name, std::string_view function, asio::io_context& context, + asio::thread_pool& pool, Start start) { + return form_on(computes_on::caller, name, function, context, pool, std::move(start)); +} + void check_cheap(asio::io_context& context, asio::thread_pool& pool) { auto loop = context.get_executor(); std::array output{}; From 051336d26e8529ab6b00bfa33371268c06d5c27d Mon Sep 17 00:00:00 2001 From: R Date: Sun, 22 Nov 2026 12:28:50 -0300 Subject: [PATCH 23/27] hash: the timing tests name their file-scope data test_key, test_salt, test_password, test_info and test_input, which no parameter of the library hides (MSVC C4459 at /WX) --- test/timing_async_test.cpp | 40 ++++++----- test/timing_botan_failure_test.cpp | 14 ++-- test/timing_during_test.cpp | 34 +++++---- test/timing_keyed_botan_test.cpp | 76 +++++++++++--------- test/timing_keyed_openssl_test.cpp | 63 ++++++++++------- test/timing_keyed_test.cpp | 107 +++++++++++++++-------------- 6 files changed, 186 insertions(+), 148 deletions(-) diff --git a/test/timing_async_test.cpp b/test/timing_async_test.cpp index 24eed50..6c8dd1e 100644 --- a/test/timing_async_test.cpp +++ b/test/timing_async_test.cpp @@ -88,8 +88,9 @@ using scrypt_backend = hash::default_backend; constexpr std::uint32_t argon2_lanes = 1; #endif -constexpr std::array password{'p', 'a', 's', 's', 'w', 'o', 'r', 'd'}; -constexpr std::array salt{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}; +constexpr std::array test_password{'p', 'a', 's', 's', 'w', 'o', 'r', 'd'}; +constexpr std::array test_salt{1, 2, 3, 4, 5, 6, 7, 8, + 9, 10, 11, 12, 13, 14, 15, 16}; // What a thread recorded through the seam, and whether it was back to DIT off when it was read. struct record { @@ -208,38 +209,39 @@ void check_heavy(asio::io_context& context, asio::thread_pool& pool) { std::array output{}; heavy("async_pbkdf2", "hash::pbkdf2", context, pool, [&](auto handler) { - hash::async_pbkdf2(work, output, password, salt, 100, - std::move(handler)); + hash::async_pbkdf2(work, output, test_password, + test_salt, 100, std::move(handler)); }); heavy("async_argon2id", "hash::argon2id", context, pool, [&](auto handler) { - hash::async_argon2id(work, output, password, salt, + hash::async_argon2id(work, output, test_password, test_salt, {.passes = 2, .memory = 65536}, std::move(handler)); }); heavy("async_argon2", "hash::argon2", context, pool, [&](auto handler) { hash::async_argon2, kdfs::argon2id, kdfs::argon2i>, - argon2_backend>(work, output, password, salt, + argon2_backend>(work, output, test_password, test_salt, {.passes = 3, .memory_kib = 64, .lanes = argon2_lanes}, std::move(handler)); }); heavy("async_scrypt", "hash::scrypt", context, pool, [&](auto handler) { - hash::async_scrypt(work, output, password, salt, + hash::async_scrypt(work, output, test_password, test_salt, {.n = 1024, .r = 8, .p = 1}, std::move(handler)); }); #ifdef WEBCPP_TEST_TIMING_ASYNC_BOTAN std::array stored{}; heavy("async_bcrypt", "hash::bcrypt", context, pool, [&](auto handler) { - hash::async_bcrypt(work, stored, password, salt, {.cost = 4}, + hash::async_bcrypt(work, stored, test_password, test_salt, {.cost = 4}, std::move(handler)); }); auto const verified = heavy("async_bcrypt_verify", "hash::bcrypt_verify", context, pool, [&](auto handler) { hash::async_bcrypt_verify( - work, password, std::string_view(stored.data(), stored.size()), std::move(handler)); + work, test_password, std::string_view(stored.data(), stored.size()), + std::move(handler)); }); expect(verified.same, "async_bcrypt_verify: the password does not match its own hash"); heavy("async_bcrypt_pbkdf", "hash::bcrypt_pbkdf", context, pool, [&](auto handler) { - hash::async_bcrypt_pbkdf(work, output, password, salt, 4, + hash::async_bcrypt_pbkdf(work, output, test_password, test_salt, 4, std::move(handler)); }); #endif @@ -260,10 +262,10 @@ void check_cheap(asio::io_context& context, asio::thread_pool& pool) { key.fill(0x0b); cheap("async_hmac", "hash::mac", context, pool, [&](auto handler) { - hash::async_hmac(loop, output, key, password, std::move(handler)); + hash::async_hmac(loop, output, key, test_password, std::move(handler)); }); cheap("async_hkdf", "hash::hkdf", context, pool, [&](auto handler) { - hash::async_hkdf(loop, output, salt, key, password, + hash::async_hkdf(loop, output, test_salt, key, test_password, std::move(handler)); }); @@ -271,7 +273,7 @@ void check_cheap(asio::io_context& context, asio::thread_pool& pool) { reset_pool_thread(pool); reset_this_thread(); completion seen; - hash::async_digest(loop, output, password, + hash::async_digest(loop, output, test_password, recording_handler(context, seen)); run_to_completion(context); record const caller = read_this_thread(); @@ -311,25 +313,25 @@ void check_cancelled_before(asio::io_context& context) { BOOST_TEST(seen.code == asio::error::operation_aborted); }; cancelled([&](auto handler) { - hash::async_pbkdf2(work, output, password, salt, 100, - std::move(handler)); + hash::async_pbkdf2(work, output, test_password, + test_salt, 100, std::move(handler)); }); cancelled([&](auto handler) { - hash::async_argon2id(work, output, password, salt, + hash::async_argon2id(work, output, test_password, test_salt, {.passes = 2, .memory = 65536}, std::move(handler)); }); cancelled([&](auto handler) { - hash::async_scrypt(work, output, password, salt, + hash::async_scrypt(work, output, test_password, test_salt, {.n = 1024, .r = 8, .p = 1}, std::move(handler)); }); #ifdef WEBCPP_TEST_TIMING_ASYNC_BOTAN std::array stored{}; cancelled([&](auto handler) { - hash::async_bcrypt(work, stored, password, salt, {.cost = 4}, + hash::async_bcrypt(work, stored, test_password, test_salt, {.cost = 4}, std::move(handler)); }); cancelled([&](auto handler) { - hash::async_bcrypt_pbkdf(work, output, password, salt, 4, + hash::async_bcrypt_pbkdf(work, output, test_password, test_salt, 4, std::move(handler)); }); #endif diff --git a/test/timing_botan_failure_test.cpp b/test/timing_botan_failure_test.cpp index a747a06..28bf89b 100644 --- a/test/timing_botan_failure_test.cpp +++ b/test/timing_botan_failure_test.cpp @@ -42,8 +42,8 @@ using hash::backends::botan; using hmac = hash::hmac_sha2_256; std::array const abc{0x61, 0x62, 0x63}; -std::array const salt{1}; -std::array const key{2}; +std::array const test_salt{1}; +std::array const test_key{2}; bool backend_failed(boost::system::result const& outcome) { return outcome.has_error() && outcome.error() == hash::error::backend_failure; @@ -62,24 +62,24 @@ void fails_inside_guard(bool set) { std::array output{}; test::require_enters("hash::mac of hmac_sha2_256 on botan", [&] { BOOST_TEST(backend_failed( - hash::mac, botan>(output, key, abc))); + hash::mac, botan>(output, test_key, abc))); }); restored("mac"); test::require_enters("hash::hkdf_extract on botan", [&] { - auto const prk = hash::hkdf_extract(salt, abc); + auto const prk = hash::hkdf_extract(test_salt, abc); BOOST_TEST(prk.has_error() && prk.error() == hash::error::backend_failure); }); restored("hkdf_extract"); test::require_enters("hash::hkdf_expand on botan", [&] { - BOOST_TEST(backend_failed(hash::hkdf_expand(output, key, abc))); + BOOST_TEST(backend_failed(hash::hkdf_expand(output, test_key, abc))); }); restored("hkdf_expand"); test::require_enters("hash::hkdf on botan", [&] { - BOOST_TEST(backend_failed(hash::hkdf(output, salt, abc, abc))); + BOOST_TEST(backend_failed(hash::hkdf(output, test_salt, abc, abc))); }); restored("hkdf"); test::require_enters("hash::pbkdf2 on botan", [&] { - BOOST_TEST(backend_failed(hash::pbkdf2(output, abc, salt, 2))); + BOOST_TEST(backend_failed(hash::pbkdf2(output, abc, test_salt, 2))); }); restored("pbkdf2"); test::force_dit(false); diff --git a/test/timing_during_test.cpp b/test/timing_during_test.cpp index 1a872f5..c7c6a24 100644 --- a/test/timing_during_test.cpp +++ b/test/timing_during_test.cpp @@ -144,9 +144,11 @@ namespace backends = webcpp::hash::backends; using probe_hmac = hash::hmac; -constexpr std::array key{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}; -constexpr std::array salt{16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1}; -constexpr std::array info{'c', 'o', 'n', 't', 'e', 'x', 't', 0}; +constexpr std::array test_key{1, 2, 3, 4, 5, 6, 7, 8, + 9, 10, 11, 12, 13, 14, 15, 16}; +constexpr std::array test_salt{16, 15, 14, 13, 12, 11, 10, 9, + 8, 7, 6, 5, 4, 3, 2, 1}; +constexpr std::array test_info{'c', 'o', 'n', 't', 'e', 'x', 't', 0}; // Reports, by `name`, a probe that never ran, an update before any guard, an update with DIT // other than the CPU gives under a guard, or a thread left with DIT set. @@ -182,38 +184,42 @@ void during(std::string const& name, Call call) { void synchronous() { during("hkdf_extract", [] { - BOOST_TEST((hash::hkdf_extract(salt, key)).has_value()); + BOOST_TEST( + (hash::hkdf_extract(test_salt, test_key)).has_value()); }); - auto const prk = hash::hkdf_extract(salt, key); + auto const prk = hash::hkdf_extract(test_salt, test_key); if (!BOOST_TEST(prk.has_value())) { return; } std::array okm{}; during("hkdf_expand", [&] { - BOOST_TEST((hash::hkdf_expand(okm, *prk, info)).has_value()); + BOOST_TEST( + (hash::hkdf_expand(okm, *prk, test_info)).has_value()); }); during("hkdf", [&] { - BOOST_TEST((hash::hkdf(okm, salt, key, info)).has_value()); + BOOST_TEST((hash::hkdf(okm, test_salt, test_key, test_info)) + .has_value()); }); std::array derived{}; during("pbkdf2", [&] { - BOOST_TEST((hash::pbkdf2(derived, key, salt, 3)).has_value()); + BOOST_TEST((hash::pbkdf2(derived, test_key, test_salt, 3)) + .has_value()); }); // The probe computes SHA-256: pbkdf2 over it gives the bytes of pbkdf2 over hmac_sha2_256. std::array plain{}; - BOOST_TEST( - (hash::pbkdf2(plain, key, salt, 3)).has_value()); + BOOST_TEST((hash::pbkdf2(plain, test_key, test_salt, 3)) + .has_value()); BOOST_TEST(derived == plain); std::array tag{}; during("mac", [&] { BOOST_TEST((hash::mac, test::dit_probe_backend>( - tag, key, info)) + tag, test_key, test_info)) .has_value()); }); std::array plain_tag{}; - BOOST_TEST((hash::mac, backends::hash2>(plain_tag, - key, info)) + BOOST_TEST((hash::mac, backends::hash2>( + plain_tag, test_key, test_info)) .has_value()); BOOST_TEST(tag == plain_tag); } @@ -245,7 +251,7 @@ void on_the_pool() { bool called = false; boost::system::error_code code; hash::async_pbkdf2( - pool.get_executor(), derived, key, salt, 3, + pool.get_executor(), derived, test_key, test_salt, 3, asio::bind_executor(context.get_executor(), [&](boost::system::error_code done) { called = true; code = done; diff --git a/test/timing_keyed_botan_test.cpp b/test/timing_keyed_botan_test.cpp index 73cafef..950b9f5 100644 --- a/test/timing_keyed_botan_test.cpp +++ b/test/timing_keyed_botan_test.cpp @@ -40,52 +40,53 @@ namespace kdfs = webcpp::hash::kdfs; using hash::backends::botan; using hmac_sha2_256 = hash::hmac_sha2_256; -constexpr std::array key = [] { +constexpr std::array test_key = [] { std::array bytes{}; for (std::size_t i = 0; i < bytes.size(); ++i) { bytes[i] = static_cast(i + 1); } return bytes; }(); -std::array const info{9, 8, 7, 6, 5, 4, 3, 2, 1}; -std::array const salt{16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1}; +std::array const test_info{9, 8, 7, 6, 5, 4, 3, 2, 1}; +std::array const test_salt{16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1}; // bcrypt, bcrypt_verify and bcrypt_pbkdf each enter their own guard, at the lowest cost; a call // that a guard refuses (a salt of 8 bytes, a malformed string, 0 rounds) enters it too. void bcrypt_enters() { std::array made{}; test::require_enters("hash::bcrypt of cost 4 on botan", [&] { - BOOST_TEST((hash::bcrypt(made, key, salt, {.cost = 4})).has_value()); + BOOST_TEST((hash::bcrypt(made, test_key, test_salt, {.cost = 4})).has_value()); }); std::array again{}; test::require_enters("hash::bcrypt with the same arguments on botan", [&] { - BOOST_TEST((hash::bcrypt(again, key, salt, {.cost = 4})).has_value()); + BOOST_TEST((hash::bcrypt(again, test_key, test_salt, {.cost = 4})).has_value()); }); BOOST_TEST(made == again); test::require_enters("hash::bcrypt with a salt of 8 bytes on botan", [&] { BOOST_TEST( - !(hash::bcrypt(again, key, std::span{salt}.first(8), {.cost = 4})).has_value()); + !(hash::bcrypt(again, test_key, std::span{test_salt}.first(8), {.cost = 4})) + .has_value()); }); std::string_view const text{made.data(), made.size()}; test::require_enters("hash::bcrypt_verify of the right password on botan", [&] { - auto const checked = hash::bcrypt_verify(key, text); + auto const checked = hash::bcrypt_verify(test_key, text); BOOST_TEST(checked.has_value() && *checked); }); test::require_enters("hash::bcrypt_verify of the wrong password on botan", [&] { - auto const checked = hash::bcrypt_verify(salt, text); + auto const checked = hash::bcrypt_verify(test_salt, text); BOOST_TEST(checked.has_value() && !*checked); }); test::require_enters("hash::bcrypt_verify of a string of the wrong form on botan", [&] { - BOOST_TEST(!hash::bcrypt_verify(key, "not a bcrypt string").has_value()); + BOOST_TEST(!hash::bcrypt_verify(test_key, "not a bcrypt string").has_value()); }); std::array derived{}; test::require_enters("hash::bcrypt_pbkdf of 1 round on botan", [&] { - BOOST_TEST((hash::bcrypt_pbkdf(derived, key, salt, 1)).has_value()); + BOOST_TEST((hash::bcrypt_pbkdf(derived, test_key, test_salt, 1)).has_value()); }); test::require_enters("hash::bcrypt_pbkdf of 0 rounds on botan", [&] { - BOOST_TEST(!(hash::bcrypt_pbkdf(derived, key, salt, 0)).has_value()); + BOOST_TEST(!(hash::bcrypt_pbkdf(derived, test_key, test_salt, 0)).has_value()); }); } @@ -97,21 +98,24 @@ void hkdf_enters() { using prk_type = hmac_sha2_256::result_type; std::optional prk; test::require_enters("hash::hkdf_extract of a salt on botan", [&] { - auto const made = hash::hkdf_extract(salt, key); + auto const made = hash::hkdf_extract(test_salt, test_key); if (BOOST_TEST(made.has_value())) { prk.emplace(*made); } }); if (prk) { test::require_enters("hash::hkdf_expand of a prk on botan", [&] { - BOOST_TEST((hash::hkdf_expand(derived, *prk, info)).has_value()); + BOOST_TEST( + (hash::hkdf_expand(derived, *prk, test_info)).has_value()); }); } test::require_enters("hash::hkdf of a salt on botan", [&] { - BOOST_TEST((hash::hkdf(derived, salt, key, info)).has_value()); + BOOST_TEST((hash::hkdf(derived, test_salt, test_key, test_info)) + .has_value()); }); test::require_enters("hash::hkdf with an output of no byte on botan", [&] { - BOOST_TEST(!(hash::hkdf(none, salt, key, info)).has_value()); + BOOST_TEST( + !(hash::hkdf(none, test_salt, test_key, test_info)).has_value()); }); } @@ -120,47 +124,55 @@ void hkdf_enters() { void derivations_enter() { std::array derived{}; test::require_enters("hash::pbkdf2 of 1000 iterations on botan", [&] { - BOOST_TEST((hash::pbkdf2(derived, key, salt, 1000)).has_value()); + BOOST_TEST( + (hash::pbkdf2(derived, test_key, test_salt, 1000)).has_value()); }); test::require_enters("hash::pbkdf2 of 0 iterations on botan", [&] { - BOOST_TEST(!(hash::pbkdf2(derived, key, salt, 0)).has_value()); + BOOST_TEST( + !(hash::pbkdf2(derived, test_key, test_salt, 0)).has_value()); }); test::require_enters("hash::kbkdf of hmac_sha2_256 on botan", [&] { - BOOST_TEST( - (hash::kbkdf(derived, key, {.label = info, .context = salt})) - .has_value()); + BOOST_TEST((hash::kbkdf(derived, test_key, + {.label = test_info, .context = test_salt})) + .has_value()); }); test::require_enters("hash::kbkdf with a counter of 7 bits on botan", [&] { - BOOST_TEST( - !(hash::kbkdf(derived, key, {.counter_bits = 7})).has_value()); + BOOST_TEST(!(hash::kbkdf(derived, test_key, {.counter_bits = 7})) + .has_value()); }); test::require_enters("hash::sskdf of sha2_256 on botan", [&] { - BOOST_TEST((hash::sskdf(derived, key, info)).has_value()); + BOOST_TEST( + (hash::sskdf(derived, test_key, test_info)).has_value()); }); test::require_enters("hash::x963kdf of sha2_256 on botan", [&] { - BOOST_TEST((hash::x963kdf(derived, key, info)).has_value()); + BOOST_TEST( + (hash::x963kdf(derived, test_key, test_info)).has_value()); }); test::require_enters("hash::argon2id of the minimum parameters on botan", [&] { BOOST_TEST( - (hash::argon2id(derived, key, salt, {.passes = 1, .memory = 8192})).has_value()); + (hash::argon2id(derived, test_key, test_salt, {.passes = 1, .memory = 8192})) + .has_value()); }); hash::argon2_parameters const family{.passes = 1, .memory_kib = 8}; test::require_enters("hash::argon2 of argon2d on botan", [&] { - BOOST_TEST((hash::argon2(derived, key, salt, family)).has_value()); + BOOST_TEST( + (hash::argon2(derived, test_key, test_salt, family)).has_value()); }); test::require_enters("hash::argon2 of argon2i on botan", [&] { - BOOST_TEST((hash::argon2(derived, key, salt, family)).has_value()); + BOOST_TEST( + (hash::argon2(derived, test_key, test_salt, family)).has_value()); }); test::require_enters("hash::argon2 of argon2id on botan", [&] { - BOOST_TEST((hash::argon2(derived, key, salt, family)).has_value()); + BOOST_TEST((hash::argon2(derived, test_key, test_salt, family)) + .has_value()); }); test::require_enters("hash::scrypt of N = 16 on botan", [&] { - BOOST_TEST( - (hash::scrypt(derived, key, salt, {.n = 16, .r = 1, .p = 1})).has_value()); + BOOST_TEST((hash::scrypt(derived, test_key, test_salt, {.n = 16, .r = 1, .p = 1})) + .has_value()); }); test::require_enters("hash::scrypt of N = 1 on botan", [&] { - BOOST_TEST( - !(hash::scrypt(derived, key, salt, {.n = 1, .r = 1, .p = 1})).has_value()); + BOOST_TEST(!(hash::scrypt(derived, test_key, test_salt, {.n = 1, .r = 1, .p = 1})) + .has_value()); }); } diff --git a/test/timing_keyed_openssl_test.cpp b/test/timing_keyed_openssl_test.cpp index 77539d5..f590fb8 100644 --- a/test/timing_keyed_openssl_test.cpp +++ b/test/timing_keyed_openssl_test.cpp @@ -38,41 +38,45 @@ namespace kdfs = webcpp::hash::kdfs; using hash::backends::openssl; using hmac_sha2_256 = hash::hmac_sha2_256; -constexpr std::array key = [] { +constexpr std::array test_key = [] { std::array bytes{}; for (std::size_t i = 0; i < bytes.size(); ++i) { bytes[i] = static_cast(i + 1); } return bytes; }(); -std::array const info{9, 8, 7, 6, 5, 4, 3, 2, 1}; -std::array const salt{16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1}; +std::array const test_info{9, 8, 7, 6, 5, 4, 3, 2, 1}; +std::array const test_salt{16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1}; // kbkdf, sskdf and x963kdf each enter their own guard; a call that a guard refuses (a counter // width of 7 bits, an output of no byte) enters it too, and the guard changes no byte. void standards_enter() { std::array derived{}; test::require_enters("hash::kbkdf of hmac_sha2_256 on openssl", [&] { - BOOST_TEST( - (hash::kbkdf(derived, key, {.label = info, .context = salt})) - .has_value()); + BOOST_TEST((hash::kbkdf(derived, test_key, + {.label = test_info, .context = test_salt})) + .has_value()); }); test::require_enters("hash::kbkdf with a counter of 7 bits on openssl", [&] { - BOOST_TEST( - !(hash::kbkdf(derived, key, {.counter_bits = 7})).has_value()); + BOOST_TEST(!(hash::kbkdf(derived, test_key, {.counter_bits = 7})) + .has_value()); }); test::require_enters("hash::sskdf of sha2_256 on openssl", [&] { - BOOST_TEST((hash::sskdf(derived, key, info)).has_value()); + BOOST_TEST( + (hash::sskdf(derived, test_key, test_info)).has_value()); }); std::array none{}; test::require_enters("hash::sskdf with an output of no byte on openssl", [&] { - BOOST_TEST(!(hash::sskdf(none, key, info)).has_value()); + BOOST_TEST( + !(hash::sskdf(none, test_key, test_info)).has_value()); }); test::require_enters("hash::x963kdf of sha2_256 on openssl", [&] { - BOOST_TEST((hash::x963kdf(derived, key, info)).has_value()); + BOOST_TEST( + (hash::x963kdf(derived, test_key, test_info)).has_value()); }); test::require_enters("hash::x963kdf with an output of no byte on openssl", [&] { - BOOST_TEST(!(hash::x963kdf(none, key, info)).has_value()); + BOOST_TEST( + !(hash::x963kdf(none, test_key, test_info)).has_value()); }); } @@ -83,7 +87,7 @@ void hkdf_enters() { using prk_type = hmac_sha2_256::result_type; std::optional prk; test::require_enters("hash::hkdf_extract of a salt on openssl", [&] { - auto const made = hash::hkdf_extract(salt, key); + auto const made = hash::hkdf_extract(test_salt, test_key); if (BOOST_TEST(made.has_value())) { prk.emplace(*made); } @@ -91,11 +95,12 @@ void hkdf_enters() { if (prk) { test::require_enters("hash::hkdf_expand of a prk on openssl", [&] { BOOST_TEST( - (hash::hkdf_expand(derived, *prk, info)).has_value()); + (hash::hkdf_expand(derived, *prk, test_info)).has_value()); }); } test::require_enters("hash::hkdf of a salt on openssl", [&] { - BOOST_TEST((hash::hkdf(derived, salt, key, info)).has_value()); + BOOST_TEST((hash::hkdf(derived, test_salt, test_key, test_info)) + .has_value()); }); } @@ -104,32 +109,38 @@ void hkdf_enters() { void derivations_enter() { std::array derived{}; test::require_enters("hash::pbkdf2 of 1000 iterations on openssl", [&] { - BOOST_TEST((hash::pbkdf2(derived, key, salt, 1000)).has_value()); + BOOST_TEST( + (hash::pbkdf2(derived, test_key, test_salt, 1000)).has_value()); }); test::require_enters("hash::pbkdf2 of 0 iterations on openssl", [&] { - BOOST_TEST(!(hash::pbkdf2(derived, key, salt, 0)).has_value()); + BOOST_TEST( + !(hash::pbkdf2(derived, test_key, test_salt, 0)).has_value()); }); test::require_enters("hash::argon2id of the minimum parameters on openssl", [&] { - BOOST_TEST((hash::argon2id(derived, key, salt, {.passes = 1, .memory = 8192})) - .has_value()); + BOOST_TEST( + (hash::argon2id(derived, test_key, test_salt, {.passes = 1, .memory = 8192})) + .has_value()); }); hash::argon2_parameters const family{.passes = 1, .memory_kib = 8}; test::require_enters("hash::argon2 of argon2d on openssl", [&] { - BOOST_TEST((hash::argon2(derived, key, salt, family)).has_value()); + BOOST_TEST((hash::argon2(derived, test_key, test_salt, family)) + .has_value()); }); test::require_enters("hash::argon2 of argon2i on openssl", [&] { - BOOST_TEST((hash::argon2(derived, key, salt, family)).has_value()); + BOOST_TEST((hash::argon2(derived, test_key, test_salt, family)) + .has_value()); }); test::require_enters("hash::argon2 of argon2id on openssl", [&] { - BOOST_TEST((hash::argon2(derived, key, salt, family)).has_value()); + BOOST_TEST((hash::argon2(derived, test_key, test_salt, family)) + .has_value()); }); test::require_enters("hash::scrypt of N = 16 on openssl", [&] { - BOOST_TEST( - (hash::scrypt(derived, key, salt, {.n = 16, .r = 1, .p = 1})).has_value()); + BOOST_TEST((hash::scrypt(derived, test_key, test_salt, {.n = 16, .r = 1, .p = 1})) + .has_value()); }); test::require_enters("hash::scrypt of N = 1 on openssl", [&] { - BOOST_TEST( - !(hash::scrypt(derived, key, salt, {.n = 1, .r = 1, .p = 1})).has_value()); + BOOST_TEST(!(hash::scrypt(derived, test_key, test_salt, {.n = 1, .r = 1, .p = 1})) + .has_value()); }); } diff --git a/test/timing_keyed_test.cpp b/test/timing_keyed_test.cpp index ecd1fc3..3609451 100644 --- a/test/timing_keyed_test.cpp +++ b/test/timing_keyed_test.cpp @@ -60,35 +60,35 @@ using webcpp::hash::blake3; using hmac_sha256 = macs::hmac; using blake2b_options = hash::digest_options; -constexpr std::array key = [] { +constexpr std::array test_key = [] { std::array bytes{}; for (std::size_t i = 0; i < bytes.size(); ++i) { bytes[i] = static_cast(i + 1); } return bytes; }(); -std::array const input{9, 8, 7, 6, 5, 4, 3, 2, 1}; +std::array const test_input{9, 8, 7, 6, 5, 4, 3, 2, 1}; // mac enters its own guard on the default backend and on sodium, and still does when the output's // size is wrong, since the guard precedes the checks. void mac_enters() { std::array tag{}; test::require_enters("hash::mac of hmac_sha256 on hash2", [&] { - auto const done = hash::mac(tag, key, input); + auto const done = hash::mac(tag, test_key, test_input); BOOST_TEST(done.has_value()); }); test::require_enters("hash::mac of blake2b_mac on sodium", [&] { - auto const done = hash::mac(tag, key, input); + auto const done = hash::mac(tag, test_key, test_input); BOOST_TEST(done.has_value()); }); std::array wrong{}; test::require_enters("hash::mac with a tag of the wrong size on hash2", [&] { - auto const done = hash::mac(wrong, key, input); + auto const done = hash::mac(wrong, test_key, test_input); BOOST_TEST(!done.has_value()); }); test::require_enters("hash::mac with a key of the wrong size on sodium", [&] { auto const done = hash::mac( - tag, std::span{}, input); + tag, std::span{}, test_input); BOOST_TEST(!done.has_value()); }); } @@ -98,25 +98,26 @@ void mac_leaves_set_state() { std::array tag{}; test::force_dit(true); BOOST_TEST_EQ(detail::dit_is_set(), detail::cpu_has_dit()); - BOOST_TEST((hash::mac(tag, key, input)).has_value()); + BOOST_TEST((hash::mac(tag, test_key, test_input)).has_value()); BOOST_TEST_EQ(detail::dit_is_set(), detail::cpu_has_dit()); test::force_dit(false); BOOST_TEST(!detail::dit_is_set()); - BOOST_TEST((hash::mac(tag, key, input)).has_value()); + BOOST_TEST((hash::mac(tag, test_key, test_input)).has_value()); BOOST_TEST(!detail::dit_is_set()); } // digest_of with a key, and hasher's make, update and finish of a keyed hasher, each enter their // own guard; the output is the one of the unguarded computation, the same on the unkeyed call. void keyed_blake2b() { - blake2b_options const keyed{.key = key}; + blake2b_options const keyed{.key = test_key}; std::array once{}; test::require_enters("hash::digest_of with a key on sodium", [&] { - BOOST_TEST((hash::digest_of(once, input, keyed)).has_value()); + BOOST_TEST((hash::digest_of(once, test_input, keyed)).has_value()); }); // The same tag by mac, and by hasher. std::array by_mac{}; - BOOST_TEST((hash::mac(by_mac, key, input)).has_value()); + BOOST_TEST( + (hash::mac(by_mac, test_key, test_input)).has_value()); BOOST_TEST(once == by_mac); std::optional> hashing; @@ -130,7 +131,7 @@ void keyed_blake2b() { return; } test::require_enters("hash::hasher::update of a keyed hasher", - [&] { BOOST_TEST(hashing->update(input).has_value()); }); + [&] { BOOST_TEST(hashing->update(test_input).has_value()); }); std::array pieces{}; test::require_enters("hash::hasher::finish of a keyed hasher", [&] { BOOST_TEST(hashing->finish(pieces).has_value()); }); @@ -141,7 +142,7 @@ void keyed_blake2b() { void unkeyed_blake2b_enters_none() { std::array out{}; test::uncovered("hash::digest_of of blake2b without a key", [&] { - BOOST_TEST((hash::digest_of(out, input)).has_value()); + BOOST_TEST((hash::digest_of(out, test_input)).has_value()); }); std::optional> hashing; test::uncovered("hash::hasher::make of blake2b without a key", [&] { @@ -154,19 +155,20 @@ void unkeyed_blake2b_enters_none() { return; } test::uncovered("hash::hasher::update of blake2b without a key", - [&] { BOOST_TEST(hashing->update(input).has_value()); }); + [&] { BOOST_TEST(hashing->update(test_input).has_value()); }); test::uncovered("hash::hasher::finish of blake2b without a key", [&] { BOOST_TEST(hashing->finish(out).has_value()); }); std::array id{}; test::uncovered("hash::digest_of of sha2_256 on hash2", [&] { - BOOST_TEST((hash::digest_of(id, input)).has_value()); + BOOST_TEST( + (hash::digest_of(id, test_input)).has_value()); }); } // A keyed hasher moved into another still holds its guards, and so does one assigned to; an // unkeyed one moved holds none. Moving enters no guard of its own. void moved_keyed_hasher() { - blake2b_options const keyed{.key = key}; + blake2b_options const keyed{.key = test_key}; auto made = hash::hasher::make(keyed); if (!BOOST_TEST(made.has_value())) { return; @@ -174,7 +176,7 @@ void moved_keyed_hasher() { std::optional> moved; test::uncovered("moving a keyed hasher", [&] { moved.emplace(std::move(*made)); }); test::require_enters("hash::hasher::update of a moved keyed hasher", - [&] { BOOST_TEST(moved->update(input).has_value()); }); + [&] { BOOST_TEST(moved->update(test_input).has_value()); }); auto other = hash::hasher::make(); if (!BOOST_TEST(other.has_value())) { return; @@ -192,7 +194,7 @@ void moved_keyed_hasher() { std::optional> plain_moved; plain_moved.emplace(std::move(*plain)); test::uncovered("hash::hasher::update of a moved unkeyed hasher", - [&] { BOOST_TEST(plain_moved->update(input).has_value()); }); + [&] { BOOST_TEST(plain_moved->update(test_input).has_value()); }); // The destructor of a keyed hasher wipes and holds no guard. auto dying = hash::hasher::make(keyed); if (BOOST_TEST(dying.has_value())) { @@ -257,7 +259,7 @@ void blake3_vectors_unchanged() { void blake3_modes() { std::array const bytes{1, 2, 3, 4, 5, 6, 7, 8, 9}; std::optional keyed; - test::require_enters("blake3::keyed", [&] { keyed.emplace(blake3::keyed(key)); }); + test::require_enters("blake3::keyed", [&] { keyed.emplace(blake3::keyed(test_key)); }); test::require_enters("blake3::update(void const*) of a keyed object", [&] { keyed->update(static_cast(bytes.data()), bytes.size()); }); @@ -355,7 +357,7 @@ void hkdf_enters() { using prk_type = hmac_sha2_256::result_type; std::optional prk; test::require_enters("hash::hkdf_extract of a salt on hash2", [&] { - auto const made = hash::hkdf_extract(salt16, key); + auto const made = hash::hkdf_extract(salt16, test_key); if (BOOST_TEST(made.has_value())) { prk.emplace(*made); } @@ -366,30 +368,31 @@ void hkdf_enters() { std::array okm{}; test::require_enters("hash::hkdf_expand of a prk on hash2", [&] { BOOST_TEST( - (hash::hkdf_expand(okm, *prk, input)).has_value()); + (hash::hkdf_expand(okm, *prk, test_input)).has_value()); }); test::require_enters("hash::hkdf_expand with a prk of the wrong size on hash2", [&] { BOOST_TEST(!(hash::hkdf_expand( - okm, std::span{key}.first(5), input)) + okm, std::span{test_key}.first(5), test_input)) .has_value()); }); std::array whole{}; test::require_enters("hash::hkdf of a salt on hash2", [&] { - BOOST_TEST( - (hash::hkdf(whole, salt16, key, input)).has_value()); + BOOST_TEST((hash::hkdf(whole, salt16, test_key, test_input)) + .has_value()); }); // The two steps give what hkdf gives: the guards change no byte. std::array stepped{}; - auto const extracted = hash::hkdf_extract(salt16, key); + auto const extracted = hash::hkdf_extract(salt16, test_key); if (BOOST_TEST(extracted.has_value())) { - BOOST_TEST((hash::hkdf_expand(stepped, *extracted, input)) - .has_value()); + BOOST_TEST( + (hash::hkdf_expand(stepped, *extracted, test_input)) + .has_value()); BOOST_TEST(stepped == whole); } std::array none{}; test::require_enters("hash::hkdf with an output of no byte on hash2", [&] { - BOOST_TEST( - !(hash::hkdf(none, salt16, key, input)).has_value()); + BOOST_TEST(!(hash::hkdf(none, salt16, test_key, test_input)) + .has_value()); }); } @@ -397,18 +400,18 @@ void hkdf_enters() { void pbkdf2_enters() { std::array derived{}; test::require_enters("hash::pbkdf2 of 1000 iterations on hash2", [&] { - BOOST_TEST( - (hash::pbkdf2(derived, key, salt16, 1000)).has_value()); + BOOST_TEST((hash::pbkdf2(derived, test_key, salt16, 1000)) + .has_value()); }); std::array again{}; test::require_enters("hash::pbkdf2 with the same arguments on hash2", [&] { - BOOST_TEST( - (hash::pbkdf2(again, key, salt16, 1000)).has_value()); + BOOST_TEST((hash::pbkdf2(again, test_key, salt16, 1000)) + .has_value()); }); BOOST_TEST(derived == again); test::require_enters("hash::pbkdf2 of 0 iterations on hash2", [&] { - BOOST_TEST( - !(hash::pbkdf2(derived, key, salt16, 0)).has_value()); + BOOST_TEST(!(hash::pbkdf2(derived, test_key, salt16, 0)) + .has_value()); }); } @@ -418,49 +421,53 @@ void sodium_derivations_enter() { std::array const context{'c', 't', 'x', '_', 't', 'e', 's', 't'}; std::array subkey{}; test::require_enters("hash::blake2b_subkey on sodium", [&] { - BOOST_TEST((hash::blake2b_subkey(subkey, key, 7, context)).has_value()); + BOOST_TEST( + (hash::blake2b_subkey(subkey, test_key, 7, context)).has_value()); }); std::array tiny{}; test::require_enters("hash::blake2b_subkey with an output too small on sodium", [&] { - BOOST_TEST(!(hash::blake2b_subkey(tiny, key, 7, context)).has_value()); + BOOST_TEST( + !(hash::blake2b_subkey(tiny, test_key, 7, context)).has_value()); }); std::array derived{}; hash::argon2id_parameters const cheapest{.passes = 1, .memory = 8192}; test::require_enters("hash::argon2id of the minimum parameters on sodium", [&] { - BOOST_TEST((hash::argon2id(derived, key, salt16, cheapest)).has_value()); + BOOST_TEST( + (hash::argon2id(derived, test_key, salt16, cheapest)).has_value()); }); std::array const short_salt{1, 2, 3, 4}; test::require_enters("hash::argon2id with a salt of the wrong size on sodium", [&] { - BOOST_TEST( - !(hash::argon2id(derived, key, short_salt, cheapest)).has_value()); + BOOST_TEST(!(hash::argon2id(derived, test_key, short_salt, cheapest)) + .has_value()); }); hash::argon2_parameters const family{.passes = 3, .memory_kib = 8}; test::require_enters("hash::argon2 of argon2id on sodium", [&] { - BOOST_TEST( - (hash::argon2(derived, key, salt16, family)) - .has_value()); + BOOST_TEST((hash::argon2(derived, test_key, salt16, + family)) + .has_value()); }); test::require_enters("hash::argon2 of argon2i on sodium", [&] { BOOST_TEST( - (hash::argon2(derived, key, salt16, family)) + (hash::argon2(derived, test_key, salt16, family)) .has_value()); }); test::require_enters("hash::argon2 with a salt too short on sodium", [&] { - BOOST_TEST(!(hash::argon2(derived, key, short_salt, - family)) + BOOST_TEST(!(hash::argon2(derived, test_key, + short_salt, family)) .has_value()); }); hash::scrypt_parameters const small{.n = 16, .r = 1, .p = 1}; test::require_enters("hash::scrypt of N = 16 on sodium", [&] { - BOOST_TEST((hash::scrypt(derived, key, salt16, small)).has_value()); + BOOST_TEST((hash::scrypt(derived, test_key, salt16, small)).has_value()); }); test::require_enters("hash::scrypt of N = 1 on sodium", [&] { - BOOST_TEST(!(hash::scrypt( - derived, key, salt16, hash::scrypt_parameters{.n = 1, .r = 1, .p = 1})) - .has_value()); + BOOST_TEST( + !(hash::scrypt(derived, test_key, salt16, + hash::scrypt_parameters{.n = 1, .r = 1, .p = 1})) + .has_value()); }); } From 8c10341a3548c7ef211a127dc356fa926262e2c9 Mon Sep 17 00:00:00 2001 From: R Date: Sun, 22 Nov 2026 14:05:29 -0300 Subject: [PATCH 24/27] hash: async_heavy_test's cancellation race holds the pool's thread in its first round until the emit, so that at least one call is aborted whatever the scheduler does --- test/async_heavy_test.cpp | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/test/async_heavy_test.cpp b/test/async_heavy_test.cpp index 505aa25..57caa0b 100644 --- a/test/async_heavy_test.cpp +++ b/test/async_heavy_test.cpp @@ -722,13 +722,27 @@ void check_allocator_released(asio::io_context& context, asio::thread_pool& pool // A cancellation racing the pool: 300 quick PBKDF2s, each cancelled after a spin of 0 to 299 // yields, so that the emit lands while the job waits, while the pool takes it, while it runs and // after it has completed. Each call completes exactly once, successfully or with -// operation_aborted, and the handler's allocator holds nothing when it runs. +// operation_aborted, and the handler's allocator holds nothing when it runs. In the first round +// the pool's only thread is held by a job of the test until the emit, so that at least one emit +// lands while the job waits, whatever the scheduler does with the others: that call is aborted. void check_cancellation_races(asio::io_context& context) { asio::thread_pool pool(1); holding counts; std::array output{}; int aborted = 0; + // The first round's hold, alive until the pool has joined: the pool's thread may still be in + // released.wait() when the round ends. + std::promise held; + std::promise release; + auto released = release.get_future(); for (int round = 0; round != 300; ++round) { + if (round == 0) { + asio::post(pool, [&] { + held.set_value(); + released.wait(); + }); + held.get_future().wait(); + } asio::cancellation_signal signal; int calls = 0; int held_at_call = -1; @@ -748,11 +762,17 @@ void check_cancellation_races(asio::io_context& context) { std::this_thread::yield(); } signal.emit(asio::cancellation_type::terminal); + if (round == 0) { + release.set_value(); + } context.restart(); context.run_for(std::chrono::seconds(5)); // lint-run: the test's event loop BOOST_TEST_EQ(calls, 1); BOOST_TEST_EQ(held_at_call, 0); BOOST_TEST(!code || code == asio::error::operation_aborted); + if (round == 0) { + BOOST_TEST(code == asio::error::operation_aborted); + } aborted += code ? 1 : 0; } pool.join(); From 8f6b7cc016fda7417f301016b1b0f32cbbc07a30 Mon Sep 17 00:00:00 2001 From: R Date: Sun, 22 Nov 2026 14:14:33 -0300 Subject: [PATCH 25/27] hash: the timing tests' wrapped byte arrays end with a trailing comma, as readability-trailing-comma asks --- test/timing_async_test.cpp | 5 +++-- test/timing_during_test.cpp | 10 ++++++---- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/test/timing_async_test.cpp b/test/timing_async_test.cpp index 6c8dd1e..18c92c4 100644 --- a/test/timing_async_test.cpp +++ b/test/timing_async_test.cpp @@ -89,8 +89,9 @@ constexpr std::uint32_t argon2_lanes = 1; #endif constexpr std::array test_password{'p', 'a', 's', 's', 'w', 'o', 'r', 'd'}; -constexpr std::array test_salt{1, 2, 3, 4, 5, 6, 7, 8, - 9, 10, 11, 12, 13, 14, 15, 16}; +constexpr std::array test_salt{ + 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, +}; // What a thread recorded through the seam, and whether it was back to DIT off when it was read. struct record { diff --git a/test/timing_during_test.cpp b/test/timing_during_test.cpp index c7c6a24..5ca376e 100644 --- a/test/timing_during_test.cpp +++ b/test/timing_during_test.cpp @@ -144,10 +144,12 @@ namespace backends = webcpp::hash::backends; using probe_hmac = hash::hmac; -constexpr std::array test_key{1, 2, 3, 4, 5, 6, 7, 8, - 9, 10, 11, 12, 13, 14, 15, 16}; -constexpr std::array test_salt{16, 15, 14, 13, 12, 11, 10, 9, - 8, 7, 6, 5, 4, 3, 2, 1}; +constexpr std::array test_key{ + 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, +}; +constexpr std::array test_salt{ + 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, +}; constexpr std::array test_info{'c', 'o', 'n', 't', 'e', 'x', 't', 0}; // Reports, by `name`, a probe that never ran, an update before any guard, an update with DIT From b386ca75f2f16f7cdcd9212b7a5f9145d810dcd5 Mon Sep 17 00:00:00 2001 From: R Date: Sun, 22 Nov 2026 14:59:23 -0300 Subject: [PATCH 26/27] hash: timing_async and timing_during build their byte arrays in a constexpr lambda, which fits a line and needs no trailing comma either way --- test/timing_async_test.cpp | 11 ++++++++--- test/timing_during_test.cpp | 22 ++++++++++++++++------ 2 files changed, 24 insertions(+), 9 deletions(-) diff --git a/test/timing_async_test.cpp b/test/timing_async_test.cpp index 18c92c4..77fa733 100644 --- a/test/timing_async_test.cpp +++ b/test/timing_async_test.cpp @@ -89,9 +89,14 @@ constexpr std::uint32_t argon2_lanes = 1; #endif constexpr std::array test_password{'p', 'a', 's', 's', 'w', 'o', 'r', 'd'}; -constexpr std::array test_salt{ - 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, -}; +// The bytes 1 to 16. +constexpr std::array test_salt = [] { + std::array bytes{}; + for (std::size_t i = 0; i < bytes.size(); ++i) { + bytes[i] = static_cast(i + 1); + } + return bytes; +}(); // What a thread recorded through the seam, and whether it was back to DIT off when it was read. struct record { diff --git a/test/timing_during_test.cpp b/test/timing_during_test.cpp index 5ca376e..743101c 100644 --- a/test/timing_during_test.cpp +++ b/test/timing_during_test.cpp @@ -144,12 +144,22 @@ namespace backends = webcpp::hash::backends; using probe_hmac = hash::hmac; -constexpr std::array test_key{ - 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, -}; -constexpr std::array test_salt{ - 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, -}; +// The bytes 1 to 16, then 16 zero bytes. +constexpr std::array test_key = [] { + std::array bytes{}; + for (std::size_t i = 0; i < 16; ++i) { + bytes[i] = static_cast(i + 1); + } + return bytes; +}(); +// The bytes 16 down to 1. +constexpr std::array test_salt = [] { + std::array bytes{}; + for (std::size_t i = 0; i < bytes.size(); ++i) { + bytes[i] = static_cast(16 - i); + } + return bytes; +}(); constexpr std::array test_info{'c', 'o', 'n', 't', 'e', 'x', 't', 0}; // Reports, by `name`, a probe that never ran, an update before any guard, an update with DIT From 58b4512cbe680f68d156a5776f41b7f87af4c82f Mon Sep 17 00:00:00 2001 From: R Date: Sun, 22 Nov 2026 16:00:44 -0300 Subject: [PATCH 27/27] hash: a reference that includes hash reads only the backends its build links, and the refusal of OpenSSL on Emscripten never stops a reference config.hpp's __MRDOCS__ block defined every WEBCPP_HASH_HAS_, so that hash's own reference documents each. The reference of another library that includes hash (trystero's, read for Emscripten's target) then met the refusal of OpenSSL on Emscripten and BLAKE3's header, which its build does not link. Each definition now sits between push_macro and pop_macro, which keep the build's definition or its absence; hash's doc/Jamfile links every library, so its reference is unchanged but for line numbers. The refusal is guarded by !defined(__MRDOCS__). --- include/webcpp/hash/config.hpp | 32 +++++++++++++++++++++++++++----- 1 file changed, 27 insertions(+), 5 deletions(-) diff --git a/include/webcpp/hash/config.hpp b/include/webcpp/hash/config.hpp index 1480281..e21e23f 100644 --- a/include/webcpp/hash/config.hpp +++ b/include/webcpp/hash/config.hpp @@ -17,10 +17,13 @@ #include -// MrDocs parses hash natively, as a build with exceptions does, where none of these macros is -// defined: these definitions are the ones the reference lists. Each is undone at once, except the -// libraries' WEBCPP_HASH_HAS_, which stay defined: doc/Jamfile links every library, so that -// the reference reads each backend's header, as a program that links them all does. +// MrDocs parses hash as a build with exceptions does, where none of these macros is defined: these +// definitions are the ones the reference lists. Each is undone at once but WEBCPP_HASH_HAS_THREADS, +// which stays defined, as a native build has it. The libraries' WEBCPP_HASH_HAS_ are left as +// the build set them (push_macro and pop_macro keep the definition or its absence): hash's +// doc/Jamfile links every library, so its reference reads each backend's header, while the +// reference of a library that includes hash reads only the backends that library links (trystero's, +// for Emscripten's target, reads BearSSL's alone). #ifdef __MRDOCS__ /** Defined when webcpp::hash is built without exceptions: when webcpp has none (the compiler has @@ -37,31 +40,48 @@ /** Defined on the WebAssembly targets, wasip2, wasip3 and Emscripten. */ #define WEBCPP_HASH_WEBASSEMBLY 1 #undef WEBCPP_HASH_WEBASSEMBLY +#pragma push_macro("WEBCPP_HASH_HAS_XKCP") +#undef WEBCPP_HASH_HAS_XKCP /** Defined by `/third_party//xkcp` when the program links XKCP; a program built without b2 defines it to 1 itself. */ #define WEBCPP_HASH_HAS_XKCP 1 +#pragma pop_macro("WEBCPP_HASH_HAS_XKCP") +#pragma push_macro("WEBCPP_HASH_HAS_BLAKE3") +#undef WEBCPP_HASH_HAS_BLAKE3 /** Defined by `/third_party//blake3` when the program links the BLAKE3 C implementation; a program built without b2 defines it to 1 itself. */ #define WEBCPP_HASH_HAS_BLAKE3 1 +#pragma pop_macro("WEBCPP_HASH_HAS_BLAKE3") +#pragma push_macro("WEBCPP_HASH_HAS_SODIUM") +#undef WEBCPP_HASH_HAS_SODIUM /** Defined by `/third_party//sodium` when the program links libsodium; a program built without b2 defines it to 1 itself. */ #define WEBCPP_HASH_HAS_SODIUM 1 +#pragma pop_macro("WEBCPP_HASH_HAS_SODIUM") +#pragma push_macro("WEBCPP_HASH_HAS_BEARSSL") +#undef WEBCPP_HASH_HAS_BEARSSL /** Defined by `/third_party//bearssl` when the program links BearSSL; a program built without b2 defines it to 1 itself. */ #define WEBCPP_HASH_HAS_BEARSSL 1 +#pragma pop_macro("WEBCPP_HASH_HAS_BEARSSL") +#pragma push_macro("WEBCPP_HASH_HAS_OPENSSL") +#undef WEBCPP_HASH_HAS_OPENSSL /** Defined by `/webcpp/hash//openssl` when the program links OpenSSL; a program built without b2 defines it to 1 itself. Refused on Emscripten, where OpenSSL is not built. */ #define WEBCPP_HASH_HAS_OPENSSL 1 +#pragma pop_macro("WEBCPP_HASH_HAS_OPENSSL") +#pragma push_macro("WEBCPP_HASH_HAS_BOTAN") +#undef WEBCPP_HASH_HAS_BOTAN /** Defined by `/third_party//botan` when the program links Botan; a program built without b2 defines it to 1 itself. Botan reports its errors by throwing: in a build without exceptions @@ -70,6 +90,7 @@ Emscripten. */ #define WEBCPP_HASH_HAS_BOTAN 1 +#pragma pop_macro("WEBCPP_HASH_HAS_BOTAN") /** Defined where the heavy functions of `` (`async_argon2id`, `async_argon2`, `async_scrypt`, `async_pbkdf2` on a synchronous backend) run on another thread: natively, where @@ -111,8 +132,9 @@ // The refusals of impossible combinations (spec 5.7). Clang and gcc go on after an #error, so // the first error is the instruction; MSVC stops at it. +// A reference (MrDocs) describes the headers and builds no program, so none of them refuses it. // clang-format off -#if defined(WEBCPP_TARGET_EMSCRIPTEN) && defined(WEBCPP_HASH_HAS_OPENSSL) +#if !defined(__MRDOCS__) && defined(WEBCPP_TARGET_EMSCRIPTEN) && defined(WEBCPP_HASH_HAS_OPENSSL) #error "webcpp::hash: OpenSSL is not built for Emscripten. In the program's Jamfile, remove /webcpp/hash//openssl: hkdf and pbkdf2 then run on backends::hash2." #endif // clang-format on