From f4db5b306d8606fffd5ba7737902f0074442fa9e Mon Sep 17 00:00:00 2001 From: R Date: Sat, 21 Nov 2026 21:21:08 -0300 Subject: [PATCH 01/14] crypto: the heavy operations' machinery on webcpp::hash's model, with cancellation before and during the work and values that wipe themselves --- include/webcpp/crypto/detail/async_access.hpp | 41 + include/webcpp/crypto/detail/heavy.hpp | 678 ++++++++++++-- test/Jamfile | 29 +- test/heavy_refusal_forgotten_test.cpp | 16 +- test/heavy_test.cpp | 827 ++++++++++++++---- .../heavy_without_threads.cpp | 16 +- .../heavy_without_threads_first.cpp | 16 +- test/msvc/heavy_without_threads/app.cpp | 14 +- 8 files changed, 1347 insertions(+), 290 deletions(-) create mode 100644 include/webcpp/crypto/detail/async_access.hpp diff --git a/include/webcpp/crypto/detail/async_access.hpp b/include/webcpp/crypto/detail/async_access.hpp new file mode 100644 index 00000000..a246c19c --- /dev/null +++ b/include/webcpp/crypto/detail/async_access.hpp @@ -0,0 +1,41 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +#ifndef WEBCPP_CRYPTO_DETAIL_ASYNC_ACCESS_HPP +#define WEBCPP_CRYPTO_DETAIL_ASYNC_ACCESS_HPP + +#include + +namespace webcpp::crypto::detail { + +/** + * The empty objects of the asynchronous family's error completions (ruling R-A3): an operation + * that completes with `void(error_code, T)` gives, on an error, the object a move leaves (a + * `secret` or an array of zeros, a `gcm` or a key pair without a key), whose every member + * refuses with `invalid_state` where it has members. + * + * Each such type whose default constructor is private befriends this class; a type whose + * default constructor is public (`secret`, `std::array`) needs no friendship. + */ +struct async_access { + /** + * An empty `T`: its default constructor, private through friendship or public, or the + * value-initialisation of an aggregate (an array of zeros). + * + * @tparam T The completion's value type. + * @return The empty object. + */ + template + [[nodiscard]] static T empty() noexcept { + static_assert(noexcept(T{}), + "webcpp::crypto: an error completion's empty value is made without failing"); + return T{}; + } +}; + +} // namespace webcpp::crypto::detail + +#endif // WEBCPP_CRYPTO_DETAIL_ASYNC_ACCESS_HPP diff --git a/include/webcpp/crypto/detail/heavy.hpp b/include/webcpp/crypto/detail/heavy.hpp index de0677f9..82a21115 100644 --- a/include/webcpp/crypto/detail/heavy.hpp +++ b/include/webcpp/crypto/detail/heavy.hpp @@ -6,46 +6,105 @@ /** The heavy operations' `async_` variants (design D23): in a build with threads - (`WEBCPP_CRYPTO_HAS_THREADS`), `detail::run_heavy` runs the synchronous call on the executor - the program gives and completes on the handler's associated executor; without threads, the - variant's first statement, `WEBCPP_CRYPTO_DETAIL_REQUIRE_THREADS`, stops the build where the + (`WEBCPP_CRYPTO_HAS_THREADS`), `detail::run_on_work` checks the operation's guards on the + caller's thread, runs its synchronous call on the work executor the program gives and completes + on the handler's associated executor, with webcpp::hash's cancellation rules; without threads, + the variant's first statement, `WEBCPP_CRYPTO_DETAIL_REQUIRE_THREADS`, stops the build where the program calls it. + The machinery is webcpp::hash's (`libs/hash/include/webcpp/hash/async.hpp`, its `heavy_phase`, + `heavy_state`, `heavy_job`, `heavy_initiation` and `run_on_work`), ported, not shared (ruling + R-A5): hash's work writes into the caller's span, crypto's returns a value, which the state + carries and the completion gives as its second argument, `void(error_code, T)`, or none, + `void(error_code)`. Lifting the state into webcpp::asio is that library's change, for when a third + library needs it. + The heavy operations are stated (design D32): RSA key generation at every size and RSA private operations at 3072 bits and above; SLH-DSA key generation, signing and verification; ML-DSA key generation and signing; BLS12-381 verification, aggregate verification, fast aggregate verification and aggregation; KZG's commitments and proofs over a blob and their batch - verification; BN254's `pairing_check`. Everything else is cheap and synchronous only. + verification; BN254's `pairing_check`. Everything else is cheap: its `async_` variant completes + through a post, and its synchronous call runs at once. */ #ifndef WEBCPP_CRYPTO_DETAIL_HEAVY_HPP #define WEBCPP_CRYPTO_DETAIL_HEAVY_HPP #include +#include #include -#include -#include +#include +#include #ifdef WEBCPP_CRYPTO_HAS_THREADS -#include // lint-world: async_ variants (D23) -#include // lint-world: async_ variants (D23) -#include // lint-world: async_ variants (D23) -#include // lint-world: async_ variants (D23) -#include // lint-world: async_ variants (D23) -#include // lint-world: async_ variants (D23) -#include // lint-world: async_ variants (D23) -#include // lint-world: async_ variants (D23) -#include // lint-world: async_ variants (D23) -#include // lint-world: async_ variants (D23) +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include // lint-world: std::this_thread::yield, the state's spin lock #endif +#include +#include + namespace webcpp::crypto::detail { +/** + * The completion signature of an asynchronous operation whose synchronous call returns + * `Result`: `void(boost::system::error_code, T)` for `boost::system::result`, and + * `void(boost::system::error_code)` for `boost::system::result` (ruling R-A3). + * + * @tparam Result The synchronous call's result. + */ +template +struct completion_of { + static_assert(dependent_false, + "webcpp::crypto: an asynchronous operation's call returns a " + "boost::system::result"); +}; + +/** + * The completion of a call that returns a value. + * + * @tparam T The value. + */ +template +struct completion_of> { + /** The completion signature. */ + using type = void(boost::system::error_code, T); + /** The value the completion gives after its error code. */ + using value_type = T; +}; + +/** The completion of a call that returns no value. */ +template <> +struct completion_of> { + /** The completion signature. */ + using type = void(boost::system::error_code); + /** No value. */ + using value_type = void; +}; + /** The refusal of a heavy operation's `async_` variant in a build without threads (design D23). Each such variant's body starts with it, so that a program fails only where it calls one, - with this error first; a variant that forgets it stops at `run_heavy`'s stand-in instead. + with this error first; a variant that forgets it stops at `run_on_work`'s stand-in instead. The variant's completion token is its parameter `token`. */ #ifdef WEBCPP_CRYPTO_HAS_THREADS @@ -62,65 +121,542 @@ namespace webcpp::crypto::detail { #ifdef WEBCPP_CRYPTO_HAS_THREADS /** - * `function` with a handler's associated allocator and cancellation slot, which asio reads - * from each function an operation posts or dispatches on its handler's behalf. + * The error code of a synchronous call's result. * - * @param allocator The handler's associated allocator. - * @param slot The handler's associated cancellation slot. - * @param function The function posted or dispatched. - * @return `function`, bound to both. + * @tparam T The result's value. + * @param done The result. + * @return Its error, or the empty code on success. */ -template -auto carrying(Allocator const& allocator, Slot const& slot, Function function) { - return boost::asio::bind_cancellation_slot( - slot, boost::asio::bind_allocator(allocator, std::move(function))); +template +boost::system::error_code code_of(boost::system::result const& done) noexcept { + return done ? boost::system::error_code{} : done.error(); } +/** Where a heavy operation is: waiting in the work executor's queue, running, or completed. */ +enum class heavy_phase : std::uint8_t { + /** Posted to the work executor, not started. */ + queued, + /** Running on a thread of the work executor. */ + running, + /** Completed, or abandoned by a work executor that destroyed it unrun. */ + finished, +}; + /** - * Runs a heavy operation's synchronous call on another thread: posts `function` to `executor` - * (natively a `thread_pool`'s; on Emscripten a pool whose threads are Web Workers) and - * dispatches its result to the handler's associated executor, which by default is `executor`. - * The handler's executor is kept busy until then, so that an `io_context` the handler runs on - * does not run out of work while the call runs elsewhere. Both the posted and the dispatched - * functions carry the handler's associated allocator and cancellation slot, as asio asks of an - * operation's intermediate handlers; the call itself is never cancelled once posted. + * The value a heavy operation's state carries from its work to its completion: engaged by the + * work on success, destroyed (a `secret` or a key pair wipes itself) when a cancellation + * aborts the completion. * - * @tparam Executor The executor the call runs on. - * @tparam Function A call without arguments that reports its errors as values, not by throwing. - * @tparam CompletionToken Any completion token; the completion signature is `void(R)`, `R` the - * call's result. - * @param executor Where the call runs. - * @param function The synchronous call. - * @param token How the program is told of the result. - * @return What the completion token makes of the operation. + * @tparam T The value; `void` for an operation without one. */ -template -auto run_heavy(Executor executor, Function function, CompletionToken&& token) { - static_assert(std::is_nothrow_invocable_v, - "webcpp::crypto: a heavy operation's call reports its errors as values"); - using result_type = std::invoke_result_t; - auto initiation = [](auto handler, Executor const& work_executor, Function call) { - auto completion_executor = - boost::asio::prefer(boost::asio::get_associated_executor(handler, work_executor), - boost::asio::execution::outstanding_work_t::tracked); - auto const allocator = boost::asio::get_associated_allocator(handler); - auto const slot = boost::asio::get_associated_cancellation_slot(handler); - boost::asio::post( - work_executor, - carrying( - allocator, slot, - [handler = std::move(handler), call = std::move(call), - completion_executor = std::move(completion_executor), allocator, slot]() mutable { - boost::asio::dispatch( - completion_executor, - carrying(allocator, slot, - [handler = std::move(handler), result = call()]() mutable { - std::move(handler)(std::move(result)); - })); - })); +template +struct heavy_value { + /** The work's value, until the completion takes it. */ + std::optional value; +}; + +/** An operation without a value carries nothing. */ +template <> +struct heavy_value {}; + +/** + * The allocator of a heavy operation's job: the work executor's own, where the executor + * answers the query (a `thread_pool`'s), else `std::allocator`, which Asio's posting + * recycles. Never the handler's: the job may wait in the work executor's queue after the + * handler has run. + * + * @tparam WorkExecutor The work executor. + */ +template +using heavy_job_allocator_t = std::conditional_t< + webcpp::asio::can_query_v>, + std::decay>>, + std::type_identity>>::type; + +/** + * The work executor's allocator, for its job. + * + * @param work The work executor. + * @return Its allocator, or `std::allocator`. + */ +template +heavy_job_allocator_t heavy_job_allocator(WorkExecutor const& work) noexcept { + if constexpr (webcpp::asio::can_query_v>) { + return webcpp::asio::query(work, webcpp::asio::execution::allocator); + } else { + return std::allocator{}; + } +} + +/** + * A heavy operation (design D23), in storage of the handler's associated allocator, as every + * Asio operation's is; webcpp::hash's `heavy_state`, carrying the work's value. + * + * Whoever moves the phase from `queued` produces the completion, exactly once: the job, which + * runs the synchronous call on the work executor's thread; or a cancellation before the work + * starts, on the handler's executor, which completes with `operation_aborted` at once, the + * value empty (every type is honoured then: nothing has happened yet). Once the work runs, only + * `terminal` and `partial` are (no C library here can be interrupted: the work ends, then its + * value is destroyed, which wipes a `secret` or a key pair, and the completion is + * `operation_aborted` with the empty value, a side effect that `total` does not allow). + * + * The completion runs on the handler's associated executor (`work` by default), where the + * slot's signal is emitted: it clears the cancellation slot, moves the handler and the value + * out, destroys the state and gives its storage back to the handler's allocator, and only then + * calls the handler, so that nothing of that allocator outlives the call (Asio's rule). The job + * queued in the work executor holds the state through one atomic pointer, whose location the + * state records under a lock each time the job moves; a cancellation before the work starts + * takes the state back from that location, so that the job, which may wait behind other work + * for long, holds nothing of the handler's when the handler runs. The handler's executor has + * outstanding work until the completion, so that the caller's event loop does not return early. + * + * @tparam Handler The completion handler. + * @tparam WorkExecutor The work executor. + * @tparam Work The synchronous call, bound to its arguments. + */ +template +class heavy_state { +public: + /** The handler's associated executor, `work` by default. */ + using executor_type = webcpp::asio::associated_executor_t; + /** The handler's associated allocator, rebound to the state. */ + using allocator_type = std::allocator_traits< + webcpp::asio::associated_allocator_t>::template rebind_alloc; + /** The work's value, `void` for an operation without one. */ + using value_type = completion_of>::value_type; + + /** Not copyable: the job and the slot reach one state. */ + heavy_state(heavy_state const&) = delete; + /** Not movable: the job and the slot hold its address. */ + heavy_state(heavy_state&&) = delete; + /** Not copyable: the job and the slot reach one state. */ + heavy_state& operator=(heavy_state const&) = delete; + /** Not movable: the job and the slot hold its address. */ + heavy_state& operator=(heavy_state&&) = delete; + /** Destroys the handler, the value and the work's guard; the storage is freed by its owner. */ + ~heavy_state() = default; + + /** + * A new state, in storage of the handler's associated allocator. + * + * @param handler The completion handler. + * @param work The work executor. + * @param run The synchronous call, bound to its arguments. + * @return The state. + */ + static heavy_state* make(Handler handler, WorkExecutor const& work, Work run) { + allocator_type allocator(webcpp::asio::get_associated_allocator(handler)); + auto* const storage = std::allocator_traits::allocate(allocator, 1); + try_construct(allocator, storage, std::move(handler), work, std::move(run)); + return storage; + } + + /** Installs the cancellation handler, when the handler's slot is connected. */ + void install_cancellation() { + // NOLINTNEXTLINE(bugprone-unchecked-optional-access): engaged until the completion + auto slot = webcpp::asio::get_associated_cancellation_slot(*handler_); + if (slot.is_connected()) { + slot.template emplace(this); + } + } + + /** + * Records where the job holds the state, or that it holds it no longer (null). + * + * @param location The job's atomic pointer. + */ + void relocate(std::atomic* location) noexcept { + lock(); + location_ = location; + unlock(); + } + + /** The job's turn on the work executor's thread, the state taken out of the job. */ + void run_work() { + relocate(nullptr); + auto expected = heavy_phase::queued; + if (!phase_.compare_exchange_strong(expected, heavy_phase::running, + std::memory_order_acq_rel)) { + // A cancellation won, and found the job holding the state no more: complete for it. + complete_on_handler(webcpp::asio::error::operation_aborted); + return; + } + auto done = run_(); + auto code = code_of(done); + if constexpr (has_value) { + if (done) { + value_.value.emplace(std::move(*done)); + } + } + if (cancelled_.load(std::memory_order_acquire)) { + if constexpr (has_value) { + value_.value.reset(); + } + code = webcpp::asio::error::operation_aborted; + } + phase_.store(heavy_phase::finished, std::memory_order_release); + complete_on_handler(code); + } + + /** The job destroyed unrun (its executor shut down): the handler is destroyed, never called. */ + void abandon() { + relocate(nullptr); + auto expected = heavy_phase::queued; + if (!phase_.compare_exchange_strong(expected, heavy_phase::finished, + std::memory_order_acq_rel)) { + complete_on_handler(webcpp::asio::error::operation_aborted); + return; + } + auto const executor = handler_work_.get_executor(); + webcpp::asio::post(executor, bound_completion({}, false)); + } + + /** + * A cancellation of type `type`, on the handler's executor, where the signal is emitted. + * + * @param type The cancellation's type. + */ + void cancel(webcpp::asio::cancellation_type_t type) { + auto expected = heavy_phase::queued; + if (phase_.compare_exchange_strong(expected, heavy_phase::finished, + std::memory_order_acq_rel)) { + // Take the state back from the queued job; a job that has just taken it out itself + // completes for this cancellation instead. + bool taken = false; + lock(); + if (location_ != nullptr) { + taken = location_->exchange(nullptr, std::memory_order_acq_rel) != nullptr; + location_ = nullptr; + } + unlock(); + if (taken) { + auto const executor = handler_work_.get_executor(); + webcpp::asio::post(executor, + bound_completion(webcpp::asio::error::operation_aborted)); + } + return; + } + using webcpp::asio::cancellation_type; + if ((type & (cancellation_type::terminal | cancellation_type::partial)) != + cancellation_type::none) { + cancelled_.store(true, std::memory_order_release); + } + } + +private: + static constexpr bool has_value = !std::is_void_v; + + // The handler installed in the cancellation slot; the completion clears the slot before the + // state is destroyed. + class cancellation { + public: + explicit cancellation(heavy_state* state) noexcept : state_(state) {} + + void operator()(webcpp::asio::cancellation_type_t type) { state_->cancel(type); } + + private: + heavy_state* state_; }; - return boost::asio::async_initiate( - std::move(initiation), token, std::move(executor), std::move(function)); + + // The completion, on the handler's executor, its storage the handler's allocator's. It owns + // the state: run, it frees the state and calls the handler (`invoke`), or, for a job + // destroyed unrun, only frees it, the handler with it; destroyed without running (its + // executor shut down or destroyed with it queued, as Asio destroys a queued operation), it + // frees the state and the handler too, never calling it, so that nothing of the handler's + // allocator is left and a handler that owns a promise breaks it. + class completion { + public: + completion(heavy_state* state, boost::system::error_code code, bool invoke) noexcept + : state_(state), code_(code), invoke_(invoke) {} + + completion(completion&& other) noexcept + : state_(std::exchange(other.state_, nullptr)), + code_(other.code_), + invoke_(other.invoke_) {} + + completion(completion const&) = delete; + completion& operator=(completion const&) = delete; + completion& operator=(completion&&) = delete; + + ~completion() { + if (state_ != nullptr) { + state_->destroy(); + } + } + + void operator()() { + auto* const state = std::exchange(state_, nullptr); + if (invoke_) { + state->complete(code_); + } else { + state->destroy(); + } + } + + private: + heavy_state* state_; + boost::system::error_code code_; + bool invoke_; + }; + + heavy_state(Handler handler, WorkExecutor const& work, Work run) + : handler_work_( + webcpp::asio::make_work_guard(webcpp::asio::get_associated_executor(handler, work))), + handler_(std::in_place, std::move(handler)), + run_(std::move(run)) {} + + // Constructs the state in `storage`, which is given back if the construction throws. + static void try_construct(allocator_type& allocator, heavy_state* storage, Handler handler, + WorkExecutor const& work, Work run) { + struct give_back { + allocator_type& allocator; + heavy_state* storage; + + ~give_back() { + if (storage != nullptr) { + std::allocator_traits::deallocate(allocator, storage, 1); + } + } + } guard{allocator, storage}; + + ::new (static_cast(storage)) heavy_state(std::move(handler), work, std::move(run)); + guard.storage = nullptr; + } + + void lock() noexcept { + while (lock_.test_and_set(std::memory_order_acquire)) { + std::this_thread::yield(); // lint-world: to the thread holding the lock, no clock + } + } + + void unlock() noexcept { lock_.clear(std::memory_order_release); } + + // The completion bound to the handler's associated allocator; `invoke` false only discards. + auto bound_completion(boost::system::error_code code, bool invoke = true) { + // NOLINTNEXTLINE(bugprone-unchecked-optional-access): engaged until the completion + return webcpp::asio::bind_allocator(webcpp::asio::get_associated_allocator(*handler_), + completion(this, code, invoke)); + } + + // Dispatches the completion to the handler's executor; the caller touches the state no more. + void complete_on_handler(boost::system::error_code code) { + auto const executor = handler_work_.get_executor(); + webcpp::asio::dispatch(executor, bound_completion(code)); + } + + // The value the completion gives: the work's, or the empty one (ruling R-A3). + value_type take_value() noexcept { + if (value_.value) { + return std::move(*value_.value); + } + return async_access::empty(); + } + + // Clears the slot, takes the handler, the value and the executor's work out, frees the + // state, then calls the handler: nothing of the handler's allocator outlives the call. + void complete(boost::system::error_code code) { + clear_slot(); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access): engaged until here + Handler handler(std::move(*handler_)); + auto work = std::move(handler_work_); + allocator_type allocator(webcpp::asio::get_associated_allocator(handler)); + if constexpr (has_value) { + value_type value = take_value(); + release_storage(allocator); + std::move(handler)(code, std::move(value)); + } else { + release_storage(allocator); + std::move(handler)(code); + } + work.reset(); + } + + // Clears the slot, then destroys the state, the handler and the value with it, and gives its + // storage back. + void destroy() { + clear_slot(); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access): engaged until here + allocator_type allocator(webcpp::asio::get_associated_allocator(*handler_)); + release_storage(allocator); + } + + // Removes the cancellation handler, on the handler's executor, before the state goes. + void clear_slot() { + // NOLINTNEXTLINE(bugprone-unchecked-optional-access): engaged until here + auto slot = webcpp::asio::get_associated_cancellation_slot(*handler_); + if (slot.is_connected()) { + slot.clear(); + } + } + + // Destroys the state and gives its storage back to a copy of the handler's allocator. + void release_storage(allocator_type& allocator) { + std::allocator_traits::destroy(allocator, this); + std::allocator_traits::deallocate(allocator, this, 1); + } + + std::atomic_flag lock_ = ATOMIC_FLAG_INIT; + std::atomic* location_ = nullptr; + std::atomic phase_{heavy_phase::queued}; + std::atomic cancelled_{false}; + webcpp::asio::executor_work_guard handler_work_; + std::optional handler_; + Work run_; + heavy_value value_; +}; + +/** + * The job a heavy operation posts to the work executor: runs its state's work, or, destroyed + * unrun (the executor shut down), abandons it. Move-only; webcpp::hash's `heavy_job`. It holds + * the state through one atomic pointer, whose location it records in the state at each move, + * so that a cancellation before the work starts can take the state back: the job's own storage + * is the work executor's (its associated allocator is the executor's, @ref heavy_job_allocator), + * never the handler's. + * + * @tparam State The operation's @ref heavy_state. + * @tparam Allocator The work executor's allocator. + */ +template +class heavy_job { +public: + /** The work executor's allocator, which Asio's post reads for the job's storage. */ + using allocator_type = Allocator; + + /** + * Holds `state`, before the state can be cancelled. + * + * @param state The operation's state. + * @param allocator The work executor's allocator. + */ + heavy_job(State* state, Allocator const& allocator) noexcept + : allocator_(allocator), state_(state) { + state->relocate(&state_); + } + + /** + * Takes `other`'s hold, and records the new location; a hold taken back by a cancellation + * is null, and the state is then touched no more. + * + * @param other The job moved from. + */ + heavy_job(heavy_job&& other) noexcept + : allocator_(other.allocator_), + state_(other.state_.exchange(nullptr, std::memory_order_acq_rel)) { + if (auto* const held = state_.load(std::memory_order_relaxed); held != nullptr) { + held->relocate(&state_); + } + } + + /** Not copyable: one job holds the state once. */ + heavy_job(heavy_job const&) = delete; + /** Not copyable: one job holds the state once. */ + heavy_job& operator=(heavy_job const&) = delete; + /** Not assignable: a job is moved into its executor once. */ + heavy_job& operator=(heavy_job&&) = delete; + + /** Abandons the state when the job never ran and still holds it. */ + // A post that fails while a work executor destroys its queue ends the program, as an + // exception from any of Asio's destructors does. + // NOLINTNEXTLINE(bugprone-exception-escape): see above + ~heavy_job() { + if (auto* const held = state_.exchange(nullptr, std::memory_order_acq_rel); + held != nullptr) { + held->abandon(); + } + } + + /** + * The work executor's allocator. + * + * @return The allocator. + */ + [[nodiscard]] allocator_type get_allocator() const noexcept { return allocator_; } + + /** Runs the work on the work executor's thread, unless a cancellation took the state back. */ + void operator()() { + if (auto* const held = state_.exchange(nullptr, std::memory_order_acq_rel); + held != nullptr) { + held->run_work(); + } + } + +private: + Allocator allocator_; + std::atomic state_; +}; + +/** + * The initiation of a heavy operation (design D23), webcpp::hash's `heavy_initiation`: its + * guards first, whose refusal is posted to the handler's associated executor with the guard's + * error and the empty value, never waiting for the work executor (unless the handler has no + * executor of its own: the work executor is then its executor); then the work posted to the + * work executor. The operation's state and its completion are in storage of the handler's + * associated allocator, all given back before the handler runs. + */ +struct heavy_initiation { + /** + * Checks the guards, then posts the work or the refusal. + * + * @param handler The completion handler. + * @param work The work executor. + * @param guards The guards, bound to the arguments. + * @param run The synchronous call, bound to its arguments. + */ + template + void operator()(Handler&& handler, WorkExecutor const& work, Guards const& guards, + Work run) const { + using value_type = completion_of>::value_type; + auto const guarded = guards(); + if (!guarded) { + auto const executor = webcpp::asio::get_associated_executor(handler, work); + if constexpr (std::is_void_v) { + webcpp::asio::post(executor, webcpp::asio::append(std::forward(handler), + guarded.error())); + } else { + webcpp::asio::post( + executor, webcpp::asio::append(std::forward(handler), guarded.error(), + async_access::empty())); + } + return; + } + using state = heavy_state, WorkExecutor, Work>; + // The job holds the state from its making on, so that a failure to install the + // cancellation or to post abandons it rather than leak it with the executor's work. + auto* const made = state::make(std::forward(handler), work, std::move(run)); + heavy_job> job(made, heavy_job_allocator(work)); + made->install_cancellation(); + webcpp::asio::post(work, std::move(job)); + } +}; + +/** + * Initiates a heavy operation (design D23): checks `guards()` on the caller's thread (a refusal + * is posted to the handler's associated executor with its error and the empty value); then runs + * `run()` on `work`, completing on the handler's associated executor with `run()`'s result split + * into its error code and its value. Cancellation through the handler's slot as + * @ref heavy_state states. + * + * @tparam CompletionToken Any completion token, of signature `completion_of::type`, `R` + * `run()`'s result. + * @param work The work executor, a `webcpp::asio::thread_pool`'s, typically. + * @param guards The guards, bound to the arguments: a call without arguments returning + * `boost::system::result`. + * @param run The synchronous call, bound to its arguments: a `noexcept` call without arguments + * returning `boost::system::result` or `boost::system::result`, called once. + * @param token The completion token. + * @return What the completion token's `async_result` gives. + */ +template +auto run_on_work(WorkExecutor const& work, Guards guards, Work run, CompletionToken& token) { + static_assert(std::is_same_v, boost::system::result>, + "webcpp::crypto: a heavy operation's guards return boost::system::result"); + static_assert(std::is_nothrow_invocable_v, + "webcpp::crypto: a heavy operation's call reports its errors as values"); + using signature = completion_of>::type; + return webcpp::asio_backend::async_initiate( + heavy_initiation{}, token, work, std::move(guards), std::move(run)); } #else @@ -131,9 +667,9 @@ auto run_heavy(Executor executor, Function function, CompletionToken&& token) { * forgets `WEBCPP_CRYPTO_DETAIL_REQUIRE_THREADS` stops here alone, rather than compile into a * call that never runs the work nor calls the handler. */ -template -void run_heavy(Executor&& /*executor*/, Function&& /*function*/, - CompletionToken&& /*token*/) noexcept { +template +void run_on_work(WorkExecutor const& /*work*/, Guards&& /*guards*/, Work&& /*run*/, + CompletionToken& /*token*/) noexcept { static_assert(::webcpp::crypto::detail::dependent_false, "webcpp::crypto: a heavy operation's async_ variant needs a build with " "threads; if no error above names the synchronous call, this variant lacks " diff --git a/test/Jamfile b/test/Jamfile index f8862c57..785fd491 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -33,8 +33,12 @@ webcpp.headers-alone crypto : ../include : crypto.hpp crypto/config.hpp crypto/detail/engines.hpp crypto/detail/entropy.hpp crypto/detail/limits.hpp crypto/detail/windows.hpp crypto/detail/wipe.hpp crypto/secret.hpp crypto/supports.hpp crypto/detail/capabilities.hpp crypto/detail/defaults.hpp - crypto/detail/heavy.hpp crypto/detail/timing.hpp crypto/ciphers/aead.hpp + crypto/detail/async_access.hpp crypto/detail/timing.hpp crypto/ciphers/aead.hpp crypto/ciphers/chacha20_poly1305.hpp crypto/ciphers/secretbox.hpp crypto/pem.hpp ; +# detail/heavy.hpp compiles alone only with webcpp::asio, which it includes +# where the build has threads. +webcpp.headers-alone crypto : ../include : crypto/detail/heavy.hpp + : /webcpp/asio//asio ; # The backend BearSSL's header and the default backend's, with BearSSL linked, # on every target. @@ -42,13 +46,13 @@ webcpp.headers-alone crypto : ../include : crypto/ciphers/aes256_gcm.hpp crypto/backends/bearssl.hpp : /third_party//bearssl ; # The backend OpenSSL's header, with OpenSSL linked; BearSSL, -# ctaes, libsecp256k1 and libsodium are linked too, so that every public -# header compiles with these options (the lint's aggregate translation unit, -# tools/lint/compile_commands.py). +# ctaes, libsecp256k1 and libsodium are linked too, and webcpp::asio, so that +# every public header compiles with these options (the lint's aggregate +# translation unit, tools/lint/compile_commands.py). webcpp.headers-alone crypto : ../include : crypto/backends/openssl.hpp : /webcpp/crypto//openssl /third_party//bearssl /third_party//ctaes /third_party//secp256k1 - /third_party//sodium + /third_party//sodium /webcpp/asio//asio : native wasip2 wasip3 ; # The backend ctaes's header and the block cipher's default's, with ctaes # linked, on every target. @@ -95,12 +99,19 @@ webcpp.compile threads_config_multi : threads_config_test.cpp webcpp.compile threads_config_opted_out : threads_config_test.cpp : multi WEBCPP_CRYPTO_NO_THREADS : native ; webcpp.compile threads_config_wasm : threads_config_test.cpp : : wasip2 wasip3 emscripten ; -# A heavy operation's async_ variant with threads: detail::run_heavy runs the -# work on a thread_pool and completes on the caller's io_context. -crypto-run heavy : heavy_test.cpp : multi : native ; +# A heavy operation's async_ variant with threads, natively and on Emscripten +# with -pthread under node: detail::run_on_work runs the work on a +# thread_pool and completes on the caller's io_context, with webcpp::hash's +# cancellation; a pool of three Web Workers, made before main, since main +# blocks in run (PTHREAD_POOL_SIZE). +crypto-run heavy : heavy_test.cpp + : /webcpp/asio//asio multi + emscripten:-sPTHREAD_POOL_SIZE=3 + : native emscripten ; # Without threads (WEBCPP_CRYPTO_NO_THREADS natively; WASI has none), a heavy # operation's async_ variant that forgets its refusal stops at -# detail::run_heavy's stand-in, which names the refusal, and with that alone. +# detail::run_on_work's stand-in, which names the refusal, and with that +# alone. webcpp.compile-diagnostic heavy_refusal_forgotten : heavy_refusal_forgotten_test.cpp : WEBCPP_CRYPTO_NO_THREADS : native wasip2 wasip3 : alone ; diff --git a/test/heavy_refusal_forgotten_test.cpp b/test/heavy_refusal_forgotten_test.cpp index 1a0764e9..49f09e07 100644 --- a/test/heavy_refusal_forgotten_test.cpp +++ b/test/heavy_refusal_forgotten_test.cpp @@ -6,7 +6,7 @@ // A heavy operation's async_ variant that forgets WEBCPP_CRYPTO_DETAIL_REQUIRE_THREADS, called in a // build without threads (natively with WEBCPP_CRYPTO_NO_THREADS; on WASI always), stops at -// detail::run_heavy's stand-in, which names the missing refusal, and with that error alone: +// detail::run_on_work's stand-in, which names the missing refusal, and with that error alone: // without it, the variant would compile, never run the work and never call the handler. // clang-format off @@ -15,21 +15,21 @@ #include -#include +#include namespace { /** The test-only heavy operation, synchronous. */ -int slow(int value) noexcept { +boost::system::result slow(int value) noexcept { return value + 1; } /** Its async_ variant, which forgets the refusal. */ template -auto async_slow(Executor executor, int value, CompletionToken&& token) { - return webcpp::crypto::detail::run_heavy( - std::move(executor), [value]() noexcept { return slow(value); }, - std::forward(token)); +auto async_slow(Executor const& work, int value, CompletionToken&& token) { + return webcpp::crypto::detail::run_on_work( + work, []() noexcept { return boost::system::result(); }, + [value]() noexcept { return slow(value); }, token); } /** An executor and a completion token, which a build without threads never uses. */ @@ -41,5 +41,5 @@ struct token {}; int main() { async_slow(executor{}, 41, token{}); - return slow(0) == 1 ? 0 : 1; + return *slow(0) == 1 ? 0 : 1; } diff --git a/test/heavy_test.cpp b/test/heavy_test.cpp index 8139cfe7..c74be318 100644 --- a/test/heavy_test.cpp +++ b/test/heavy_test.cpp @@ -4,249 +4,718 @@ // accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) -// detail::run_heavy, the initiator of every heavy operation's async_ variant (design D23), in a -// build with threads, on a test-only heavy operation: the work runs on the executor given (a -// thread_pool's), not on the caller's thread; the caller's io_context goes on meanwhile (a 10 ms -// timer on it fires while the work waits for it); the completion runs on the handler's -// associated executor (the caller's io_context, on the caller's thread), whose io_context does -// not run out of work before it; a move-only result reaches the handler; any completion token -// works (asio's deferred); and the handler's associated allocator and cancellation slot are -// those of the function posted to the work's executor and of the one dispatched to the -// completion's, as asio asks of an operation's intermediate handlers. +// detail::run_on_work, the initiator of every heavy operation's async_ variant (design D23, +// ruling R-A5: webcpp::hash's heavy machinery, libs/hash/include/webcpp/hash/async.hpp, ported), +// in a build with threads (natively, and on Emscripten with -pthread under node), on a test-only +// heavy operation, async_slow, whose work makes a secret<32> of bytes all `value` and whose +// guard refuses `value == 0` with invalid_input_size: +// - heavy_runs_on_pool: the work runs on a thread of the pool, never the caller's; the completion +// runs on the caller's io_context, to which the handler is bound, with the work's value. +// - heavy_loop_goes_on: a latch holds the work until a 1 ms timer on the loop has fired (ruling +// R-A8, never by timing); the completion follows the timer. +// - heavy_guard_refused: a guard's refusal completes on the loop with its error and an all-zero +// secret, while the pool's one thread is held, and the pool runs nothing. +// - heavy_cancel_before_start: with the pool's one thread held, a cancellation of every type +// emitted on the loop completes at once with operation_aborted, and the work never runs. +// - heavy_cancel_while_running: once the work has started (latched), a terminal or partial +// cancellation lets it end, then destroys its value (a sentinel shows it gone before the +// handler runs) and completes with operation_aborted and the empty value; a total one is +// ignored and the value arrives. +// - heavy_signal_outlives: the signal declared before the loop and the pool, as hash's page asks; +// a pool destroyed with the job queued destroys the handler unrun, whether the handler is bound +// to the loop (which then runs, or is destroyed without running) or has no executor of its own, +// and the signal emitted after it reaches nothing. +// - heavy_tokens: a callback without an executor of its own (completing on the pool), use_future +// (in the build with exceptions, a refusal thrown as system_error), deferred and as_tuple. +// - heavy_allocator: the handler's associated allocator, bound by bind_allocator, holds the +// operation's state and every completion, and gets every block back before the handler runs, on +// each way an operation completes; the job queued in the pool is the work executor's, given +// back by the pool; and the replaced global operator new (support/counting.hpp) is not called. #include +#include +#include #include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include +#include "support/counting.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + #include #include +#include +#include +#include #include #include #include +#include +#include +#include #include #include -#include +#include #include #ifndef WEBCPP_CRYPTO_HAS_THREADS #error "test/Jamfile builds this test with threading=multi, where the build has threads" #endif +namespace asio = webcpp::asio; namespace crypto = webcpp::crypto; namespace { -/** The test-only heavy operation, synchronous. */ -int slow(int value) noexcept { - return value + 1; +using key = crypto::secret<32>; + +// The caller's thread, set by main before any work, and where the work of async_slow ran. Global: +// the work is a function of its own, which the test does not reach otherwise. +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables): set once by main +std::thread::id caller_thread; +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables): written by the pool's threads +std::atomic runs_off_caller{0}; +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables): written by the pool's threads +std::atomic runs_on_caller{0}; + +// The latch of the work: while engaged, a work that has started says so and waits until the test +// opens it, so that the test, never the scheduler, orders the work's end. Global, as the counters. +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables): set by the test +std::atomic latch_engaged{false}; +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables): written by the pool's thread +std::atomic latch_entered{false}; +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables): set by the test +std::atomic latch_open{false}; + +/** Engages the latch: the next work waits until open_latch. */ +void engage_latch() noexcept { + latch_entered = false; + latch_open = false; + latch_engaged = true; +} + +/** Waits until the work has started and waits at the latch. */ +void wait_until_entered() noexcept { + while (!latch_entered) { + std::this_thread::yield(); + } +} + +/** Lets the work end, and disengages the latch for the next one. */ +void open_latch() noexcept { + latch_engaged = false; + latch_open = true; +} + +/** The work's first step: where it runs is recorded, then it waits at the latch if engaged. */ +void enter_work() noexcept { + if (std::this_thread::get_id() == caller_thread) { + ++runs_on_caller; + } else { + ++runs_off_caller; + } + if (latch_engaged) { + latch_entered = true; + while (!latch_open) { + std::this_thread::yield(); + } + } +} + +/** How many works have run, on any thread. */ +int runs() noexcept { + return runs_off_caller.load() + runs_on_caller.load(); +} + +/** The guard of the test-only heavy operation: `value` 0 is refused. */ +boost::system::result slow_guards(std::uint8_t value) noexcept { + if (value == 0) { + return crypto::error::invalid_input_size; + } + return {}; +} + +/** The test-only heavy operation, synchronous: a secret of bytes all `value`. */ +boost::system::result slow(std::uint8_t value) noexcept { + enter_work(); + key made; + std::ranges::fill(made.writable(), value); + return made; } -/** Its async_ variant, as every heavy operation declares one. */ -template -auto async_slow(Executor executor, int value, CompletionToken&& token) { +/** Its async_ variant, as every heavy operation declares one (ruling R-A6). */ +template +auto async_slow(WorkExecutor const& work, std::uint8_t value, CompletionToken&& token) { WEBCPP_CRYPTO_DETAIL_REQUIRE_THREADS("async_slow", "slow"); - return crypto::detail::run_heavy( - std::move(executor), [value]() noexcept { return slow(value); }, - std::forward(token)); + return crypto::detail::run_on_work( + work, [value]() noexcept { return slow_guards(value); }, + [value]() noexcept { return slow(value); }, token); } -/** Waits, at most 5 s, until `flag` is set; whether it was. */ -bool wait_for(std::atomic const& flag) noexcept { - auto const deadline = std::chrono::steady_clock::now() + std::chrono::seconds(5); - while (!flag.load() && std::chrono::steady_clock::now() < deadline) { - std::this_thread::sleep_for(std::chrono::milliseconds(1)); +/** A value whose destruction the test sees: the sentinel's last owner, empty by default. */ +struct tracked { + std::shared_ptr sentinel; +}; + +/** A heavy operation whose value is a tracked holding `sentinel`. */ +template +auto async_tracked(WorkExecutor const& work, std::shared_ptr sentinel, + CompletionToken&& token) { + WEBCPP_CRYPTO_DETAIL_REQUIRE_THREADS("async_tracked", "tracked"); + return crypto::detail::run_on_work( + work, []() noexcept { return boost::system::result(); }, + [sentinel = std::move(sentinel)]() mutable noexcept { + enter_work(); + return boost::system::result(tracked{std::move(sentinel)}); + }, + token); +} + +/** Whether every byte of `made` is `value`. */ +bool all_bytes(key const& made, std::uint8_t value) { + return std::ranges::all_of(made.bytes(), [value](std::uint8_t byte) { return byte == value; }); +} + +/** A pool of one thread, held by a job of the test's until release or destruction. */ +struct held_pool { + asio::thread_pool pool{1}; + std::atomic blocking{false}; + std::atomic released{false}; + + held_pool() { + asio::post(pool, [this] { + blocking = true; + while (!released) { + std::this_thread::yield(); + } + }); + while (!blocking) { + std::this_thread::yield(); + } + } + + held_pool(held_pool const&) = delete; + held_pool& operator=(held_pool const&) = delete; + held_pool(held_pool&&) = delete; + held_pool& operator=(held_pool&&) = delete; + + ~held_pool() { + release(); + pool.join(); } - return flag.load(); + + void release() noexcept { released = true; } +}; + +/** What a callback of async_slow saw. */ +struct seen { + int calls = 0; + std::thread::id thread; + boost::system::error_code code; + key value; +}; + +/** A callback bound to `loop` that records into `into`. */ +auto recorder(asio::io_context& loop, seen& into) { + return asio::bind_executor(loop.get_executor(), + [&into](boost::system::error_code code, key value) { + ++into.calls; + into.thread = std::this_thread::get_id(); + into.code = code; + into.value = std::move(value); + }); } -void runs_elsewhere_and_completes_on_the_caller() { - boost::asio::io_context caller; - boost::asio::thread_pool pool(1); - auto const caller_thread = std::this_thread::get_id(); - std::atomic fired{false}; - boost::asio::steady_timer timer(caller, std::chrono::milliseconds(10)); - timer.async_wait([&fired](boost::system::error_code const& error) { - BOOST_TEST(!error); - fired.store(true); +void heavy_runs_on_pool(asio::io_context& loop, asio::thread_pool& pool) { + int const off_before = runs_off_caller.load(); + int const on_before = runs_on_caller.load(); + seen done; + async_slow(pool.get_executor(), 0x42, recorder(loop, done)); + BOOST_TEST_EQ(done.calls, 0); // never inside the call + loop.restart(); + loop.run(); // lint-run: the test's event loop, kept busy until the completion + BOOST_TEST_EQ(done.calls, 1); + BOOST_TEST(!done.code); + BOOST_TEST(done.thread == caller_thread); + BOOST_TEST(all_bytes(done.value, 0x42)); + BOOST_TEST_EQ(runs_off_caller.load(), off_before + 1); + BOOST_TEST_EQ(runs_on_caller.load(), on_before); +} + +void heavy_loop_goes_on(asio::io_context& loop, asio::thread_pool& pool) { + engage_latch(); + seen done; + async_slow(pool.get_executor(), 7, recorder(loop, done)); + wait_until_entered(); + bool timer_fired = false; + bool timer_first = false; + asio::steady_timer timer(loop, std::chrono::milliseconds(1)); + timer.async_wait([&](boost::system::error_code code) { + BOOST_TEST(!code); + timer_fired = true; + timer_first = done.calls == 0; + open_latch(); }); - std::thread::id work_thread; - std::thread::id completion_thread; - bool timer_fired_meanwhile = false; - bool completed = false; - crypto::detail::run_heavy( - pool.get_executor(), - [&work_thread, &fired]() noexcept { - work_thread = std::this_thread::get_id(); - return wait_for(fired); - }, - boost::asio::bind_executor(caller.get_executor(), [&](bool timer_fired) { - completion_thread = std::this_thread::get_id(); - timer_fired_meanwhile = timer_fired; - completed = true; - })); - // The completion keeps the caller's io_context busy: run returns after it, not before. - caller.run(); // lint-run: that run waits for the tracked work is what this test proves - pool.join(); - BOOST_TEST(completed); - BOOST_TEST(timer_fired_meanwhile); - BOOST_TEST(work_thread != caller_thread); - BOOST_TEST(work_thread != std::thread::id{}); - BOOST_TEST(completion_thread == caller_thread); -} - -void move_only_result() { - boost::asio::io_context caller; - boost::asio::thread_pool pool(1); - std::unique_ptr received; - crypto::detail::run_heavy( - pool.get_executor(), []() noexcept { return std::make_unique(7); }, - boost::asio::bind_executor(caller.get_executor(), [&received](std::unique_ptr result) { - received = std::move(result); - })); - caller.run(); // lint-run: waits for the pool's thread to post the completion + loop.restart(); + loop.run(); // lint-run: the test's event loop, going on while the work runs + BOOST_TEST(timer_fired); + BOOST_TEST(timer_first); + BOOST_TEST_EQ(done.calls, 1); + BOOST_TEST(!done.code); + BOOST_TEST(all_bytes(done.value, 7)); +} + +void heavy_guard_refused(asio::io_context& loop) { + held_pool held; + int const before = runs(); + seen refused; + refused.value = key{}; + async_slow(held.pool.get_executor(), 0, recorder(loop, refused)); + BOOST_TEST_EQ(refused.calls, 0); + loop.restart(); + loop.run(); // lint-run: the test's event loop; the pool is held, the refusal needs it not + BOOST_TEST_EQ(refused.calls, 1); + BOOST_TEST(refused.code == crypto::error::invalid_input_size); + BOOST_TEST(refused.thread == caller_thread); + BOOST_TEST(all_bytes(refused.value, 0)); + held.release(); + held.pool.join(); + BOOST_TEST_EQ(runs(), before); +} + +void heavy_cancel_before_start(asio::io_context& loop) { + for (auto const type : { + asio::cancellation_type::terminal, + asio::cancellation_type::partial, + asio::cancellation_type::total, + }) { + held_pool held; + int const before = runs(); + asio::cancellation_signal signal; + seen cancelled; + async_slow(held.pool.get_executor(), 9, + asio::bind_cancellation_slot(signal.slot(), recorder(loop, cancelled))); + asio::post(loop, [&signal, type] { signal.emit(type); }); + loop.restart(); + loop.run(); // lint-run: the test's event loop; the pool is still held + BOOST_TEST_EQ(cancelled.calls, 1); + BOOST_TEST(cancelled.code == asio::error::operation_aborted); + BOOST_TEST(cancelled.thread == caller_thread); + BOOST_TEST(all_bytes(cancelled.value, 0)); + held.release(); + held.pool.join(); + BOOST_TEST_EQ(runs(), before); + BOOST_TEST_EQ(cancelled.calls, 1); + } +} + +void heavy_cancel_while_running(asio::io_context& loop) { + for (auto const type : {asio::cancellation_type::terminal, asio::cancellation_type::partial}) { + asio::thread_pool pool(1); + engage_latch(); + asio::cancellation_signal signal; + seen cancelled; + async_slow(pool.get_executor(), 5, + asio::bind_cancellation_slot(signal.slot(), recorder(loop, cancelled))); + wait_until_entered(); + signal.emit(type); + open_latch(); + loop.restart(); + loop.run(); // lint-run: the test's event loop + BOOST_TEST_EQ(cancelled.calls, 1); + BOOST_TEST(cancelled.code == asio::error::operation_aborted); + BOOST_TEST(all_bytes(cancelled.value, 0)); + + // The value the work made is destroyed before the handler runs: a secret is wiped so. + engage_latch(); + auto sentinel = std::make_shared(1); + std::weak_ptr const alive = sentinel; + asio::cancellation_signal tracked_signal; + int calls = 0; + bool alive_at_call = true; + bool empty_value = false; + boost::system::error_code tracked_code; + async_tracked( + pool.get_executor(), std::move(sentinel), + asio::bind_cancellation_slot( + tracked_signal.slot(), + asio::bind_executor(loop.get_executor(), + [&](boost::system::error_code code, tracked const& value) { + ++calls; + alive_at_call = !alive.expired(); + empty_value = value.sentinel == nullptr; + tracked_code = code; + }))); + wait_until_entered(); + tracked_signal.emit(type); + open_latch(); + loop.restart(); + loop.run(); // lint-run: the test's event loop + BOOST_TEST_EQ(calls, 1); + BOOST_TEST(tracked_code == asio::error::operation_aborted); + BOOST_TEST(!alive_at_call); + BOOST_TEST(empty_value); + pool.join(); + } + + asio::thread_pool pool(1); + engage_latch(); + asio::cancellation_signal signal; + seen total; + async_slow(pool.get_executor(), 5, + asio::bind_cancellation_slot(signal.slot(), recorder(loop, total))); + wait_until_entered(); + signal.emit(asio::cancellation_type::total); + open_latch(); + loop.restart(); + loop.run(); // lint-run: the test's event loop + BOOST_TEST_EQ(total.calls, 1); + BOOST_TEST(!total.code); + BOOST_TEST(all_bytes(total.value, 5)); pool.join(); - BOOST_TEST(received != nullptr); - if (received) { - BOOST_TEST_EQ(*received, 7); +} + +/** The handler of an operation that never completes: destroyed, never called. */ +struct unrun_handler { + std::shared_ptr sentinel; + bool* called; + + void operator()(boost::system::error_code /*code*/, key /*value*/) const { *called = true; } +}; + +/** A pool of one held thread destroyed with the job of async_slow queued, its handler bound. */ +template +void destroy_pool_with_job_queued(std::weak_ptr& alive, bool& called, Bind bind) { + held_pool held; + auto sentinel = std::make_shared(1); + alive = sentinel; + async_slow(held.pool.get_executor(), 3, + bind(unrun_handler{.sentinel = std::move(sentinel), .called = &called})); + held.pool.stop(); +} + +void heavy_signal_outlives() { + // The signal outlives the loop and the pool: a signal must outlive the operation connected to + // its slot, which clears the slot when its handler is destroyed. + asio::cancellation_signal signal; + std::weak_ptr alive; + bool called = false; + { + asio::io_context loop; + destroy_pool_with_job_queued(alive, called, [&](auto handler) { + return asio::bind_cancellation_slot( + signal.slot(), asio::bind_executor(loop.get_executor(), std::move(handler))); + }); + loop.run(); // lint-run: the discarded operation's turn + BOOST_TEST(alive.expired()); + BOOST_TEST(!called); + } + signal.emit(asio::cancellation_type::terminal); + BOOST_TEST(!called); + + { + asio::io_context elsewhere; + destroy_pool_with_job_queued(alive, called, [&](auto handler) { + return asio::bind_cancellation_slot( + signal.slot(), asio::bind_executor(elsewhere.get_executor(), std::move(handler))); + }); } + BOOST_TEST(alive.expired()); + BOOST_TEST(!called); + signal.emit(asio::cancellation_type::terminal); + + destroy_pool_with_job_queued(alive, called, [&](auto handler) { + return asio::bind_cancellation_slot(signal.slot(), std::move(handler)); + }); + BOOST_TEST(alive.expired()); + BOOST_TEST(!called); + signal.emit(asio::cancellation_type::terminal); + BOOST_TEST(!called); } -void heavy_operation_with_any_token() { - boost::asio::io_context caller; - boost::asio::thread_pool pool(1); - int received = 0; - auto operation = async_slow(pool.get_executor(), 41, boost::asio::deferred); - std::move(operation)(boost::asio::bind_executor( - caller.get_executor(), [&received](int result) { received = result; })); - caller.run(); // lint-run: waits for the pool's thread to post the completion +void heavy_tokens(asio::io_context& loop) { + { + // A callback without an executor of its own completes on the work executor. + asio::thread_pool pool(1); + std::atomic calls{0}; + std::atomic off_caller{false}; + std::atomic right{false}; + async_slow(pool.get_executor(), 1, [&](boost::system::error_code code, key value) { + ++calls; + off_caller = std::this_thread::get_id() != caller_thread; + right = !code && all_bytes(value, 1); + }); + pool.join(); + BOOST_TEST_EQ(calls.load(), 1); + BOOST_TEST(off_caller.load()); + BOOST_TEST(right.load()); + } + + asio::thread_pool pool(1); +#ifndef WEBCPP_CRYPTO_NO_EXCEPTIONS + std::future made = async_slow(pool.get_executor(), 2, asio::use_future); + BOOST_TEST(all_bytes(made.get(), 2)); + std::future refused = async_slow(pool.get_executor(), 0, asio::use_future); + bool thrown = false; + try { + static_cast(refused.get()); + } catch (boost::system::system_error const& failure) { + thrown = failure.code() == crypto::error::invalid_input_size; + } + BOOST_TEST(thrown); +#endif + + seen deferred; + auto operation = async_slow(pool.get_executor(), 3, asio::deferred); + std::move(operation)(recorder(loop, deferred)); + loop.restart(); + loop.run(); // lint-run: the test's event loop + BOOST_TEST_EQ(deferred.calls, 1); + BOOST_TEST(!deferred.code); + BOOST_TEST(all_bytes(deferred.value, 3)); + + int tuples = 0; + async_slow(pool.get_executor(), 4, + asio::as_tuple(asio::bind_executor( + loop.get_executor(), [&](std::tuple done) { + ++tuples; + BOOST_TEST(!std::get<0>(done)); + BOOST_TEST(all_bytes(std::get<1>(done), 4)); + }))); + async_slow(pool.get_executor(), 0, + asio::as_tuple(asio::bind_executor( + loop.get_executor(), [&](std::tuple done) { + ++tuples; + BOOST_TEST(std::get<0>(done) == crypto::error::invalid_input_size); + BOOST_TEST(all_bytes(std::get<1>(done), 0)); + }))); + loop.restart(); + loop.run(); // lint-run: the test's event loop + BOOST_TEST_EQ(tuples, 2); pool.join(); - BOOST_TEST_EQ(received, 42); } -/** An allocator the test recognises by its type; it allocates as std::allocator does. */ +// What a holding_allocator counts, shared by its rebound copies: the blocks it holds now, and +// every block it has given. +struct holding { + std::atomic held{0}; + std::atomic taken{0}; +}; + +// An allocator that counts the blocks it holds and gives; its deallocation may run on a pool's +// thread. Its blocks are the C library's, so that a call of operator new is never its own. template -struct tagged_allocator { +struct holding_allocator { using value_type = T; + holding* counts; - tagged_allocator() noexcept = default; + explicit holding_allocator(holding* counter) noexcept : counts(counter) {} + // Allocator rebind conversions must be implicit (Allocator requirements). template - explicit(false) tagged_allocator(tagged_allocator const& /*other*/) noexcept {} + // NOLINTNEXTLINE(misc-explicit-constructor) + holding_allocator(holding_allocator const& other) noexcept : counts(other.counts) {} - [[nodiscard]] T* allocate(std::size_t count) { return std::allocator{}.allocate(count); } + T* allocate(std::size_t count) { + static_assert(alignof(T) <= alignof(std::max_align_t), "malloc's alignment suffices"); + void* const block = std::malloc(count * sizeof(T)); + if (block == nullptr) { + webcpp_test_out_of_memory(); + } + counts->held.fetch_add(1); + counts->taken.fetch_add(1); + return static_cast(block); + } - void deallocate(T* pointer, std::size_t count) noexcept { - std::allocator{}.deallocate(pointer, count); + void deallocate(T* pointer, std::size_t /*count*/) noexcept { + std::free(pointer); + counts->held.fetch_sub(1); } - friend bool operator==(tagged_allocator const& /*left*/, - tagged_allocator const& /*right*/) noexcept { - return true; + template + bool operator==(holding_allocator const& other) const noexcept { + return counts == other.counts; } }; -/** What a recording executor saw of the functions it was given to run. */ -struct record { - /** How many functions it ran. */ - std::atomic functions{0}; - /** How many of them had the handler's allocator associated. */ - std::atomic allocators{0}; - /** How many of them had the handler's cancellation slot associated. */ - std::atomic slots{0}; +// What the handler of one call of heavy_allocator saw. +struct allocator_call { + int calls = 0; + int held_at_call = -1; + int taken = 0; + int jobs_held_at_call = -1; + std::size_t news = 0; + boost::system::error_code code; }; -/** An executor that records, of each function it runs, its associated allocator and - * cancellation slot, then runs it on `Inner`; properties are `Inner`'s. */ -template -class recording_executor { -public: - recording_executor(Inner inner, std::shared_ptr seen) noexcept - : inner_(std::move(inner)), seen_(std::move(seen)) {} - - template - void execute(Function&& function) const { - ++seen_->functions; - if constexpr (std::is_same_v< - std::decay_t, - tagged_allocator>) { - ++seen_->allocators; - } - if (boost::asio::get_associated_cancellation_slot(function).is_connected()) { - ++seen_->slots; - } - inner_.execute(std::forward(function)); - } +// The handler of one call of heavy_allocator: it records what the allocators hold when it runs, +// what was taken since it was made, and the calls of operator new since then. It names its +// executor, its allocator and its cancellation slot itself, as hash's test does: three binders +// nested make MSVC's compiler stop without a diagnostic. +struct held_handler { + using executor_type = asio::io_context::executor_type; + using allocator_type = holding_allocator; + using cancellation_slot_type = asio::cancellation_slot; - template - [[nodiscard]] auto query(Property const& property) const noexcept - -> decltype(boost::asio::query(std::declval(), property)) { - return boost::asio::query(inner_, property); - } + executor_type executor; + allocator_type allocator; + cancellation_slot_type slot; + holding* jobs; + allocator_call* call; + int taken_before; + std::size_t news_before; - template - [[nodiscard]] auto require(Property const& property) const -> recording_executor< - std::decay_t(), property))>> { - return {boost::asio::require(inner_, property), seen_}; - } + [[nodiscard]] executor_type get_executor() const noexcept { return executor; } - friend bool operator==(recording_executor const& left, - recording_executor const& right) noexcept { - return left.inner_ == right.inner_ && left.seen_ == right.seen_; - } + [[nodiscard]] allocator_type get_allocator() const noexcept { return allocator; } -private: - template - friend class recording_executor; + [[nodiscard]] cancellation_slot_type get_cancellation_slot() const noexcept { return slot; } - Inner inner_; - std::shared_ptr seen_; + void operator()(boost::system::error_code done, key /*value*/) const { + call->news = webcpp::test::counted_new.load() - news_before; + ++call->calls; + call->held_at_call = allocator.counts->held.load(); + call->taken = allocator.counts->taken.load() - taken_before; + call->jobs_held_at_call = jobs->held.load(); + call->code = done; + } }; -void carries_the_handlers_allocator_and_cancellation_slot() { - boost::asio::io_context caller; - boost::asio::thread_pool pool(1); - auto const work = std::make_shared(); - auto const completion = std::make_shared(); - boost::asio::cancellation_signal signal; - int received = 0; - crypto::detail::run_heavy( - recording_executor(pool.get_executor(), work), []() noexcept { return slow(41); }, - boost::asio::bind_cancellation_slot( - signal.slot(), - boost::asio::bind_allocator( - tagged_allocator{}, - boost::asio::bind_executor(recording_executor(caller.get_executor(), completion), - [&received](int result) { received = result; })))); - caller.run(); // lint-run: waits for the pool's thread to post the completion +// async_slow of `value` on `pool`, its job in storage of a holding_allocator over `jobs`, its +// handler on the loop's executor with `slot` and a holding_allocator over `counts`. +void start_held(asio::io_context& loop, asio::thread_pool& pool, holding& jobs, holding& counts, + std::uint8_t value, asio::cancellation_slot slot, allocator_call& call) { + auto const work = asio::require(pool.get_executor(), + asio::execution::allocator(holding_allocator(&jobs))); + held_handler handler{ + .executor = loop.get_executor(), + .allocator = holding_allocator(&counts), + .slot = slot, + .jobs = &jobs, + .call = &call, + .taken_before = counts.taken.load(), + .news_before = webcpp::test::counted_new.load(), + }; + async_slow(work, value, std::move(handler)); +} + +void heavy_allocator(asio::io_context& loop) { + holding counts; + holding jobs; + asio::thread_pool pool(1); + + // One uncounted call first, so that what the runtime makes once (a thread's first use of a + // facility) is outside the windows below. + allocator_call warm; + start_held(loop, pool, jobs, counts, 1, {}, warm); + loop.restart(); + loop.run(); // lint-run: the test's event loop + BOOST_TEST_EQ(warm.calls, 1); + + // The work done, no slot connected: the state and the completion are the handler's, the job + // the work executor's, and nothing calls operator new. + allocator_call done; + start_held(loop, pool, jobs, counts, 1, {}, done); + loop.restart(); + loop.run(); // lint-run: the test's event loop + BOOST_TEST_EQ(done.calls, 1); + BOOST_TEST(!done.code); + BOOST_TEST_EQ(done.held_at_call, 0); + BOOST_TEST_GE(done.taken, 2); + BOOST_TEST_EQ(done.news, 0U); + + // A guard's refusal: its post alone, the handler's. + allocator_call refused; + start_held(loop, pool, jobs, counts, 0, {}, refused); + loop.restart(); + loop.run(); // lint-run: the test's event loop + BOOST_TEST_EQ(refused.calls, 1); + BOOST_TEST(refused.code == crypto::error::invalid_input_size); + BOOST_TEST_EQ(refused.held_at_call, 0); + BOOST_TEST_GE(refused.taken, 1); + BOOST_TEST_EQ(refused.news, 0U); + + // The work done with a connected slot. The slot's cancellation handler is in the signal's + // storage, which Asio allocates itself (cancellation_slot::prepare_memory): operator new is + // not counted here. + asio::cancellation_signal done_signal; + allocator_call slotted; + start_held(loop, pool, jobs, counts, 1, done_signal.slot(), slotted); + loop.restart(); + loop.run(); // lint-run: the test's event loop + BOOST_TEST_EQ(slotted.calls, 1); + BOOST_TEST(!slotted.code); + BOOST_TEST_EQ(slotted.held_at_call, 0); + BOOST_TEST_GE(slotted.taken, 2); pool.join(); - BOOST_TEST_EQ(received, 42); - BOOST_TEST_EQ(work->functions.load(), 1); - BOOST_TEST_EQ(work->allocators.load(), 1); - BOOST_TEST_EQ(work->slots.load(), 1); - BOOST_TEST_EQ(completion->functions.load(), 1); - BOOST_TEST_EQ(completion->allocators.load(), 1); - BOOST_TEST_EQ(completion->slots.load(), 1); + + // A cancellation before the work starts, the pool held: the handler gets every block back, + // while the job, the work executor's, still waits in the pool's queue. + { + held_pool held; + asio::cancellation_signal signal; + allocator_call cancelled; + start_held(loop, held.pool, jobs, counts, 1, signal.slot(), cancelled); + signal.emit(asio::cancellation_type::terminal); + loop.restart(); + loop.run(); // lint-run: the test's event loop + BOOST_TEST_EQ(cancelled.calls, 1); + BOOST_TEST(cancelled.code == asio::error::operation_aborted); + BOOST_TEST_EQ(cancelled.held_at_call, 0); + BOOST_TEST_GE(cancelled.taken, 2); + BOOST_TEST_EQ(cancelled.jobs_held_at_call, 1); + } + + // A cancellation once the work has started. + { + asio::thread_pool one(1); + engage_latch(); + asio::cancellation_signal signal; + allocator_call running; + start_held(loop, one, jobs, counts, 1, signal.slot(), running); + wait_until_entered(); + signal.emit(asio::cancellation_type::terminal); + open_latch(); + loop.restart(); + loop.run(); // lint-run: the test's event loop + BOOST_TEST_EQ(running.calls, 1); + BOOST_TEST(running.code == asio::error::operation_aborted); + BOOST_TEST_EQ(running.held_at_call, 0); + BOOST_TEST_GE(running.taken, 2); + one.join(); + } + BOOST_TEST_EQ(counts.held.load(), 0); + BOOST_TEST_EQ(jobs.held.load(), 0); + BOOST_TEST_GE(jobs.taken.load(), 4); } } // namespace int main() { - runs_elsewhere_and_completes_on_the_caller(); - move_only_result(); - heavy_operation_with_any_token(); - carries_the_handlers_allocator_and_cancellation_slot(); + caller_thread = std::this_thread::get_id(); + asio::io_context loop; + asio::thread_pool pool(2); + heavy_runs_on_pool(loop, pool); + heavy_loop_goes_on(loop, pool); + pool.join(); + heavy_guard_refused(loop); + heavy_cancel_before_start(loop); + heavy_cancel_while_running(loop); + heavy_signal_outlives(); + heavy_tokens(loop); + heavy_allocator(loop); return webcpp::test::exit_status(boost::report_errors()); } diff --git a/test/messages/heavy_without_threads/heavy_without_threads.cpp b/test/messages/heavy_without_threads/heavy_without_threads.cpp index a875466c..986327b1 100644 --- a/test/messages/heavy_without_threads/heavy_without_threads.cpp +++ b/test/messages/heavy_without_threads/heavy_without_threads.cpp @@ -8,7 +8,7 @@ // WEBCPP_CRYPTO_NO_THREADS; on WASI always) stops where it is called, with the synchronous // operation to call instead (design D23). The operation is a test's own, declared as every heavy // operation declares its variant. The refusal is the first error (heavy_without_threads_first -// pins the order); detail::run_heavy's stand-in adds its own after it, which defers to an error +// pins the order); detail::run_on_work's stand-in adds its own after it, which defers to an error // above that names the synchronous call. The test is alone: these two errors are the compile's // only ones. The refusal's directive comes last, as the message the page shows // (doc/tables/generate.py reads a test's last directive). @@ -20,22 +20,22 @@ #include -#include +#include namespace { /** The test-only heavy operation, synchronous. */ -int slow(int value) noexcept { +boost::system::result slow(int value) noexcept { return value + 1; } /** Its async_ variant, as every heavy operation declares one. */ template -auto async_slow(Executor executor, int value, CompletionToken&& token) { +auto async_slow(Executor const& work, int value, CompletionToken&& token) { WEBCPP_CRYPTO_DETAIL_REQUIRE_THREADS("async_slow", "slow"); - return webcpp::crypto::detail::run_heavy( - std::move(executor), [value]() noexcept { return slow(value); }, - std::forward(token)); + return webcpp::crypto::detail::run_on_work( + work, []() noexcept { return boost::system::result(); }, + [value]() noexcept { return slow(value); }, token); } /** An executor and a completion token, which a build without threads never uses. */ @@ -47,5 +47,5 @@ struct token {}; int main() { async_slow(executor{}, 41, token{}); - return slow(0) == 1 ? 0 : 1; + return *slow(0) == 1 ? 0 : 1; } diff --git a/test/messages/heavy_without_threads_first/heavy_without_threads_first.cpp b/test/messages/heavy_without_threads_first/heavy_without_threads_first.cpp index d64c573a..447c2a14 100644 --- a/test/messages/heavy_without_threads_first/heavy_without_threads_first.cpp +++ b/test/messages/heavy_without_threads_first/heavy_without_threads_first.cpp @@ -6,7 +6,7 @@ // heavy_without_threads' program compiled with -ferror-limit=1: clang stops after the first // error, so the refusal that names the synchronous call is that first error, before -// detail::run_heavy's stand-in, whose text defers to "an error above". The test is alone: the +// detail::run_on_work's stand-in, whose text defers to "an error above". The test is alone: the // refusal and clang's fatal "too many errors emitted" are the compile's only errors, so a // regression that puts the stand-in, or any other error, first fails it. -verify cannot order // its directives; the limit does. The refusal's directive comes last, as the message the page @@ -19,22 +19,22 @@ #include -#include +#include namespace { /** The test-only heavy operation, synchronous. */ -int slow(int value) noexcept { +boost::system::result slow(int value) noexcept { return value + 1; } /** Its async_ variant, as every heavy operation declares one. */ template -auto async_slow(Executor executor, int value, CompletionToken&& token) { +auto async_slow(Executor const& work, int value, CompletionToken&& token) { WEBCPP_CRYPTO_DETAIL_REQUIRE_THREADS("async_slow", "slow"); - return webcpp::crypto::detail::run_heavy( - std::move(executor), [value]() noexcept { return slow(value); }, - std::forward(token)); + return webcpp::crypto::detail::run_on_work( + work, []() noexcept { return boost::system::result(); }, + [value]() noexcept { return slow(value); }, token); } /** An executor and a completion token, which a build without threads never uses. */ @@ -46,5 +46,5 @@ struct token {}; int main() { async_slow(executor{}, 41, token{}); - return slow(0) == 1 ? 0 : 1; + return *slow(0) == 1 ? 0 : 1; } diff --git a/test/msvc/heavy_without_threads/app.cpp b/test/msvc/heavy_without_threads/app.cpp index 9c2d89d6..916bbe83 100644 --- a/test/msvc/heavy_without_threads/app.cpp +++ b/test/msvc/heavy_without_threads/app.cpp @@ -8,20 +8,20 @@ // on MSVC the compile fails. The text is checked on clang, in test/messages/heavy_without_threads. #include -#include +#include namespace { -int slow(int value) noexcept { +boost::system::result slow(int value) noexcept { return value + 1; } template -auto async_slow(Executor executor, int value, CompletionToken&& token) { +auto async_slow(Executor const& work, int value, CompletionToken&& token) { WEBCPP_CRYPTO_DETAIL_REQUIRE_THREADS("async_slow", "slow"); - return webcpp::crypto::detail::run_heavy( - std::move(executor), [value]() noexcept { return slow(value); }, - std::forward(token)); + return webcpp::crypto::detail::run_on_work( + work, []() noexcept { return boost::system::result(); }, + [value]() noexcept { return slow(value); }, token); } struct executor {}; @@ -32,5 +32,5 @@ struct token {}; int main() { async_slow(executor{}, 41, token{}); - return slow(0) == 1 ? 0 : 1; + return *slow(0) == 1 ? 0 : 1; } From 9da0387c907d4a1b9a30630b9888cbb7a155c439 Mon Sep 17 00:00:00 2001 From: R Date: Sat, 21 Nov 2026 21:27:41 -0300 Subject: [PATCH 02/14] crypto: the heavy job's allocator is chosen lazily, with a type-erased work executor tested, and a heavy operation's value must move without throwing --- include/webcpp/crypto/detail/heavy.hpp | 34 ++++++++++++++++++++++---- test/heavy_test.cpp | 20 +++++++++++++-- 2 files changed, 47 insertions(+), 7 deletions(-) diff --git a/include/webcpp/crypto/detail/heavy.hpp b/include/webcpp/crypto/detail/heavy.hpp index 82a21115..1c344ef9 100644 --- a/include/webcpp/crypto/detail/heavy.hpp +++ b/include/webcpp/crypto/detail/heavy.hpp @@ -167,12 +167,33 @@ struct heavy_value {}; * * @tparam WorkExecutor The work executor. */ +template >> +struct heavy_job_allocator_of { + /** An executor that does not answer the query: Asio's recycling `std::allocator`. */ + using type = std::allocator; +}; + +/** + * The allocator of a work executor that answers the query, named only then. + * + * @tparam WorkExecutor The work executor. + */ +template +struct heavy_job_allocator_of { + /** The executor's own allocator. */ + using type = + std::decay_t>>; +}; + +/** + * The allocator of a heavy operation's job, as @ref heavy_job_allocator_of chooses it. + * + * @tparam WorkExecutor The work executor. + */ template -using heavy_job_allocator_t = std::conditional_t< - webcpp::asio::can_query_v>, - std::decay>>, - std::type_identity>>::type; +using heavy_job_allocator_t = heavy_job_allocator_of::type; /** * The work executor's allocator, for its job. @@ -654,6 +675,9 @@ auto run_on_work(WorkExecutor const& work, Guards guards, Work run, CompletionTo "webcpp::crypto: a heavy operation's guards return boost::system::result"); static_assert(std::is_nothrow_invocable_v, "webcpp::crypto: a heavy operation's call reports its errors as values"); + using value_type = completion_of>::value_type; + static_assert(std::is_void_v || std::is_nothrow_move_constructible_v, + "webcpp::crypto: a heavy operation's value moves without failing"); using signature = completion_of>::type; return webcpp::asio_backend::async_initiate( heavy_initiation{}, token, work, std::move(guards), std::move(run)); diff --git a/test/heavy_test.cpp b/test/heavy_test.cpp index c74be318..177c738d 100644 --- a/test/heavy_test.cpp +++ b/test/heavy_test.cpp @@ -26,7 +26,8 @@ // to the loop (which then runs, or is destroyed without running) or has no executor of its own, // and the signal emitted after it reaches nothing. // - heavy_tokens: a callback without an executor of its own (completing on the pool), use_future -// (in the build with exceptions, a refusal thrown as system_error), deferred and as_tuple. +// (in the build with exceptions, a refusal thrown as system_error), deferred and as_tuple; and +// a type-erased work executor (any_io_executor), whose job falls back to std::allocator. // - heavy_allocator: the handler's associated allocator, bound by bind_allocator, holds the // operation's state and every completion, and gets every block back before the handler runs, on // each way an operation completes; the job queued in the pool is the work executor's, given @@ -39,6 +40,7 @@ #include "support/counting.hpp" +#include #include #include #include @@ -69,6 +71,7 @@ #include #include #include +#include #include #ifndef WEBCPP_CRYPTO_HAS_THREADS @@ -282,7 +285,6 @@ void heavy_guard_refused(asio::io_context& loop) { held_pool held; int const before = runs(); seen refused; - refused.value = key{}; async_slow(held.pool.get_executor(), 0, recorder(loop, refused)); BOOST_TEST_EQ(refused.calls, 0); loop.restart(); @@ -487,6 +489,20 @@ void heavy_tokens(asio::io_context& loop) { BOOST_TEST(!deferred.code); BOOST_TEST(all_bytes(deferred.value, 3)); + // A type-erased work executor, which does not answer the allocator query: the job's storage + // is then Asio's recycling std::allocator. + static_assert(std::is_same_v, + std::allocator>); + asio::any_io_executor const erased_work(pool.get_executor()); + seen erased; + async_slow(erased_work, 6, recorder(loop, erased)); + loop.restart(); + loop.run(); // lint-run: the test's event loop + BOOST_TEST_EQ(erased.calls, 1); + BOOST_TEST(!erased.code); + BOOST_TEST(erased.thread == caller_thread); + BOOST_TEST(all_bytes(erased.value, 6)); + int tuples = 0; async_slow(pool.get_executor(), 4, asio::as_tuple(asio::bind_executor( From 4a7450bf97aa21024fbf1ff6ebeefa8c61686981 Mon Sep 17 00:00:00 2001 From: R Date: Sat, 21 Nov 2026 21:44:30 -0300 Subject: [PATCH 03/14] crypto: async.hpp's base, completions posted on every target, and the seam the browser backend fills --- include/webcpp/crypto/async.hpp | 168 +++++++++++ test/Jamfile | 12 +- test/async_post_test.cpp | 468 +++++++++++++++++++++++++++++++ test/convenience_header_test.cpp | 8 +- 4 files changed, 653 insertions(+), 3 deletions(-) create mode 100644 include/webcpp/crypto/async.hpp create mode 100644 test/async_post_test.cpp diff --git a/include/webcpp/crypto/async.hpp b/include/webcpp/crypto/async.hpp new file mode 100644 index 00000000..86cdeb10 --- /dev/null +++ b/include/webcpp/crypto/async.hpp @@ -0,0 +1,168 @@ +// 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 family (design D23), webcpp::hash's ``'s twin: each + function an Asio asynchronous operation in webcpp::asio's model, initiated through + `async_initiate`, so that one call works with a callback, `use_awaitable`, Cobalt's `use_op`, + `deferred`, `as_tuple`, `use_future` and every other completion token. An operation that returns + a value completes with `void(boost::system::error_code, T)`, the value second, and on an error + the empty object a move leaves (a `secret` or an array of zeros, a `gcm` or a key pair without + a key, whose every member refuses with `invalid_state`); one without a value completes with + `void(boost::system::error_code)`. + + - The cheap functions exist on every target, for the algorithms the browser's WebCrypto has. + Each takes the executor its completion is posted to first. On a synchronous backend, their + default, they run the synchronous call at once (its guards and its work, on the caller's + thread) and complete through a post to that executor, whence the completion reaches the + handler's associated executor, never inside the initiating call. + - The heavy functions (design D32's list) take the work executor first (a + `webcpp::asio::thread_pool`'s): they check their guards on the caller's thread, run the work on + the work executor and complete on the handler's associated executor, with webcpp::hash's + cancellation rules (`detail/heavy.hpp`). They exist only where the build has threads + (`WEBCPP_CRYPTO_HAS_THREADS`); elsewhere each name refuses at compile time. + + The default backend of each is the synchronous function's, `default_async_backend_t`, + `default_backend_t` on every target, Emscripten included: the browser's backend is used + only where a type names it, so that one program gives the same bytes on every target. + + What a call reads (the object, the spans) is the caller's until the completion: a synchronous + backend reads it before the call returns, the browser's later. + + The header needs webcpp::asio, `/webcpp/asio//asio` in the program's Jamfile, which + `` does not bring: include it by itself. + + @code + // exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//gcm-default /webcpp/asio//asio ; + // A coroutine seals in place on the default backend; the completion, the error code and the + // tag, is posted to the coroutine's executor. + namespace asio = webcpp::asio; + auto const executor = co_await asio::this_coro::executor; + auto [code, tag] = co_await webcpp::crypto::async_seal(executor, aead, iv, ad, data, + asio::as_tuple(asio::use_awaitable)); + @endcode + + @see "Asynchronous calls", in the guide. +*/ +#ifndef WEBCPP_CRYPTO_ASYNC_HPP +#define WEBCPP_CRYPTO_ASYNC_HPP + +#include + +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include +#include + +#include +#include + +namespace webcpp::crypto { + +/** + * The backend of the asynchronous family when a call names none (ruling R-A4): the synchronous + * function's, `default_backend_t`, on every target, Emscripten included. The browser's + * backend is never a default: a program names it in the type to reach WebCrypto. + * + * @tparam Family A family tag of `families` that has a default. + */ +template +using default_async_backend_t = default_backend_t; + +namespace detail { + +/** + * Whether `Backend` completes by itself, asynchronously: no backend yet; part B's + * `backends::browser` alone will, through @ref async_engine. + * + * @tparam Backend A backend. + */ +template +inline constexpr bool asynchronous_backend_v = false; + +/** + * The operations of a backend that completes by itself: part B specialises it for + * `backends::browser`, with a static member function per asynchronous function, taking its + * arguments and returning its result. Declared only: no synchronous backend reaches it. + * + * @tparam Backend `backends::browser`. + */ +template +struct async_engine; + +/** + * The initiation of a cheap function on a synchronous backend: runs the synchronous call (its + * guards first) at once and posts the completion, its result split by @ref completion_of, to + * `executor`, whence it reaches the handler's associated executor; the post's storage is the + * handler's associated allocator's. + */ +struct post_initiation { + /** + * Runs `operation` and posts `handler` with its error code and, for a call that returns a + * value, the value, or on an error the empty one (ruling R-A3). + * + * @param handler The completion handler. + * @param executor The executor the completion is posted to. + * @param operation The synchronous call, bound to its arguments. + */ + template + void operator()(Handler&& handler, Executor const& executor, Operation operation) const { + auto done = operation(); + using value_type = completion_of::value_type; + if constexpr (std::is_void_v) { + boost::system::error_code const code = + done ? boost::system::error_code{} : done.error(); + webcpp::asio::post(executor, + webcpp::asio::append(std::forward(handler), code)); + } else if (done) { + webcpp::asio::post(executor, + webcpp::asio::append(std::forward(handler), + boost::system::error_code{}, std::move(*done))); + } else { + webcpp::asio::post(executor, + webcpp::asio::append(std::forward(handler), done.error(), + async_access::empty())); + } + } +}; + +/** + * Initiates a cheap function on a synchronous backend (design D23): runs `operation()` at once, + * on the caller's thread, and completes through a post to `executor`, never inside the call, + * with `operation()`'s result split into its error code and its value. + * + * @tparam CompletionToken Any completion token, of signature `completion_of::type`, `R` + * `operation()`'s result. + * @param executor The executor the completion is posted to, whence it reaches the handler's + * associated executor. + * @param token The completion token. + * @param operation The synchronous call, bound to its arguments: a `noexcept` call without + * arguments returning `boost::system::result` or `boost::system::result`, called once. + * @return What the completion token's `async_result` gives. + */ +template +auto complete_by_post(Executor const& executor, CompletionToken& token, Operation operation) { + static_assert(std::is_nothrow_invocable_v, + "webcpp::crypto: an asynchronous operation's call reports its errors as values"); + using signature = completion_of>::type; + return webcpp::asio_backend::async_initiate( + post_initiation{}, token, executor, std::move(operation)); +} + +} // namespace detail + +} // namespace webcpp::crypto + +#endif // WEBCPP_CRYPTO_ASYNC_HPP diff --git a/test/Jamfile b/test/Jamfile index 785fd491..673ecd9d 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -36,8 +36,9 @@ webcpp.headers-alone crypto : ../include : crypto.hpp crypto/config.hpp crypto/detail/async_access.hpp crypto/detail/timing.hpp crypto/ciphers/aead.hpp crypto/ciphers/chacha20_poly1305.hpp crypto/ciphers/secretbox.hpp crypto/pem.hpp ; # detail/heavy.hpp compiles alone only with webcpp::asio, which it includes -# where the build has threads. -webcpp.headers-alone crypto : ../include : crypto/detail/heavy.hpp +# where the build has threads; async.hpp, which includes it, only with +# webcpp::asio on every target. +webcpp.headers-alone crypto : ../include : crypto/detail/heavy.hpp crypto/async.hpp : /webcpp/asio//asio ; # The backend BearSSL's header and the default backend's, with BearSSL linked, @@ -108,6 +109,13 @@ crypto-run heavy : heavy_test.cpp : /webcpp/asio//asio multi emscripten:-sPTHREAD_POOL_SIZE=3 : native emscripten ; +# The cheap functions of the asynchronous family on a synchronous backend, on +# every target: detail::complete_by_post runs the call at once and completes +# through a post, on the handler's associated executor and in its associated +# allocator, with every completion token (use_future where exceptions are on). +crypto-run async_post : async_post_test.cpp + : /webcpp/asio//asio /webcpp/crypto//gcm-default + /third_party//sodium ; # Without threads (WEBCPP_CRYPTO_NO_THREADS natively; WASI has none), a heavy # operation's async_ variant that forgets its refusal stops at # detail::run_on_work's stand-in, which names the refusal, and with that diff --git a/test/async_post_test.cpp b/test/async_post_test.cpp new file mode 100644 index 00000000..5c4141e4 --- /dev/null +++ b/test/async_post_test.cpp @@ -0,0 +1,468 @@ +// 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 cheap functions of the asynchronous family on a synchronous backend (ruling R-A4: the +// default everywhere), through detail::complete_by_post, the initiation each of them makes: the +// synchronous call runs at once, inside the initiating call, and its result, split by +// detail::completion_of, completes through a post, never inside the call (rulings R-A2, R-A3). +// Three test-only operations, declared as the family's functions are, exercise it on every +// result shape: async_key (a secret<32> of bytes all `value`), async_block (an array of 64 bytes +// all `value`) and async_check (no value); each refuses `value == 0` with invalid_input_size. +// - post_never_inline: a flag the callback sets is unset when the call returns and set after +// run; the synchronous call has run once when the call returns. +// - post_bound_executor: with one io_context's executor given and the handler bound to a second +// io_context, the completion runs on the second (review focus 1), never on the first. +// - post_allocator: the handler's associated allocator, bound by bind_allocator, holds the post, +// and has every block back before the handler runs; the replaced global operator new +// (support/counting.hpp) is not called. +// - post_tokens: a callback, use_future (in the build with exceptions alone, a refusal thrown as +// system_error), deferred (the call runs when the operation is launched), as_tuple, and +// use_awaitable in a coroutine of the context (a refusal through as_tuple; with exceptions a +// plain use_awaitable throws). +// - post_error_value: an error completes with its code and the empty value (ruling R-A3): a +// secret<32> and an array of zeros. +// Tasks 4.A3 and 4.A4 add async_seal's and async_verify's cases to each check: each check takes +// the operation's start as a callable of (executor, token). + +#include +#include +#include +#include + +#include "support/counting.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#ifndef WEBCPP_CRYPTO_NO_EXCEPTIONS +#include +#endif + +#include +#include +#include +#ifndef WEBCPP_CRYPTO_NO_EXCEPTIONS +#include +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace asio = webcpp::asio; +namespace crypto = webcpp::crypto; + +namespace { + +using key = crypto::secret<32>; +using block = std::array; + +// How many times a test-only operation's synchronous call has run. +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables): counted by the calls +int sync_runs = 0; + +/** The synchronous call of async_key: a secret of bytes all `value`, 0 refused. */ +boost::system::result make_key(std::uint8_t value) noexcept { + ++sync_runs; + if (value == 0) { + return crypto::error::invalid_input_size; + } + key made; + std::ranges::fill(made.writable(), value); + return made; +} + +/** The synchronous call of async_block: 64 bytes all `value`, 0 refused. */ +boost::system::result make_block(std::uint8_t value) noexcept { + ++sync_runs; + if (value == 0) { + return crypto::error::invalid_input_size; + } + block made{}; + made.fill(value); + return made; +} + +/** The synchronous call of async_check: no value, 0 refused. */ +boost::system::result check(std::uint8_t value) noexcept { + ++sync_runs; + if (value == 0) { + return crypto::error::invalid_input_size; + } + return {}; +} + +/** A cheap operation completing with `void(error_code, secret<32>)`, as the family declares. */ +template +auto async_key(Executor const& executor, std::uint8_t value, CompletionToken&& token) { + return crypto::detail::complete_by_post(executor, token, + [value]() noexcept { return make_key(value); }); +} + +/** A cheap operation completing with `void(error_code, std::array)`. */ +template +auto async_block(Executor const& executor, std::uint8_t value, CompletionToken&& token) { + return crypto::detail::complete_by_post(executor, token, + [value]() noexcept { return make_block(value); }); +} + +/** A cheap operation completing with `void(error_code)`. */ +template +auto async_check(Executor const& executor, std::uint8_t value, CompletionToken&& token) { + return crypto::detail::complete_by_post(executor, token, + [value]() noexcept { return check(value); }); +} + +/** Whether every byte of `bytes` is `value`. */ +template +bool all_bytes(Bytes const& bytes, std::uint8_t value) { + return std::ranges::all_of(bytes, [value](std::uint8_t byte) { return byte == value; }); +} + +bool all_bytes(key const& made, std::uint8_t value) { + return all_bytes(made.bytes(), value); +} + +// What a callback saw: its calls, whether the initiating call had returned, the error code and +// the value, if the operation has one. +template +struct seen { + int calls = 0; + bool after_return = false; + boost::system::error_code code; + std::tuple value; +}; + +// Starts `start(executor, token)` with a callback, checks that the synchronous call ran inside +// the call and the completion did not, then runs the context and checks one completion after +// the return. +template +seen complete_by_callback(asio::io_context& context, Start start) { + seen done; + bool returned = false; + int const runs_before = sync_runs; + start(context.get_executor(), + [&done, &returned](boost::system::error_code code, Value... value) { + ++done.calls; + done.after_return = returned; + done.code = code; + done.value = std::tuple(std::move(value)...); + }); + returned = true; + BOOST_TEST_EQ(done.calls, 0); // never inside the call + BOOST_TEST_EQ(sync_runs, runs_before + 1); // the synchronous call ran at once + context.restart(); + context.run(); // lint-run: the test's event loop + BOOST_TEST_EQ(done.calls, 1); + BOOST_TEST(done.after_return); + return done; +} + +// The starts of the test-only operations, of `value`. +auto key_of(std::uint8_t value) { + return [value](auto const& executor, auto&& token) { + return async_key(executor, value, std::forward(token)); + }; +} + +auto block_of(std::uint8_t value) { + return [value](auto const& executor, auto&& token) { + return async_block(executor, value, std::forward(token)); + }; +} + +auto check_of(std::uint8_t value) { + return [value](auto const& executor, auto&& token) { + return async_check(executor, value, std::forward(token)); + }; +} + +void post_never_inline(asio::io_context& context) { + auto const made = complete_by_callback(context, key_of(0x42)); + BOOST_TEST(!made.code); + BOOST_TEST(all_bytes(std::get<0>(made.value), 0x42)); + auto const filled = complete_by_callback(context, block_of(0x17)); + BOOST_TEST(!filled.code); + BOOST_TEST(all_bytes(std::get<0>(filled.value), 0x17)); + auto const checked = complete_by_callback<>(context, check_of(1)); + BOOST_TEST(!checked.code); +} + +// One start given the executor of `given`, its handler bound to `bound`: the completion runs on +// `bound` alone, after `given` has run. +template +void complete_on_bound(Start start) { + asio::io_context given; + asio::io_context bound; + int calls = 0; + bool on_bound = false; + bool on_given = true; + start(given.get_executor(), + asio::bind_executor(bound.get_executor(), [&](boost::system::error_code code, Value...) { + ++calls; + on_bound = bound.get_executor().running_in_this_thread(); + on_given = given.get_executor().running_in_this_thread(); + BOOST_TEST(!code); + })); + given.run(); // lint-run: the test's event loop, which hands the completion over + BOOST_TEST_EQ(calls, 0); + bound.run(); // lint-run: the event loop the handler is bound to + BOOST_TEST_EQ(calls, 1); + BOOST_TEST(on_bound); + BOOST_TEST(!on_given); +} + +void post_bound_executor() { + complete_on_bound(key_of(3)); + complete_on_bound(block_of(3)); + complete_on_bound<>(check_of(3)); +} + +// What a holding_allocator counts, shared by its rebound copies: the blocks it holds now, and +// every block it has given. +struct holding { + int held = 0; + int taken = 0; +}; + +// An allocator that counts the blocks it holds and gives. Its blocks are the C library's, so +// that a call of operator new is never its own. +template +struct holding_allocator { + using value_type = T; + holding* counts; + + explicit holding_allocator(holding* counter) noexcept : counts(counter) {} + + // Allocator rebind conversions must be implicit (Allocator requirements). + template + // NOLINTNEXTLINE(misc-explicit-constructor) + holding_allocator(holding_allocator const& other) noexcept : counts(other.counts) {} + + T* allocate(std::size_t count) { + static_assert(alignof(T) <= alignof(std::max_align_t), "malloc's alignment suffices"); + void* const block = std::malloc(count * sizeof(T)); + if (block == nullptr) { + webcpp_test_out_of_memory(); + } + ++counts->held; + ++counts->taken; + return static_cast(block); + } + + void deallocate(T* pointer, std::size_t /*count*/) noexcept { + std::free(pointer); + --counts->held; + } + + template + bool operator==(holding_allocator const& other) const noexcept { + return counts == other.counts; + } +}; + +// What the handler of one counted start saw. +struct allocator_call { + int calls = 0; + int held_at_call = -1; + int taken = 0; + std::size_t news = 0; + boost::system::error_code code; +}; + +// One start with a handler whose associated allocator holds; `call` records what the allocator +// holds when the handler runs, what it gave since the start, and the calls of operator new. +template +void start_counted(asio::io_context& context, Start start, allocator_call& call) { + holding counts; + std::size_t const news_before = webcpp::test::counted_new.load(); + start(context.get_executor(), + asio::bind_allocator( + holding_allocator(&counts), + [&call, &counts, news_before](boost::system::error_code code, Value...) { + call.news = webcpp::test::counted_new.load() - news_before; + ++call.calls; + call.held_at_call = counts.held; + call.taken = counts.taken; + call.code = code; + })); + context.restart(); + context.run(); // lint-run: the test's event loop + BOOST_TEST_EQ(counts.held, 0); +} + +// The start's success and its refusal each post through the handler's allocator alone. +template +void check_allocator(asio::io_context& context, Start made, Start refused) { + allocator_call done; + start_counted(context, made, done); + BOOST_TEST_EQ(done.calls, 1); + BOOST_TEST(!done.code); + BOOST_TEST_EQ(done.held_at_call, 0); + BOOST_TEST_GE(done.taken, 1); + BOOST_TEST_EQ(done.news, 0U); + + allocator_call failed; + start_counted(context, refused, failed); + BOOST_TEST_EQ(failed.calls, 1); + BOOST_TEST(failed.code == crypto::error::invalid_input_size); + BOOST_TEST_EQ(failed.held_at_call, 0); + BOOST_TEST_GE(failed.taken, 1); + BOOST_TEST_EQ(failed.news, 0U); +} + +void post_allocator(asio::io_context& context) { + // One uncounted call first, so that what the runtime makes once is outside the windows. + allocator_call warm; + start_counted(context, key_of(1), warm); + BOOST_TEST_EQ(warm.calls, 1); + + check_allocator(context, key_of(1), key_of(0)); + check_allocator(context, block_of(1), block_of(0)); + check_allocator<>(context, check_of(1), check_of(0)); +} + +void post_tokens(asio::io_context& context) { + auto const executor = context.get_executor(); + +#ifndef WEBCPP_CRYPTO_NO_EXCEPTIONS + // use_future: a single-threaded program runs the context before get(). + auto made = async_key(executor, 5, asio::use_future); + auto filled = async_block(executor, 5, asio::use_future); + auto checked = async_check(executor, 5, asio::use_future); + auto refused = async_key(executor, 0, asio::use_future); + context.restart(); + context.run(); // lint-run: the test's event loop + BOOST_TEST(all_bytes(made.get(), 5)); + BOOST_TEST(all_bytes(filled.get(), 5)); + checked.get(); + bool thrown = false; + try { + static_cast(refused.get()); + } catch (boost::system::system_error const& failure) { + thrown = failure.code() == crypto::error::invalid_input_size; + } + BOOST_TEST(thrown); +#endif + + // deferred: the operation runs when it is launched, and completes through the post. + int const runs_before = sync_runs; + auto operation = async_key(executor, 6, asio::deferred); + BOOST_TEST_EQ(sync_runs, runs_before); + int deferred_calls = 0; + std::move(operation)([&](boost::system::error_code code, key value) { + ++deferred_calls; + BOOST_TEST(!code); + BOOST_TEST(all_bytes(value, 6)); + }); + BOOST_TEST_EQ(sync_runs, runs_before + 1); + BOOST_TEST_EQ(deferred_calls, 0); + auto checking = async_check(executor, 0, asio::deferred); + std::move(checking)([&](boost::system::error_code code) { + ++deferred_calls; + BOOST_TEST(code == crypto::error::invalid_input_size); + }); + context.restart(); + context.run(); // lint-run: the test's event loop + BOOST_TEST_EQ(deferred_calls, 2); + + // as_tuple: the error code and the value in one argument. + int tuples = 0; + async_block(executor, 7, asio::as_tuple([&](std::tuple done) { + ++tuples; + BOOST_TEST(!std::get<0>(done)); + BOOST_TEST(all_bytes(std::get<1>(done), 7)); + })); + async_check(executor, 0, asio::as_tuple([&](std::tuple done) { + ++tuples; + BOOST_TEST(std::get<0>(done) == crypto::error::invalid_input_size); + })); + context.restart(); + context.run(); // lint-run: the test's event loop + BOOST_TEST_EQ(tuples, 2); + + // use_awaitable in a coroutine of the context. + bool done = false; + asio::co_spawn( + context, + [&]() -> asio::awaitable { + auto const coro = co_await asio::this_coro::executor; + auto [made_code, made_key] = + co_await async_key(coro, 8, asio::as_tuple(asio::use_awaitable)); + BOOST_TEST(!made_code); + BOOST_TEST(all_bytes(made_key, 8)); + auto [refused_code, refused_block] = + co_await async_block(coro, 0, asio::as_tuple(asio::use_awaitable)); + BOOST_TEST(refused_code == crypto::error::invalid_input_size); + BOOST_TEST(all_bytes(refused_block, 0)); + auto [checked_code] = + co_await async_check(coro, 8, asio::as_tuple(asio::use_awaitable)); + BOOST_TEST(!checked_code); +#ifndef WEBCPP_CRYPTO_NO_EXCEPTIONS + key const awaited = co_await async_key(coro, 9, asio::use_awaitable); + BOOST_TEST(all_bytes(awaited, 9)); + co_await async_check(coro, 9, asio::use_awaitable); + bool thrown = false; + try { + co_await async_check(coro, 0, asio::use_awaitable); + } catch (boost::system::system_error const& failure) { + thrown = failure.code() == crypto::error::invalid_input_size; + } + BOOST_TEST(thrown); +#endif + done = true; + }, + [](std::exception_ptr const& failure) { BOOST_TEST(!failure); }); + context.restart(); + context.run(); // lint-run: the test's event loop + BOOST_TEST(done); +} + +void post_error_value(asio::io_context& context) { + auto const refused_key = complete_by_callback(context, key_of(0)); + BOOST_TEST(refused_key.code == crypto::error::invalid_input_size); + BOOST_TEST(all_bytes(std::get<0>(refused_key.value), 0)); + auto const refused_block = complete_by_callback(context, block_of(0)); + BOOST_TEST(refused_block.code == crypto::error::invalid_input_size); + BOOST_TEST(all_bytes(std::get<0>(refused_block.value), 0)); + auto const refused_check = complete_by_callback<>(context, check_of(0)); + BOOST_TEST(refused_check.code == crypto::error::invalid_input_size); +} + +// The asynchronous default is the synchronous one, on every target (ruling R-A4), and no +// synchronous backend completes by itself: part B's backends::browser alone will. +template +constexpr bool same_default = + std::is_same_v, crypto::default_backend_t>; +static_assert(same_default && same_default && + same_default); +static_assert(!crypto::detail::asynchronous_backend_v && + !crypto::detail::asynchronous_backend_v && + !crypto::detail::asynchronous_backend_v); + +} // namespace + +int main() { + asio::io_context context; + post_never_inline(context); + post_bound_executor(); + post_allocator(context); + post_tokens(context); + post_error_value(context); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/convenience_header_test.cpp b/test/convenience_header_test.cpp index 025f7872..f3905e24 100644 --- a/test/convenience_header_test.cpp +++ b/test/convenience_header_test.cpp @@ -5,7 +5,9 @@ // https://www.boost.org/LICENSE_1_0.txt) // The convenience header with no backend linked compiles, links and runs (spec section 2.1): this -// program includes alone, names no backend, links none, and calls equal. +// program includes alone, names no backend, links none, and calls equal. The +// convenience header leaves the asynchronous family out: needs +// webcpp::asio, which the program would then link. #include #include @@ -22,6 +24,10 @@ #error "this program links no backend: its project must not name one" #endif +#ifdef WEBCPP_CRYPTO_ASYNC_HPP +#error " must not include , which needs webcpp::asio" +#endif + int main() { std::array const zero{}; std::array other{}; From 824067618b26990c8333588692cddef30a22e972 Mon Sep 17 00:00:00 2001 From: R Date: Sat, 21 Nov 2026 22:00:51 -0300 Subject: [PATCH 04/14] crypto: AES-GCM's asynchronous make, seal and open, posted on every target --- include/webcpp/crypto/async.hpp | 175 +++++++++- include/webcpp/crypto/ciphers/gcm.hpp | 4 + test/Jamfile | 18 +- test/async_gcm_test.cpp | 330 ++++++++++++++++++ test/async_post_test.cpp | 288 ++++++++++++++- test/messages/Jamfile | 1 + test/messages/async_seal_xchacha/Jamfile | 14 + .../async_seal_xchacha/async_seal_xchacha.cpp | 41 +++ test/msvc/Jamfile | 1 + test/msvc/async_seal_xchacha/Jamfile | 11 + test/msvc/async_seal_xchacha/app.cpp | 33 ++ test/support/timing_coverage.hpp | 93 +++++ test/timing_coverage_bearssl_test.cpp | 9 +- test/timing_coverage_openssl_test.cpp | 9 +- 14 files changed, 1006 insertions(+), 21 deletions(-) create mode 100644 test/async_gcm_test.cpp create mode 100644 test/messages/async_seal_xchacha/Jamfile create mode 100644 test/messages/async_seal_xchacha/async_seal_xchacha.cpp create mode 100644 test/msvc/async_seal_xchacha/Jamfile create mode 100644 test/msvc/async_seal_xchacha/app.cpp diff --git a/include/webcpp/crypto/async.hpp b/include/webcpp/crypto/async.hpp index 86cdeb10..c30d2837 100644 --- a/include/webcpp/crypto/async.hpp +++ b/include/webcpp/crypto/async.hpp @@ -16,9 +16,13 @@ - The cheap functions exist on every target, for the algorithms the browser's WebCrypto has. Each takes the executor its completion is posted to first. On a synchronous backend, their - default, they run the synchronous call at once (its guards and its work, on the caller's - thread) and complete through a post to that executor, whence the completion reaches the - handler's associated executor, never inside the initiating call. + default, they run the synchronous call when the operation is initiated (its guards and its + work, on the thread that initiates it: the caller's for a callback or `use_awaitable`, the one + that launches the operation for `deferred`) and complete through a post to that executor, + whence the completion reaches the handler's associated executor, never inside the initiating + call. + - AES-GCM: `async_make`, `async_seal` and `async_open`, over `ciphers::gcm`. The other AEADs + (ChaCha20-Poly1305 and its forms, the secret boxes) are not in WebCrypto: call their `seal`. - The heavy functions (design D32's list) take the work executor first (a `webcpp::asio::thread_pool`'s): they check their guards on the caller's thread, run the work on the work executor and complete on the handler's associated executor, with webcpp::hash's @@ -37,12 +41,24 @@ @code // exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//gcm-default /webcpp/asio//asio ; - // A coroutine seals in place on the default backend; the completion, the error code and the - // tag, is posted to the coroutine's executor. namespace asio = webcpp::asio; - auto const executor = co_await asio::this_coro::executor; - auto [code, tag] = co_await webcpp::crypto::async_seal(executor, aead, iv, ad, data, - asio::as_tuple(asio::use_awaitable)); + namespace crypto = webcpp::crypto; + using gcm = crypto::ciphers::gcm>; + + // A coroutine makes a key and seals in place on the default backend; each completion, the error + // code and the value, is posted to the coroutine's executor. + asio::awaitable seal_message(std::span key, + std::span iv, + std::span additional_data, + std::span data) { + auto const executor = co_await asio::this_coro::executor; + auto [made_code, aead] = + co_await crypto::async_make(executor, key, asio::as_tuple(asio::use_awaitable)); + if (made_code) { co_return; } + auto [code, tag] = co_await crypto::async_seal(executor, aead, iv, additional_data, data, + asio::as_tuple(asio::use_awaitable)); + // `data` holds the ciphertext and `tag` the tag when `code` is clear. + } @endcode @see "Asynchronous calls", in the guide. @@ -53,11 +69,10 @@ #include #include -#include -#include #include #include #include +#include #include #include @@ -66,6 +81,8 @@ #include #include +#include +#include #include #include @@ -139,8 +156,9 @@ struct post_initiation { }; /** - * Initiates a cheap function on a synchronous backend (design D23): runs `operation()` at once, - * on the caller's thread, and completes through a post to `executor`, never inside the call, + * Initiates a cheap function on a synchronous backend (design D23): runs `operation()` when the + * operation is initiated (on the initiating thread; for `deferred`, when the deferred operation + * is launched), and completes through a post to `executor`, never inside the call, * with `operation()`'s result split into its error code and its value. * * @tparam CompletionToken Any completion token, of signature `completion_of::type`, `R` @@ -161,8 +179,141 @@ auto complete_by_post(Executor const& executor, CompletionToken& token, Operatio post_initiation{}, token, executor, std::move(operation)); } +/** Whether `Type` is an AES-GCM, `ciphers::gcm`. */ +template +inline constexpr bool is_gcm_v = false; + +template +inline constexpr bool is_gcm_v> = true; + +/** False for every type, so that a refusal's `static_assert` fires only when it is reached. */ +template +inline constexpr bool refused_v = false; + } // namespace detail +/** + * Makes an AES-GCM object from a key, asynchronously: `Algorithm::make(key_bytes)` run when the + * operation is initiated, its result posted to `executor` (design D23). The key is read before + * the call returns on a synchronous backend, later on the browser's: it is the caller's until the + * completion. + * + * @tparam Algorithm A `ciphers::gcm`, on any backend of AES-GCM; the other algorithms + * WebCrypto has are made by their own overloads of the key pairs' functions. + * @param executor The executor the completion is posted to. + * @param key_bytes `Algorithm::key_size` bytes. + * @param token The completion token, of signature `void(boost::system::error_code, Algorithm)`; + * on an error the object is empty, and every member refuses with `invalid_state` + * (`invalid_key_size`, `errc::not_enough_memory`, `backend_failure`). + * @return What the completion token's `async_result` gives. + */ +template +auto async_make(Executor const& executor, std::span key_bytes, + CompletionToken&& token) { + detail::timing_guard const timing; + if constexpr (!detail::is_gcm_v) { + static_assert(detail::refused_v, + "webcpp::crypto: async_make takes AES-GCM, the algorithm WebCrypto has: " + "call make for the others."); + } else { + using backend = Algorithm::backend_type; + if constexpr (detail::asynchronous_backend_v) { + return detail::async_engine::template make( + executor, key_bytes, std::forward(token)); + } else { + return detail::complete_by_post( + executor, token, [key_bytes]() noexcept { return Algorithm::make(key_bytes); }); + } + } +} + +/** + * Seals a message in place, asynchronously: `aead.seal(iv_bytes, additional_data_bytes, + * data_bytes)` run when the operation is initiated, its result posted to `executor`. + * + * `aead` and the spans are the caller's until the completion: a synchronous backend reads and + * writes them before the call returns, the browser's later. `data_bytes` holds the ciphertext at + * the completion. A guard's refusal (`invalid_iv_size`, `message_too_long`, `invalid_state`) + * leaves it untouched, a backend's failure zeroes it, as `seal` does. + * + * @tparam Gcm A `ciphers::gcm`; the other AEADs are not in WebCrypto: call their `seal`. + * @param executor The executor the completion is posted to. + * @param aead The keyed object. + * @param iv_bytes 1 to `max_iv_size` bytes, never reused under this key. + * @param additional_data_bytes Authenticated, not encrypted. + * @param data_bytes The message. + * @param token The completion token, of signature `void(boost::system::error_code, + * Gcm::result_type)`: the tag; on an error the zeroed tag. + * @return What the completion token's `async_result` gives. + */ +template +auto async_seal(Executor const& executor, Gcm& aead, std::span iv_bytes, + std::span additional_data_bytes, + std::span data_bytes, CompletionToken&& token) { + detail::timing_guard const timing; + if constexpr (!detail::is_gcm_v) { + static_assert(detail::refused_v, + "webcpp::crypto: async_seal takes AES-GCM, the AEAD WebCrypto has: call seal " + "for the others."); + } else { + using backend = Gcm::backend_type; + if constexpr (detail::asynchronous_backend_v) { + return detail::async_engine::seal(executor, aead, iv_bytes, + additional_data_bytes, data_bytes, + std::forward(token)); + } else { + return detail::complete_by_post( + executor, token, [&aead, iv_bytes, additional_data_bytes, data_bytes]() noexcept { + return aead.seal(iv_bytes, additional_data_bytes, data_bytes); + }); + } + } +} + +/** + * Opens a message in place, asynchronously: `aead.open(iv_bytes, additional_data_bytes, + * data_bytes, tag_bytes)` run when the operation is initiated, its result posted to `executor`. + * + * `aead` and the spans are the caller's until the completion. `data_bytes` holds the plaintext at + * a successful completion; a wrong tag (`authentication_failed`) or a backend's failure zeroes + * it, a guard's refusal leaves it untouched, as `open` does. + * + * @tparam Gcm A `ciphers::gcm`; the other AEADs are not in WebCrypto: call their `open`. + * @param executor The executor the completion is posted to. + * @param aead The keyed object. + * @param iv_bytes The IV of the seal. + * @param additional_data_bytes The additional data of the seal. + * @param data_bytes The ciphertext. + * @param tag_bytes The seal's tag, 16 bytes. + * @param token The completion token, of signature `void(boost::system::error_code)`. + * @return What the completion token's `async_result` gives. + */ +template +auto async_open(Executor const& executor, Gcm& aead, std::span iv_bytes, + std::span additional_data_bytes, + std::span data_bytes, std::span tag_bytes, + CompletionToken&& token) { + detail::timing_guard const timing; + if constexpr (!detail::is_gcm_v) { + static_assert(detail::refused_v, + "webcpp::crypto: async_open takes AES-GCM, the AEAD WebCrypto has: call open " + "for the others."); + } else { + using backend = Gcm::backend_type; + if constexpr (detail::asynchronous_backend_v) { + return detail::async_engine::open(executor, aead, iv_bytes, + additional_data_bytes, data_bytes, tag_bytes, + std::forward(token)); + } else { + return detail::complete_by_post( + executor, token, + [&aead, iv_bytes, additional_data_bytes, data_bytes, tag_bytes]() noexcept { + return aead.open(iv_bytes, additional_data_bytes, data_bytes, tag_bytes); + }); + } + } +} + } // namespace webcpp::crypto #endif // WEBCPP_CRYPTO_ASYNC_HPP diff --git a/include/webcpp/crypto/ciphers/gcm.hpp b/include/webcpp/crypto/ciphers/gcm.hpp index 95e60c5e..f268df67 100644 --- a/include/webcpp/crypto/ciphers/gcm.hpp +++ b/include/webcpp/crypto/ciphers/gcm.hpp @@ -15,6 +15,7 @@ #include #include +#include #include #include #include @@ -569,6 +570,9 @@ class gcm { // The bytes authenticate decrypts at once into its own buffer. static constexpr std::size_t scratch_size = 256; + // The asynchronous family's error completions make the empty object a move leaves. + friend struct detail::async_access; + gcm() noexcept = default; // A call of the incremental machine in `expected`: outside it, `invalid_state`, which ends diff --git a/test/Jamfile b/test/Jamfile index 673ecd9d..8ee52fb8 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -116,6 +116,14 @@ crypto-run heavy : heavy_test.cpp crypto-run async_post : async_post_test.cpp : /webcpp/asio//asio /webcpp/crypto//gcm-default /third_party//sodium ; +# AES-GCM's asynchronous functions, async_make, async_seal and async_open, on +# BearSSL (every target) and on OpenSSL (where it is built): the specification's +# cases, a wrong tag, a long IV, a refused key, a coroutine. +crypto-run async_gcm : async_gcm_test.cpp + : /webcpp/asio//asio /third_party//bearssl ; +crypto-run async_gcm_openssl : async_gcm_test.cpp + : /webcpp/asio//asio /webcpp/crypto//openssl + WEBCPP_TEST_ASYNC_GCM_OPENSSL : native wasip2 wasip3 ; # Without threads (WEBCPP_CRYPTO_NO_THREADS natively; WASI has none), a heavy # operation's async_ variant that forgets its refusal stops at # detail::run_on_work's stand-in, which names the refusal, and with that @@ -145,15 +153,15 @@ crypto-run timing_mock : timing_mock_test.cpp ; # and leaves the thread's DIT as it found it: one program per backend, # wherever the backend is built (support/timing_coverage.hpp). crypto-run timing_coverage_bearssl : timing_coverage_bearssl_test.cpp - : /third_party//bearssl ; + : /third_party//bearssl /webcpp/asio//asio ; crypto-run timing_coverage_openssl : timing_coverage_openssl_test.cpp - : /webcpp/crypto//openssl : native wasip2 wasip3 ; + : /webcpp/crypto//openssl /webcpp/asio//asio : native wasip2 wasip3 ; crypto-run timing_coverage_ctaes : timing_coverage_ctaes_test.cpp - : /third_party//ctaes ; + : /third_party//ctaes /webcpp/asio//asio ; crypto-run timing_coverage_sodium : timing_coverage_sodium_test.cpp - : /third_party//sodium ; + : /third_party//sodium /webcpp/asio//asio ; crypto-run timing_coverage_secp256k1 : timing_coverage_secp256k1_test.cpp - : /third_party//secp256k1 ; + : /third_party//secp256k1 /webcpp/asio//asio ; # The specification's scenarios on libsodium's Ed25519: a thread whose DIT is # clear finds it clear after sign, one that set it finds it still set. crypto-run timing_sodium : timing_sodium_test.cpp : /third_party//sodium ; diff --git a/test/async_gcm_test.cpp b/test/async_gcm_test.cpp new file mode 100644 index 00000000..1eebb260 --- /dev/null +++ b/test/async_gcm_test.cpp @@ -0,0 +1,330 @@ +// 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) + +// AES-GCM's asynchronous functions, async_make, async_seal and async_open, on one backend +// (BearSSL, or OpenSSL where the program defines WEBCPP_TEST_ASYNC_GCM_OPENSSL), on a callback +// and in a coroutine: +// - async_spec_cases: the 18 cases of the specification through async_make, async_seal and +// async_open give the synchronous answers byte for byte (ciphertext, tag, plaintext), the +// completion arriving after the initiating call returned. +// - async_wrong_tag: a wrong tag completes with authentication_failed and zeroed data. +// - async_long_iv: a 129-byte IV completes with invalid_iv_size, the data untouched, for the +// seal (with a zeroed tag) and the open. +// - async_make_refused: a 31-byte key completes with invalid_key_size and an empty gcm, which +// refuses every member with invalid_state (review focus 5). +// - async_coroutine: the example of async.hpp's header, in a coroutine of the context. + +#include +#if defined(WEBCPP_TEST_ASYNC_GCM_OPENSSL) +#include +#else +#include +#endif +#include +#include +#include +#include + +#include "support/gcm_spec_vectors.hpp" +#include "support/hex.hpp" + +#include +#include +#include +#include +#include +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace asio = webcpp::asio; +namespace crypto = webcpp::crypto; + +namespace { + +#if defined(WEBCPP_TEST_ASYNC_GCM_OPENSSL) +using backend = crypto::backends::openssl; +#else +using backend = crypto::backends::bearssl; +#endif + +template +struct cipher_of; + +template <> +struct cipher_of<16> { + using type = crypto::ciphers::aes128; +}; + +template <> +struct cipher_of<24> { + using type = crypto::ciphers::aes192; +}; + +template <> +struct cipher_of<32> { + using type = crypto::ciphers::aes256; +}; + +using gcm256 = crypto::ciphers::gcm::type>; + +bool all_zero(std::span bytes) { + return std::ranges::all_of(bytes, [](std::uint8_t byte) { return byte == 0; }); +} + +bool same_bytes(std::span left, std::span right) { + return std::ranges::equal(left, right); +} + +// What one completion handed over. +template +struct completion { + int calls = 0; + boost::system::error_code code; + std::optional value; +}; + +// Runs a start with a callback taking the code and a Value, checks that the completion did not +// come inside the call and came once after, and returns it. +template +completion complete(asio::io_context& context, Start start) { + completion done; + bool returned = false; + bool inline_call = false; + start(context.get_executor(), + [&done, &returned, &inline_call](boost::system::error_code code, Value value) { + ++done.calls; + inline_call = !returned; + done.code = code; + done.value.emplace(std::move(value)); + }); + returned = true; + BOOST_TEST_EQ(done.calls, 0); + context.restart(); + context.run(); // lint-run: the test's event loop + BOOST_TEST_EQ(done.calls, 1); + BOOST_TEST(!inline_call); + return done; +} + +// The same for an operation without a value. +struct plain_completion { + int calls = 0; + boost::system::error_code code; +}; + +template +plain_completion complete_plain(asio::io_context& context, Start start) { + plain_completion done; + bool returned = false; + bool inline_call = false; + start(context.get_executor(), [&done, &returned, &inline_call](boost::system::error_code code) { + ++done.calls; + inline_call = !returned; + done.code = code; + }); + returned = true; + BOOST_TEST_EQ(done.calls, 0); + context.restart(); + context.run(); // lint-run: the test's event loop + BOOST_TEST_EQ(done.calls, 1); + BOOST_TEST(!inline_call); + return done; +} + +// One case of the specification, through the three functions, for the cipher of its key's size. +template +void run_case(asio::io_context& context, webcpp::test::gcm_case const& spec) { + auto const key = webcpp::test::from_hex(spec.key); + auto const iv = webcpp::test::from_hex(spec.iv); + auto const additional_data = webcpp::test::from_hex(spec.additional_data); + auto const plaintext = webcpp::test::from_hex(spec.plaintext); + auto const ciphertext = webcpp::test::from_hex(spec.ciphertext); + auto const tag = webcpp::test::from_hex(spec.tag); + + auto made = complete(context, [&](auto const& executor, auto&& token) { + crypto::async_make(executor, key, std::forward(token)); + }); + BOOST_TEST(!made.code); + if (!BOOST_TEST(made.value.has_value()) || made.code) { + return; + } + Gcm& aead = *made.value; + + std::vector data = plaintext; + auto sealed = + complete(context, [&](auto const& executor, auto&& token) { + crypto::async_seal(executor, aead, iv, additional_data, data, + std::forward(token)); + }); + BOOST_TEST(!sealed.code); + BOOST_TEST(same_bytes(data, ciphertext)); + if (BOOST_TEST(sealed.value.has_value())) { + BOOST_TEST(same_bytes(std::span(sealed.value->data(), sealed.value->size()), tag)); + } + + auto const opened = complete_plain(context, [&](auto const& executor, auto&& token) { + crypto::async_open(executor, aead, iv, additional_data, data, tag, + std::forward(token)); + }); + BOOST_TEST(!opened.code); + BOOST_TEST(same_bytes(data, plaintext)); +} + +void async_spec_cases(asio::io_context& context) { + for (auto const& spec : webcpp::test::gcm_spec_cases) { + switch (spec.key.size() / 2) { + case 16: run_case::type>>(context, spec); break; + case 24: run_case::type>>(context, spec); break; + default: run_case(context, spec); break; + } + } +} + +// A keyed gcm of the all-zero key, through async_make. +gcm256 keyed(asio::io_context& context) { + std::array const key{}; + auto made = complete(context, [&](auto const& executor, auto&& token) { + crypto::async_make(executor, key, std::forward(token)); + }); + BOOST_TEST(!made.code); + BOOST_TEST(made.value.has_value()); + return std::move(*made.value); +} + +void async_wrong_tag(asio::io_context& context) { + gcm256 aead = keyed(context); + std::array const iv{}; + std::array const additional_data{1, 2, 3, 4}; + std::array data{}; + data.fill(0x5a); + auto sealed = complete(context, [&](auto const& executor, auto&& token) { + crypto::async_seal(executor, aead, iv, additional_data, data, + std::forward(token)); + }); + BOOST_TEST(!sealed.code); + if (!BOOST_TEST(sealed.value.has_value())) { + return; + } + std::array tag{}; + std::ranges::copy(*sealed.value, tag.begin()); + tag[7] ^= 1U; + auto const opened = complete_plain(context, [&](auto const& executor, auto&& token) { + crypto::async_open(executor, aead, iv, additional_data, data, tag, + std::forward(token)); + }); + BOOST_TEST(opened.code == crypto::error::authentication_failed); + BOOST_TEST(all_zero(data)); +} + +void async_long_iv(asio::io_context& context) { + gcm256 aead = keyed(context); + std::array const iv{}; + std::array data{}; + data.fill(0x6c); + auto const untouched = data; + std::array const tag{}; + auto sealed = complete(context, [&](auto const& executor, auto&& token) { + crypto::async_seal(executor, aead, iv, {}, data, std::forward(token)); + }); + BOOST_TEST(sealed.code == crypto::error::invalid_iv_size); + BOOST_TEST(same_bytes(data, untouched)); + if (BOOST_TEST(sealed.value.has_value())) { + BOOST_TEST(all_zero(std::span(sealed.value->data(), sealed.value->size()))); + } + auto const opened = complete_plain(context, [&](auto const& executor, auto&& token) { + crypto::async_open(executor, aead, iv, {}, data, tag, std::forward(token)); + }); + BOOST_TEST(opened.code == crypto::error::invalid_iv_size); + BOOST_TEST(same_bytes(data, untouched)); +} + +void async_make_refused(asio::io_context& context) { + std::array const key{}; + auto made = complete(context, [&](auto const& executor, auto&& token) { + crypto::async_make(executor, key, std::forward(token)); + }); + BOOST_TEST(made.code == crypto::error::invalid_key_size); + if (!BOOST_TEST(made.value.has_value())) { + return; + } + // The empty gcm refuses every member, and leaves data untouched. + gcm256& empty = *made.value; + std::array const iv{}; + std::array data{}; + data.fill(0x6c); + auto const untouched = data; + std::array const tag{}; + BOOST_TEST(empty.seal(iv, {}, data).error() == crypto::error::invalid_state); + BOOST_TEST(empty.open(iv, {}, data, tag).error() == crypto::error::invalid_state); + BOOST_TEST(empty.begin_seal(iv, {}).error() == crypto::error::invalid_state); + BOOST_TEST(empty.begin_open(iv, {}).error() == crypto::error::invalid_state); + BOOST_TEST(empty.update(data).error() == crypto::error::invalid_state); + BOOST_TEST(empty.result().error() == crypto::error::invalid_state); + BOOST_TEST(same_bytes(data, untouched)); + // Through the asynchronous functions too. + auto sealed = complete(context, [&](auto const& executor, auto&& token) { + crypto::async_seal(executor, empty, iv, {}, data, std::forward(token)); + }); + BOOST_TEST(sealed.code == crypto::error::invalid_state); + BOOST_TEST(same_bytes(data, untouched)); +} + +// The example of async.hpp's header, in a coroutine of the context: make, seal, open. +void async_coroutine(asio::io_context& context) { + bool done = false; + asio::co_spawn( + context, + [&]() -> asio::awaitable { + auto const executor = co_await asio::this_coro::executor; + std::array const key{}; + std::array const iv{}; + std::array const additional_data{9, 8, 7, 6}; + std::array data{}; + data.fill(0x33); + auto const plaintext = data; + auto [made_code, aead] = co_await crypto::async_make( + executor, key, asio::as_tuple(asio::use_awaitable)); + BOOST_TEST(!made_code); + auto [code, tag] = co_await crypto::async_seal( + executor, aead, iv, additional_data, data, asio::as_tuple(asio::use_awaitable)); + BOOST_TEST(!code); + BOOST_TEST(!same_bytes(data, plaintext)); + auto [open_code] = co_await crypto::async_open(executor, aead, iv, additional_data, + data, std::span(tag.data(), tag.size()), + asio::as_tuple(asio::use_awaitable)); + BOOST_TEST(!open_code); + BOOST_TEST(same_bytes(data, plaintext)); + done = true; + }, + [](std::exception_ptr const& failure) { BOOST_TEST(!failure); }); + context.restart(); + context.run(); // lint-run: the test's event loop + BOOST_TEST(done); +} + +} // namespace + +int main() { + asio::io_context context; + async_spec_cases(context); + async_wrong_tag(context); + async_long_iv(context); + async_make_refused(context); + async_coroutine(context); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/async_post_test.cpp b/test/async_post_test.cpp index 5c4141e4..dab33b14 100644 --- a/test/async_post_test.cpp +++ b/test/async_post_test.cpp @@ -24,10 +24,14 @@ // plain use_awaitable throws). // - post_error_value: an error completes with its code and the empty value (ruling R-A3): a // secret<32> and an array of zeros. -// Tasks 4.A3 and 4.A4 add async_seal's and async_verify's cases to each check: each check takes -// the operation's start as a callable of (executor, token). +// - post_gcm: the same cases through AES-GCM's async_make, async_seal and async_open (the +// functions the family really has, Task 4.A3): never inside the call, the work done when the +// call returns, a bound executor, the handler's allocator, every token, an error's empty +// value. Task 4.A4 adds async_verify's. +// Each check takes the operation's start as a callable of (executor, token). #include +#include #include #include #include @@ -60,6 +64,7 @@ #include #include #include +#include #include #include #include @@ -326,6 +331,27 @@ void check_allocator(asio::io_context& context, Start made, Start refused) { BOOST_TEST_EQ(failed.news, 0U); } +// check_allocator for a start whose refusal is `expected`, the value type spelled. +template +void check_allocator_with(asio::io_context& context, Made made, Refused refused, + boost::system::error_code expected) { + allocator_call done; + start_counted(context, made, done); + BOOST_TEST_EQ(done.calls, 1); + BOOST_TEST(!done.code); + BOOST_TEST_EQ(done.held_at_call, 0); + BOOST_TEST_GE(done.taken, 1); + BOOST_TEST_EQ(done.news, 0U); + + allocator_call failed; + start_counted(context, refused, failed); + BOOST_TEST_EQ(failed.calls, 1); + BOOST_TEST(failed.code == expected); + BOOST_TEST_EQ(failed.held_at_call, 0); + BOOST_TEST_GE(failed.taken, 1); + BOOST_TEST_EQ(failed.news, 0U); +} + void post_allocator(asio::io_context& context) { // One uncounted call first, so that what the runtime makes once is outside the windows. allocator_call warm; @@ -444,6 +470,260 @@ void post_error_value(asio::io_context& context) { BOOST_TEST(refused_check.code == crypto::error::invalid_input_size); } +// AES-GCM through the family's real functions, on the default backend. The fixture: a key, an IV, +// four bytes of additional data and forty of data, which a seal changes. +struct gcm_fixture { + using gcm = crypto::ciphers::aes256_gcm; + std::array key{}; + std::array iv{}; + std::array additional_data{1, 2, 3, 4}; + std::array data{}; + std::array long_iv{}; + std::array tag{}; + gcm aead; + + gcm_fixture() : aead(*gcm::make(key)) { data.fill(0x5a); } + + auto seal() { + return [this](auto const& executor, auto&& token) { + return crypto::async_seal(executor, aead, iv, additional_data, data, + std::forward(token)); + }; + } + + auto seal_refused() { + return [this](auto const& executor, auto&& token) { + return crypto::async_seal(executor, aead, long_iv, additional_data, data, + std::forward(token)); + }; + } + + auto open() { + return [this](auto const& executor, auto&& token) { + return crypto::async_open(executor, aead, iv, additional_data, data, tag, + std::forward(token)); + }; + } + + auto open_refused() { + return [this](auto const& executor, auto&& token) { + return crypto::async_open(executor, aead, long_iv, additional_data, data, tag, + std::forward(token)); + }; + } + + auto make() { + return [this](auto const& executor, auto&& token) { + return crypto::async_make(executor, key, std::forward(token)); + }; + } + + auto make_refused() { + return [this](auto const& executor, auto&& token) { + return crypto::async_make(executor, std::span(key).first(31), + std::forward(token)); + }; + } +}; + +using gcm_tag = gcm_fixture::gcm::result_type; + +void post_gcm_inline(asio::io_context& context) { + gcm_fixture fixture; + auto const plaintext = fixture.data; + // The seal ran when the call returned (the data is the ciphertext), the completion after. + seen sealed; + bool returned = false; + fixture.seal()(context.get_executor(), [&](boost::system::error_code code, gcm_tag tag) { + ++sealed.calls; + sealed.after_return = returned; + sealed.code = code; + sealed.value = std::tuple(tag); + }); + returned = true; + BOOST_TEST_EQ(sealed.calls, 0); + BOOST_TEST(fixture.data != plaintext); + context.restart(); + context.run(); // lint-run: the test's event loop + BOOST_TEST_EQ(sealed.calls, 1); + BOOST_TEST(sealed.after_return); + BOOST_TEST(!sealed.code); + std::ranges::copy(std::get<0>(sealed.value), fixture.tag.begin()); + + // The open, no value: the plaintext is back when the call returns. + seen<> opened; + returned = false; + fixture.open()(context.get_executor(), [&](boost::system::error_code code) { + ++opened.calls; + opened.after_return = returned; + opened.code = code; + }); + returned = true; + BOOST_TEST_EQ(opened.calls, 0); + BOOST_TEST(fixture.data == plaintext); + context.restart(); + context.run(); // lint-run: the test's event loop + BOOST_TEST_EQ(opened.calls, 1); + BOOST_TEST(opened.after_return); + BOOST_TEST(!opened.code); + + // A refusal is posted too, with the zeroed tag, and leaves the data untouched. + seen refused; + fixture.seal_refused()(context.get_executor(), + [&](boost::system::error_code code, gcm_tag tag) { + ++refused.calls; + refused.code = code; + refused.value = std::tuple(tag); + }); + BOOST_TEST_EQ(refused.calls, 0); + context.restart(); + context.run(); // lint-run: the test's event loop + BOOST_TEST_EQ(refused.calls, 1); + BOOST_TEST(refused.code == crypto::error::invalid_iv_size); + BOOST_TEST(all_bytes(std::get<0>(refused.value), 0)); + BOOST_TEST(fixture.data == plaintext); +} + +void post_gcm_bound_executor() { + gcm_fixture fixture; + // The open needs a sealed message. + auto const sealed = fixture.aead.seal(fixture.iv, fixture.additional_data, fixture.data); + if (BOOST_TEST(sealed.has_value())) { + std::ranges::copy(*sealed, fixture.tag.begin()); + } + complete_on_bound<>(fixture.open()); + complete_on_bound(fixture.seal()); + complete_on_bound(fixture.make()); +} + +void post_gcm_allocator(asio::io_context& context) { + gcm_fixture fixture; + allocator_call warm; + start_counted(context, fixture.seal(), warm); + BOOST_TEST_EQ(warm.calls, 1); + // A seal changes the data and tag; the open of the next call needs its tag. + allocator_call sealed; + start_counted(context, fixture.seal(), sealed); + BOOST_TEST(!sealed.code); + BOOST_TEST_EQ(sealed.held_at_call, 0); + BOOST_TEST_GE(sealed.taken, 1); + BOOST_TEST_EQ(sealed.news, 0U); + allocator_call refused; + start_counted(context, fixture.seal_refused(), refused); + BOOST_TEST(refused.code == crypto::error::invalid_iv_size); + BOOST_TEST_EQ(refused.held_at_call, 0); + BOOST_TEST_GE(refused.taken, 1); + BOOST_TEST_EQ(refused.news, 0U); + // An open (no value) with a refusal, then a make (an object) and its refusal. + allocator_call open_refused; + start_counted<>(context, fixture.open_refused(), open_refused); + BOOST_TEST(open_refused.code == crypto::error::invalid_iv_size); + BOOST_TEST_EQ(open_refused.held_at_call, 0); + BOOST_TEST_GE(open_refused.taken, 1); + BOOST_TEST_EQ(open_refused.news, 0U); + check_allocator_with(context, fixture.make(), fixture.make_refused(), + crypto::error::invalid_key_size); +} + +void post_gcm_tokens(asio::io_context& context) { + gcm_fixture fixture; + auto const plaintext = fixture.data; + auto const executor = context.get_executor(); + +#ifndef WEBCPP_CRYPTO_NO_EXCEPTIONS + auto future_tag = crypto::async_seal(executor, fixture.aead, fixture.iv, + fixture.additional_data, fixture.data, asio::use_future); + context.restart(); + context.run(); // lint-run: the test's event loop + std::ranges::copy(future_tag.get(), fixture.tag.begin()); + BOOST_TEST(fixture.data != plaintext); + auto future_open = + crypto::async_open(executor, fixture.aead, fixture.iv, fixture.additional_data, + fixture.data, fixture.tag, asio::use_future); + context.restart(); + context.run(); // lint-run: the test's event loop + future_open.get(); + BOOST_TEST(fixture.data == plaintext); + auto future_made = + crypto::async_make(executor, fixture.key, asio::use_future); + auto future_refused = crypto::async_make( + executor, std::span(fixture.key).first(31), asio::use_future); + context.restart(); + context.run(); // lint-run: the test's event loop + static_cast(future_made.get()); + bool thrown = false; + try { + static_cast(future_refused.get()); + } catch (boost::system::system_error const& failure) { + thrown = failure.code() == crypto::error::invalid_key_size; + } + BOOST_TEST(thrown); +#endif + + // deferred: the synchronous call runs when the operation is launched, not when it is made. + auto operation = crypto::async_seal(executor, fixture.aead, fixture.iv, fixture.additional_data, + fixture.data, asio::deferred); + BOOST_TEST(fixture.data == plaintext); + int deferred_calls = 0; + std::move(operation)([&](boost::system::error_code code, gcm_tag tag) { + ++deferred_calls; + BOOST_TEST(!code); + std::ranges::copy(tag, fixture.tag.begin()); + }); + BOOST_TEST(fixture.data != plaintext); + BOOST_TEST_EQ(deferred_calls, 0); + context.restart(); + context.run(); // lint-run: the test's event loop + BOOST_TEST_EQ(deferred_calls, 1); + + // as_tuple: the code and the value in one argument; the open, the code alone. + int tuples = 0; + crypto::async_open(executor, fixture.aead, fixture.iv, fixture.additional_data, fixture.data, + fixture.tag, asio::as_tuple([&](std::tuple done) { + ++tuples; + BOOST_TEST(!std::get<0>(done)); + })); + crypto::async_seal(executor, fixture.aead, fixture.long_iv, fixture.additional_data, + fixture.data, + asio::as_tuple([&](std::tuple done) { + ++tuples; + BOOST_TEST(std::get<0>(done) == crypto::error::invalid_iv_size); + BOOST_TEST(all_bytes(std::get<1>(done), 0)); + })); + context.restart(); + context.run(); // lint-run: the test's event loop + BOOST_TEST_EQ(tuples, 2); + BOOST_TEST(fixture.data == plaintext); + + // use_awaitable in a coroutine of the context: a refusal through as_tuple. + bool done = false; + asio::co_spawn( + context, + [&]() -> asio::awaitable { + auto const coro = co_await asio::this_coro::executor; + auto [made_code, made] = co_await crypto::async_make( + coro, std::span(fixture.key).first(31), asio::as_tuple(asio::use_awaitable)); + BOOST_TEST(made_code == crypto::error::invalid_key_size); + BOOST_TEST(made.seal(fixture.iv, {}, fixture.data).error() == + crypto::error::invalid_state); + auto [seal_code, tag] = + co_await crypto::async_seal(coro, fixture.aead, fixture.iv, fixture.additional_data, + fixture.data, asio::as_tuple(asio::use_awaitable)); + BOOST_TEST(!seal_code); + BOOST_TEST(fixture.data != plaintext); + auto [open_code] = co_await crypto::async_open( + coro, fixture.aead, fixture.iv, fixture.additional_data, fixture.data, + std::span(tag.data(), tag.size()), asio::as_tuple(asio::use_awaitable)); + BOOST_TEST(!open_code); + BOOST_TEST(fixture.data == plaintext); + done = true; + }, + [](std::exception_ptr const& failure) { BOOST_TEST(!failure); }); + context.restart(); + context.run(); // lint-run: the test's event loop + BOOST_TEST(done); +} + // The asynchronous default is the synchronous one, on every target (ruling R-A4), and no // synchronous backend completes by itself: part B's backends::browser alone will. template @@ -464,5 +744,9 @@ int main() { post_allocator(context); post_tokens(context); post_error_value(context); + post_gcm_inline(context); + post_gcm_bound_executor(); + post_gcm_allocator(context); + post_gcm_tokens(context); return webcpp::test::exit_status(boost::report_errors()); } diff --git a/test/messages/Jamfile b/test/messages/Jamfile index dba28bb0..79b3846c 100644 --- a/test/messages/Jamfile +++ b/test/messages/Jamfile @@ -29,6 +29,7 @@ build-project ed25519_on_bearssl ; build-project ed25519ph_sha256 ; build-project ed25519_default_not_linked ; build-project heavy_without_threads ; +build-project async_seal_xchacha ; build-project heavy_without_threads_first ; build-project chacha_default_not_linked ; build-project aead_not_a_family ; diff --git a/test/messages/async_seal_xchacha/Jamfile b/test/messages/async_seal_xchacha/Jamfile new file mode 100644 index 00000000..b9dcb038 --- /dev/null +++ b/test/messages/async_seal_xchacha/Jamfile @@ -0,0 +1,14 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/crypto//crypto ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +webcpp.compile-diagnostic async_seal_xchacha : async_seal_xchacha.cpp + : /webcpp/asio//asio /third_party//sodium : native wasip2 wasip3 : alone ; diff --git a/test/messages/async_seal_xchacha/async_seal_xchacha.cpp b/test/messages/async_seal_xchacha/async_seal_xchacha.cpp new file mode 100644 index 00000000..d8f6667a --- /dev/null +++ b/test/messages/async_seal_xchacha/async_seal_xchacha.cpp @@ -0,0 +1,41 @@ +// 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) + +// async_seal on an AEAD WebCrypto lacks, XChaCha20-Poly1305, stops with the synchronous call to +// make instead, and with that error alone, while the AEAD's own seal compiles. + +// clang-format off +// expected-error@webcpp/crypto/async.hpp:* {{webcpp::crypto: async_seal takes AES-GCM, the AEAD WebCrypto has: call seal for the others.}} +// clang-format on +#include +#include + +#include + +#include +#include + +#include +#include + +int main() { + namespace crypto = webcpp::crypto; + std::array const key{}; + auto made = crypto::ciphers::xchacha20_poly1305<>::make(key); + if (!made) { + return 1; + } + std::array const iv{}; + std::array data{}; + // The synchronous seal compiles. + if (!made->seal(iv, {}, data)) { + return 1; + } + webcpp::asio::io_context context; + crypto::async_seal(context.get_executor(), *made, iv, {}, data, + [](boost::system::error_code, boost::hash2::digest<16>) {}); + return 0; +} diff --git a/test/msvc/Jamfile b/test/msvc/Jamfile index 90f0675c..20778e17 100644 --- a/test/msvc/Jamfile +++ b/test/msvc/Jamfile @@ -48,6 +48,7 @@ build-project ed25519_on_bearssl ; build-project ed25519ph_sha256 ; build-project ed25519_default_not_linked ; build-project heavy_without_threads ; +build-project async_seal_xchacha ; build-project chacha_default_not_linked ; build-project aead_not_a_family ; build-project chacha_on_ctaes ; diff --git a/test/msvc/async_seal_xchacha/Jamfile b/test/msvc/async_seal_xchacha/Jamfile new file mode 100644 index 00000000..c30e7bbc --- /dev/null +++ b/test/msvc/async_seal_xchacha/Jamfile @@ -0,0 +1,11 @@ +# 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) + +import webcpp ; + +webcpp.compile-fail async_seal_xchacha : app.cpp + : /webcpp/crypto//crypto /webcpp/asio//asio /third_party//sodium + : native ; diff --git a/test/msvc/async_seal_xchacha/app.cpp b/test/msvc/async_seal_xchacha/app.cpp new file mode 100644 index 00000000..20e2c09f --- /dev/null +++ b/test/msvc/async_seal_xchacha/app.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) + +// async_seal on an AEAD WebCrypto lacks, XChaCha20-Poly1305, stops where it is called: on MSVC the +// compile fails. The text is checked on clang, in test/messages/async_seal_xchacha. +#include +#include + +#include + +#include +#include + +#include +#include + +int main() { + namespace crypto = webcpp::crypto; + std::array const key{}; + auto made = crypto::ciphers::xchacha20_poly1305<>::make(key); + if (!made) { + return 1; + } + std::array const iv{}; + std::array data{}; + webcpp::asio::io_context context; + crypto::async_seal(context.get_executor(), *made, iv, {}, data, + [](boost::system::error_code, boost::hash2::digest<16>) {}); + return 0; +} diff --git a/test/support/timing_coverage.hpp b/test/support/timing_coverage.hpp index 253ce8d9..347f7ade 100644 --- a/test/support/timing_coverage.hpp +++ b/test/support/timing_coverage.hpp @@ -15,19 +15,24 @@ #include "timing_seam.hpp" +#include #include #include #include #include #include +#include + #include +#include #include #include #include #include #include +#include #include namespace webcpp::test { @@ -317,6 +322,94 @@ void cover_gcm(std::string const& family, std::string const& backend) { cover_gcm_moves(family, on); } +/** + * A completion handler of `cover_async_gcm` that counts its completions and, given a tag's + * address, keeps the tag. Not a lambda: a lambda in a template argument keeps + * `names_function` from reading the guard's function (support/timing_seam.hpp). + */ +template +struct async_gcm_completion { + /** Counts the completion. */ + int* completions; + /** Where a seal's tag is kept, or null. */ + Tag* tag = nullptr; + + /** A completion with an error code alone. */ + void operator()(boost::system::error_code /*code*/) const { ++*completions; } + + /** A completion with a value, which is the tag of a seal or an object that is dropped. */ + template + void operator()(boost::system::error_code /*code*/, Value&& value) const { + ++*completions; + if constexpr (std::is_same_v, Tag>) { + if (tag != nullptr) { + *tag = value; + } + } + } +}; + +/** + * gcm's asynchronous functions, `async_make`, `async_seal` and `async_open`, each called with + * valid input and with input refused before the backend, an `io_context` run after each call so + * that its completion is delivered. The first guard each enters is its own (the synchronous call + * it makes holds another, which runs second). + * + * @tparam Gcm `gcm>`, `gcm>` or `gcm>`. + * @param family The algorithm's name, `aes128_gcm` or `aes256_gcm`. + * @param backend The backend's name. + */ +template +void cover_async_gcm(std::string const& family, std::string const& backend) { + namespace crypto = webcpp::crypto; + std::string const on = " on " + backend; + webcpp::asio::io_context context; + auto const executor = context.get_executor(); + auto const key = coverage_key(); + int completions = 0; + typename Gcm::result_type kept{}; + async_gcm_completion const counted{&completions}; + async_gcm_completion const keeping{&completions, &kept}; + // Each call's completion is delivered before the next call. + auto const deliver = [&context] { + context.restart(); + context.run(); // lint-run: the test's event loop + }; + covered(family + "::async_make" + on, "crypto::async_make", [&] { + crypto::async_make(executor, key, counted); + deliver(); + }); + covered(family + "::async_make with a short key" + on, "crypto::async_make", [&] { + crypto::async_make(executor, std::span(key).first(Gcm::key_size - 1), counted); + deliver(); + }); + auto made = Gcm::make(key); + if (!BOOST_TEST(made.has_value())) { + return; + } + gcm_coverage_message message; + covered(family + "::async_seal" + on, "crypto::async_seal", [&] { + crypto::async_seal(executor, *made, message.iv, message.additional_data, message.data, + keeping); + deliver(); + }); + covered(family + "::async_open" + on, "crypto::async_open", [&] { + crypto::async_open(executor, *made, message.iv, message.additional_data, message.data, + std::span(kept.data(), kept.size()), counted); + deliver(); + }); + covered(family + "::async_seal with an empty IV" + on, "crypto::async_seal", [&] { + crypto::async_seal(executor, *made, {}, message.additional_data, message.data, counted); + deliver(); + }); + covered(family + "::async_open with an empty IV" + on, "crypto::async_open", [&] { + crypto::async_open(executor, *made, {}, message.additional_data, message.data, + std::span(kept.data(), kept.size()), counted); + deliver(); + }); + BOOST_TEST_EQ(completions, 6); +} + /** * ciphers::aead's guarded functions: `make`, a key of the wrong size included, `seal` and * `open`, a nonce of the wrong size included. diff --git a/test/timing_coverage_bearssl_test.cpp b/test/timing_coverage_bearssl_test.cpp index 5fdfef73..7619f189 100644 --- a/test/timing_coverage_bearssl_test.cpp +++ b/test/timing_coverage_bearssl_test.cpp @@ -13,7 +13,8 @@ // // What it covers, by family; a family BearSSL gains adds its line and its checks: // - AES-GCM, gcm, gcm and gcm: make, the move constructor and move -// assignment (ruling R3), seal, open, begin_seal, update, result. +// assignment (ruling R3), seal, open, begin_seal, update, result, and the asynchronous +// async_make, async_seal and async_open. // - ChaCha20-Poly1305, aead: make, seal, open. #include "support/timing_seam.hpp" @@ -37,10 +38,16 @@ using crypto::backends::bearssl; void cover_ciphers() { webcpp::test::cover_gcm>>("aes128_gcm", "bearssl"); + webcpp::test::cover_async_gcm>>( + "aes128_gcm", "bearssl"); webcpp::test::cover_gcm>>("aes192_gcm", "bearssl"); + webcpp::test::cover_async_gcm>>( + "aes192_gcm", "bearssl"); webcpp::test::cover_gcm>>("aes256_gcm", "bearssl"); + webcpp::test::cover_async_gcm>>( + "aes256_gcm", "bearssl"); webcpp::test::cover_aead>("chacha20_poly1305", "bearssl"); } diff --git a/test/timing_coverage_openssl_test.cpp b/test/timing_coverage_openssl_test.cpp index 7210ff83..b2afbe0e 100644 --- a/test/timing_coverage_openssl_test.cpp +++ b/test/timing_coverage_openssl_test.cpp @@ -14,7 +14,8 @@ // What it covers, by family; a family OpenSSL gains adds its line and its checks: // - The AES block cipher, aes128, aes192 and aes256: make; basic_aes: encrypt, decrypt. // - AES-GCM, gcm, gcm and gcm: make, the move constructor and move -// assignment (ruling R3), seal, open, begin_seal, update, result. +// assignment (ruling R3), seal, open, begin_seal, update, result, and the asynchronous +// async_make, async_seal and async_open. // - ChaCha20-Poly1305, aead: make, seal, open. #include "support/timing_seam.hpp" @@ -41,10 +42,16 @@ void cover_ciphers() { webcpp::test::cover_aes>("aes256", "openssl"); webcpp::test::cover_gcm>>("aes128_gcm", "openssl"); + webcpp::test::cover_async_gcm>>( + "aes128_gcm", "openssl"); webcpp::test::cover_gcm>>("aes192_gcm", "openssl"); + webcpp::test::cover_async_gcm>>( + "aes192_gcm", "openssl"); webcpp::test::cover_gcm>>("aes256_gcm", "openssl"); + webcpp::test::cover_async_gcm>>( + "aes256_gcm", "openssl"); webcpp::test::cover_aead>("chacha20_poly1305", "openssl"); } From 4828b3db65d301af48f82ac15b62485f1bfbcf79 Mon Sep 17 00:00:00 2001 From: R Date: Sat, 21 Nov 2026 22:20:46 -0300 Subject: [PATCH 05/14] crypto: Ed25519's and X25519's asynchronous functions, posted on every target Also the review's minors of the AES-GCM commit: the Jamfile's wording of when a call runs, the async_make documentation now true for key pairs, and the async_engine seam's documented shape. --- include/webcpp/crypto/async.hpp | 190 ++++++++- include/webcpp/crypto/curves/ed25519.hpp | 3 + test/Jamfile | 12 +- test/async_25519_test.cpp | 375 ++++++++++++++++++ test/async_post_test.cpp | 217 +++++++++- test/messages/Jamfile | 1 + test/messages/async_sign_secp256k1/Jamfile | 15 + .../async_sign_secp256k1.cpp | 40 ++ test/msvc/Jamfile | 1 + test/msvc/async_sign_secp256k1/Jamfile | 12 + test/msvc/async_sign_secp256k1/app.cpp | 32 ++ test/support/timing_coverage.hpp | 111 ++++++ test/timing_coverage_sodium_test.cpp | 7 +- 13 files changed, 995 insertions(+), 21 deletions(-) create mode 100644 test/async_25519_test.cpp create mode 100644 test/messages/async_sign_secp256k1/Jamfile create mode 100644 test/messages/async_sign_secp256k1/async_sign_secp256k1.cpp create mode 100644 test/msvc/async_sign_secp256k1/Jamfile create mode 100644 test/msvc/async_sign_secp256k1/app.cpp diff --git a/include/webcpp/crypto/async.hpp b/include/webcpp/crypto/async.hpp index c30d2837..ea0ae8e1 100644 --- a/include/webcpp/crypto/async.hpp +++ b/include/webcpp/crypto/async.hpp @@ -23,6 +23,10 @@ call. - AES-GCM: `async_make`, `async_seal` and `async_open`, over `ciphers::gcm`. The other AEADs (ChaCha20-Poly1305 and its forms, the secret boxes) are not in WebCrypto: call their `seal`. + - Ed25519: `async_make` (a key pair from its seed), `async_generate`, `async_sign` and + `async_verify`, over `curves::ed25519::basic_keypair` and `curves::ed25519::verify`. A key + pair of an algorithm WebCrypto lacks (secp256k1) is not here: call its own `sign`. + - X25519: `async_agree`, over `curves::x25519::agree`. - The heavy functions (design D32's list) take the work executor first (a `webcpp::asio::thread_pool`'s): they check their guards on the caller's thread, run the work on the work executor and complete on the handler's associated executor, with webcpp::hash's @@ -69,10 +73,13 @@ #include #include +#include +#include #include #include #include #include +#include #include #include @@ -111,8 +118,23 @@ inline constexpr bool asynchronous_backend_v = false; /** * The operations of a backend that completes by itself: part B specialises it for - * `backends::browser`, with a static member function per asynchronous function, taking its - * arguments and returning its result. Declared only: no synchronous backend reaches it. + * `backends::browser`. Declared only: no synchronous backend reaches it. + * + * Each asynchronous function whose backend satisfies @ref asynchronous_backend_v calls one static + * member function of the specialisation and returns its result, the completion token's + * `async_result`. The shape is the same for every one: the executor the completion is posted to + * first, the function's other arguments as the public function takes them, the completion token + * last, forwarded (`std::forward(token)`); the function's explicit template + * arguments, other than the backend, go to a member template of the same name: + * - `make(executor, key_bytes, token)`: AES-GCM or a key pair from its bytes; + * - `generate(executor, token)`; + * - `seal(executor, aead, iv_bytes, additional_data_bytes, data_bytes, token)` and + * `open(executor, aead, iv_bytes, additional_data_bytes, data_bytes, tag_bytes, token)`; + * - `sign(executor, key_pair, message, token)`; + * - `verify(executor, public_key, message, signature, token)`; + * - `agree(executor, secret_key, peer_public_key, token)`. + * The signatures of the completions are the public functions'. The function's guard + * (`detail::timing_guard`) is held by the public function before it calls the engine. * * @tparam Backend `backends::browser`. */ @@ -121,9 +143,9 @@ struct async_engine; /** * The initiation of a cheap function on a synchronous backend: runs the synchronous call (its - * guards first) at once and posts the completion, its result split by @ref completion_of, to - * `executor`, whence it reaches the handler's associated executor; the post's storage is the - * handler's associated allocator's. + * guards first) when the operation is initiated and posts the completion, its result split by @ref + * completion_of, to `executor`, whence it reaches the handler's associated executor; the post's + * storage is the handler's associated allocator's. */ struct post_initiation { /** @@ -186,6 +208,13 @@ inline constexpr bool is_gcm_v = false; template inline constexpr bool is_gcm_v> = true; +/** Whether `Type` is an Ed25519 key pair, `curves::ed25519::basic_keypair`. */ +template +inline constexpr bool is_ed25519_keypair_v = false; + +template +inline constexpr bool is_ed25519_keypair_v> = true; + /** False for every type, so that a refusal's `static_assert` fires only when it is reached. */ template inline constexpr bool refused_v = false; @@ -193,15 +222,16 @@ inline constexpr bool refused_v = false; } // namespace detail /** - * Makes an AES-GCM object from a key, asynchronously: `Algorithm::make(key_bytes)` run when the - * operation is initiated, its result posted to `executor` (design D23). The key is read before - * the call returns on a synchronous backend, later on the browser's: it is the caller's until the - * completion. + * Makes an AES-GCM object or an Ed25519 key pair from its key bytes, asynchronously: + * `Algorithm::make(key_bytes)` run when the operation is initiated, its result posted to + * `executor` (design D23). The key is read before the call returns on a synchronous backend, + * later on the browser's: it is the caller's until the completion. * - * @tparam Algorithm A `ciphers::gcm`, on any backend of AES-GCM; the other algorithms - * WebCrypto has are made by their own overloads of the key pairs' functions. + * @tparam Algorithm A `ciphers::gcm` or a `curves::ed25519::basic_keypair`, on + * any backend that has it; the other algorithms crypto has are not in WebCrypto: call their + * `make`. * @param executor The executor the completion is posted to. - * @param key_bytes `Algorithm::key_size` bytes. + * @param key_bytes `Algorithm::key_size` bytes for AES-GCM, the seed's `seed_size` for a key pair. * @param token The completion token, of signature `void(boost::system::error_code, Algorithm)`; * on an error the object is empty, and every member refuses with `invalid_state` * (`invalid_key_size`, `errc::not_enough_memory`, `backend_failure`). @@ -211,10 +241,10 @@ template auto async_make(Executor const& executor, std::span key_bytes, CompletionToken&& token) { detail::timing_guard const timing; - if constexpr (!detail::is_gcm_v) { + if constexpr (!detail::is_gcm_v && !detail::is_ed25519_keypair_v) { static_assert(detail::refused_v, - "webcpp::crypto: async_make takes AES-GCM, the algorithm WebCrypto has: " - "call make for the others."); + "webcpp::crypto: async_make takes AES-GCM or a key pair of an algorithm " + "WebCrypto has (Ed25519, P-256): call make for the others."); } else { using backend = Algorithm::backend_type; if constexpr (detail::asynchronous_backend_v) { @@ -227,6 +257,38 @@ auto async_make(Executor const& executor, std::span key_byte } } +/** + * Makes an Ed25519 key pair from a fresh seed, asynchronously: `Keypair::generate()` run when + * the operation is initiated (the system's generator is drawn from then), its result posted to + * `executor`. + * + * @tparam Keypair A `curves::ed25519::basic_keypair`, by default the family's + * `curves::ed25519::keypair`; the other key pairs are not in WebCrypto: call their `generate`. + * @param executor The executor the completion is posted to. + * @param token The completion token, of signature `void(boost::system::error_code, Keypair)`; + * on an error the key pair is empty, and every member refuses with `invalid_state` + * (`entropy_unavailable`, `backend_failure`). + * @return What the completion token's `async_result` gives. + */ +template +auto async_generate(Executor const& executor, CompletionToken&& token) { + detail::timing_guard const timing; + if constexpr (!detail::is_ed25519_keypair_v) { + static_assert(detail::refused_v, + "webcpp::crypto: async_generate takes a key pair of an algorithm WebCrypto " + "has (Ed25519, P-256): call generate for the others."); + } else { + using backend = Keypair::backend_type; + if constexpr (detail::asynchronous_backend_v) { + return detail::async_engine::template generate( + executor, std::forward(token)); + } else { + return detail::complete_by_post(executor, token, + []() noexcept { return Keypair::generate(); }); + } + } +} + /** * Seals a message in place, asynchronously: `aead.seal(iv_bytes, additional_data_bytes, * data_bytes)` run when the operation is initiated, its result posted to `executor`. @@ -314,6 +376,104 @@ auto async_open(Executor const& executor, Gcm& aead, std::span`; the other key pairs are not in + * WebCrypto: call their `sign`. + * @param executor The executor the completion is posted to. + * @param key_pair The key pair. + * @param message Any bytes. + * @param token The completion token, of signature `void(boost::system::error_code, + * std::array)`: the signature; on an error 64 zeros (`invalid_state`, + * `backend_failure`). + * @return What the completion token's `async_result` gives. + */ +template +auto async_sign(Executor const& executor, Keypair const& key_pair, + std::span message, CompletionToken&& token) { + detail::timing_guard const timing; + if constexpr (!detail::is_ed25519_keypair_v) { + static_assert(detail::refused_v, + "webcpp::crypto: async_sign takes a key pair of an algorithm WebCrypto has " + "(Ed25519, P-256): call the key pair's sign for the others."); + } else { + using backend = Keypair::backend_type; + if constexpr (detail::asynchronous_backend_v) { + return detail::async_engine::sign(executor, key_pair, message, + std::forward(token)); + } else { + return detail::complete_by_post(executor, token, [&key_pair, message]() noexcept { + return key_pair.sign(message); + }); + } + } +} + +/** + * Verifies an Ed25519 signature, asynchronously: `curves::ed25519::verify` + * run when the operation is initiated, its result posted to `executor`. The spans are the + * caller's until the completion. + * + * @tparam Policy The verification policy, `curves::ed25519::strict`. + * @tparam Backend The backend; by default the asynchronous family's. + * @param executor The executor the completion is posted to. + * @param public_key 32 bytes. + * @param message The signed bytes. + * @param signature 64 bytes. + * @param token The completion token, of signature `void(boost::system::error_code)`: + * `invalid_public_key` for a key of another size, `invalid_signature`. + * @return What the completion token's `async_result` gives. + */ +template , class Executor, + class CompletionToken> +auto async_verify(Executor const& executor, std::span public_key, + std::span message, std::span signature, + CompletionToken&& token) { + detail::timing_guard const timing; + if constexpr (detail::asynchronous_backend_v) { + return detail::async_engine::template verify( + executor, public_key, message, signature, std::forward(token)); + } else { + return detail::complete_by_post( + executor, token, [public_key, message, signature]() noexcept { + return curves::ed25519::verify(public_key, message, signature); + }); + } +} + +/** + * Agrees an X25519 shared secret, asynchronously: `curves::x25519::agree` run when the + * operation is initiated, its result posted to `executor`. The spans are the caller's until the + * completion. + * + * @tparam Backend The backend; by default the asynchronous family's. + * @param executor The executor the completion is posted to. + * @param secret_key 32 bytes. + * @param peer_public_key 32 bytes. + * @param token The completion token, of signature `void(boost::system::error_code, secret<32>)`: + * the shared secret; on an error a secret of zeros (`invalid_key_size`, `invalid_public_key`, + * `weak_public_key`, `backend_failure`). + * @return What the completion token's `async_result` gives. + */ +template , class Executor, + class CompletionToken> +auto async_agree(Executor const& executor, std::span secret_key, + std::span peer_public_key, CompletionToken&& token) { + detail::timing_guard const timing; + if constexpr (detail::asynchronous_backend_v) { + return detail::async_engine::agree(executor, secret_key, peer_public_key, + std::forward(token)); + } else { + return detail::complete_by_post(executor, token, [secret_key, peer_public_key]() noexcept { + return curves::x25519::agree(secret_key, peer_public_key); + }); + } +} + } // namespace webcpp::crypto #endif // WEBCPP_CRYPTO_ASYNC_HPP diff --git a/include/webcpp/crypto/curves/ed25519.hpp b/include/webcpp/crypto/curves/ed25519.hpp index 4597e49a..da3a0cc2 100644 --- a/include/webcpp/crypto/curves/ed25519.hpp +++ b/include/webcpp/crypto/curves/ed25519.hpp @@ -20,6 +20,7 @@ #include +#include #include #include #include @@ -88,6 +89,8 @@ class basic_keypair { friend class ph; template friend struct detail::ed25519_keypair_access; + // The asynchronous family's error completions make the empty object a move leaves. + friend struct detail::async_access; public: /** The family, for `supports_v`. */ diff --git a/test/Jamfile b/test/Jamfile index 8ee52fb8..ebef86aa 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -110,9 +110,10 @@ crypto-run heavy : heavy_test.cpp emscripten:-sPTHREAD_POOL_SIZE=3 : native emscripten ; # The cheap functions of the asynchronous family on a synchronous backend, on -# every target: detail::complete_by_post runs the call at once and completes -# through a post, on the handler's associated executor and in its associated -# allocator, with every completion token (use_future where exceptions are on). +# every target: detail::complete_by_post runs the call when the operation is +# initiated and completes through a post, on the handler's associated executor +# and in its associated allocator, with every completion token (use_future where +# exceptions are on). crypto-run async_post : async_post_test.cpp : /webcpp/asio//asio /webcpp/crypto//gcm-default /third_party//sodium ; @@ -124,6 +125,11 @@ crypto-run async_gcm : async_gcm_test.cpp crypto-run async_gcm_openssl : async_gcm_test.cpp : /webcpp/asio//asio /webcpp/crypto//openssl WEBCPP_TEST_ASYNC_GCM_OPENSSL : native wasip2 wasip3 ; +# Ed25519's and X25519's asynchronous functions on libsodium, every target: +# RFC 8032's and RFC 7748's cases, a changed byte, a generated key pair, a +# refused seed, a weak peer key, a coroutine. +crypto-run async_25519 : async_25519_test.cpp + : /webcpp/asio//asio /third_party//sodium ; # Without threads (WEBCPP_CRYPTO_NO_THREADS natively; WASI has none), a heavy # operation's async_ variant that forgets its refusal stops at # detail::run_on_work's stand-in, which names the refusal, and with that diff --git a/test/async_25519_test.cpp b/test/async_25519_test.cpp new file mode 100644 index 00000000..9b95fb3e --- /dev/null +++ b/test/async_25519_test.cpp @@ -0,0 +1,375 @@ +// 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) + +// Ed25519's and X25519's asynchronous functions on libsodium, on a callback and in a coroutine: +// - async_rfc8032: RFC 8032 section 7.1's tests 1, 2 and 3 through async_make and async_sign give +// the RFC's signatures and the synchronous ones, and async_verify accepts them; each completion +// arrives after the initiating call returned. +// - async_verify_changed: a changed byte of the signature or of the message completes with +// invalid_signature, a public key of 31 bytes with invalid_public_key. +// - async_generate: async_generate gives a key pair whose signature verifies, on the default +// backend and on libsodium named. +// - async_make_refused: a seed of 31 bytes completes with invalid_key_size and an empty key pair, +// which refuses every member with invalid_state (review focus 5), async_sign on it too, with +// a signature of zeros. +// - async_rfc7748: section 6.1's Alice and Bob through async_agree give the RFC's shared secret; +// a peer key of low order completes with weak_public_key and a secret of zeros; a short key +// with invalid_key_size. +// - async_coroutine: the same in one coroutine of the context. + +#include +#include +#include +#include +#include +#include +#include + +#include "support/hex.hpp" + +#include +#include +#include +#include +#include +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace asio = webcpp::asio; +namespace crypto = webcpp::crypto; +namespace ed25519 = webcpp::crypto::curves::ed25519; +namespace x25519 = webcpp::crypto::curves::x25519; +namespace test = webcpp::test; + +namespace { + +using keypair = ed25519::basic_keypair; +using signature_type = std::array; + +// What a completion saw: its calls, whether the initiating call had returned, its error code and +// its value, if it has one. +template +struct completed { + int calls = 0; + bool after_return = false; + boost::system::error_code code; + std::optional> value; +}; + +// Starts `start(executor, token)` with a callback, runs the context and returns what the +// callback saw: one completion, after the initiating call returned. +template +completed complete(asio::io_context& context, Start start) { + completed done; + bool returned = false; + start(context.get_executor(), + [&done, &returned](boost::system::error_code code, Value... value) { + ++done.calls; + done.after_return = returned; + done.code = code; + done.value = std::tuple(std::move(value)...); + }); + returned = true; + BOOST_TEST_EQ(done.calls, 0); + context.restart(); + context.run(); // lint-run: the test's event loop + BOOST_TEST_EQ(done.calls, 1); + BOOST_TEST(done.after_return); + return done; +} + +// The completion of an operation with no value. +template +boost::system::error_code complete_code(asio::io_context& context, Start start) { + completed<> done; + bool returned = false; + start(context.get_executor(), [&done, &returned](boost::system::error_code code) { + ++done.calls; + done.after_return = returned; + done.code = code; + }); + returned = true; + BOOST_TEST_EQ(done.calls, 0); + context.restart(); + context.run(); // lint-run: the test's event loop + BOOST_TEST_EQ(done.calls, 1); + BOOST_TEST(done.after_return); + return done.code; +} + +/** One test of RFC 8032 section 7.1, as the RFC writes it. */ +struct rfc8032_case { + std::string_view secret_key; + std::string_view public_key; + std::string_view message; + std::string_view signature; +}; + +// clang-format off +constexpr auto rfc8032_cases = std::to_array({ + {.secret_key = "9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60", + .public_key = "d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a", + .message = "", + .signature = "e5564300c360ac729086e2cc806e828a84877f1eb8e5d974d873e065224901555fb8821590a33bacc61e39701cf9b46bd25bf5f0595bbe24655141438e7a100b", + }, + {.secret_key = "4ccd089b28ff96da9db6c346ec114e0f5b8a319f35aba624da8cf6ed4fb8a6fb", + .public_key = "3d4017c3e843895a92b70aa74d1b7ebc9c982ccf2ec4968cc0cd55f12af4660c", + .message = "72", + .signature = "92a009a9f0d4cab8720e820b5f642540a2b27b5416503f8fb3762223ebdb69da085ac1e43e15996e458f3613d0f11d8c387b2eaeb4302aeeb00d291612bb0c00", + }, + {.secret_key = "c5aa8df43f9f837bedb7442f31dcb7b166d38535076f094b85ce3a2e0b4458f7", + .public_key = "fc51cd8e6218a1a38da47ed00230f0580816ed13ba3303ac5deb911548908025", + .message = "af82", + .signature = "6291d657deec24024827e69c3abe01a30ce548a284743a445e3680d7db5ac3ac18ff9b538d16f290ae67f760984dc6594a7c15e9716ed28dc027beceea1ec40a", + }, +}); +// clang-format on + +/** Whether every byte of `bytes` is zero. */ +template +bool all_zero(Bytes const& bytes) { + return std::ranges::all_of(bytes, [](std::uint8_t byte) { return byte == 0; }); +} + +void async_rfc8032(asio::io_context& context) { + for (auto const& tested : rfc8032_cases) { + auto const seed = test::from_hex(tested.secret_key); + auto const public_key = test::from_hex(tested.public_key); + auto const message = test::from_hex(tested.message); + auto const expected = test::from_hex(tested.signature); + + auto made = complete(context, [&](auto const& executor, auto&& token) { + return crypto::async_make(executor, seed, + std::forward(token)); + }); + BOOST_TEST(!made.code); + if (!BOOST_TEST(made.value.has_value())) { + continue; + } + auto& key = std::get<0>(*made.value); + auto const signed_async = complete(context, [&](auto const& executor, + auto&& token) { + return crypto::async_sign(executor, key, message, std::forward(token)); + }); + BOOST_TEST(!signed_async.code); + if (!BOOST_TEST(signed_async.value.has_value())) { + continue; + } + auto const& signature = std::get<0>(*signed_async.value); + BOOST_TEST(std::ranges::equal(signature, expected)); + auto const signed_sync = key.sign(message); + BOOST_TEST(signed_sync.has_value() && *signed_sync == signature); + auto const verified = complete_code(context, [&](auto const& executor, auto&& token) { + return crypto::async_verify( + executor, public_key, message, signature, std::forward(token)); + }); + BOOST_TEST(!verified); + // The defaults name the same backend. + auto const verified_default = + complete_code(context, [&](auto const& executor, auto&& token) { + return crypto::async_verify(executor, public_key, message, signature, + std::forward(token)); + }); + BOOST_TEST(!verified_default); + } +} + +void async_verify_changed(asio::io_context& context) { + auto const& tested = rfc8032_cases[2]; + auto const public_key = test::from_hex(tested.public_key); + auto message = test::from_hex(tested.message); + auto signature = test::from_hex(tested.signature); + auto const verify = [&](std::span key) { + return complete_code(context, [&](auto const& executor, auto&& token) { + return crypto::async_verify(executor, key, message, signature, + std::forward(token)); + }); + }; + BOOST_TEST(!verify(public_key)); + signature[10] ^= 1U; + BOOST_TEST(verify(public_key) == crypto::error::invalid_signature); + signature[10] ^= 1U; + message[0] ^= 1U; + BOOST_TEST(verify(public_key) == crypto::error::invalid_signature); + message[0] ^= 1U; + BOOST_TEST(!verify(public_key)); + BOOST_TEST(verify(std::span(public_key).first(31)) == crypto::error::invalid_public_key); +} + +template +void generated(asio::io_context& context) { + auto made = complete(context, [](auto const& executor, auto&& token) { + return crypto::async_generate(executor, std::forward(token)); + }); + BOOST_TEST(!made.code); + if (!BOOST_TEST(made.value.has_value())) { + return; + } + auto& key = std::get<0>(*made.value); + std::array const message{1, 2, 3, 4, 5}; + auto const public_key = key.public_key(); + auto const signature = key.sign(message); + if (!BOOST_TEST(public_key.has_value()) || !BOOST_TEST(signature.has_value())) { + return; + } + auto const verified_sync = ed25519::verify( + *public_key, message, *signature); + BOOST_TEST(verified_sync.has_value()); + auto const signed_async = + complete(context, [&](auto const& executor, auto&& token) { + return crypto::async_sign(executor, key, message, std::forward(token)); + }); + BOOST_TEST(!signed_async.code); + auto const verified = complete_code(context, [&](auto const& executor, auto&& token) { + return crypto::async_verify(executor, *public_key, message, *signature, + std::forward(token)); + }); + BOOST_TEST(!verified); +} + +void async_generate(asio::io_context& context) { + generated(context); + generated(context); +} + +void async_make_refused(asio::io_context& context) { + std::array const seed{7}; + auto const made = complete(context, [&](auto const& executor, auto&& token) { + return crypto::async_make(executor, std::span(seed).first(31), + std::forward(token)); + }); + BOOST_TEST(made.code == crypto::error::invalid_key_size); + if (!BOOST_TEST(made.value.has_value())) { + return; + } + auto const& empty = std::get<0>(*made.value); + std::array const message{1, 2, 3}; + BOOST_TEST(empty.public_key().error() == crypto::error::invalid_state); + BOOST_TEST(empty.sign(message).error() == crypto::error::invalid_state); + BOOST_TEST(empty.x25519_secret().error() == crypto::error::invalid_state); + auto const signed_empty = complete(context, [&](auto const& executor, + auto&& token) { + return crypto::async_sign(executor, empty, message, std::forward(token)); + }); + BOOST_TEST(signed_empty.code == crypto::error::invalid_state); + if (BOOST_TEST(signed_empty.value.has_value())) { + BOOST_TEST(all_zero(std::get<0>(*signed_empty.value))); + } +} + +void async_rfc7748(asio::io_context& context) { + auto const alice_secret = + test::from_hex("77076d0a7318a57d3c16c17251b26645df4c2f87ebc0992ab177fba51db92c2a"); + auto const bob_secret = + test::from_hex("5dab087e624a8a4b79e17f8b83800ee66f3bb1292618b6fd1c2f8b27ff88e0eb"); + auto const alice_public = + test::from_hex("8520f0098930a754748b7ddcb43ef75a0dbf3a0d26381af4eba4a98eaa9b4e6a"); + auto const bob_public = + test::from_hex("de9edb7d7b7dc1b4d35b61c2ece435373f8343c85b78674dadfc7e146f882b4f"); + auto const shared = + test::from_hex("4a5d9d5ba4ce2de1728e3bf480350f25e07e21c947d19e3376f09b3c1e161742"); + auto const agree = [&](std::span secret_key, + std::span peer) { + return complete>(context, [&](auto const& executor, auto&& token) { + return crypto::async_agree(executor, secret_key, peer, + std::forward(token)); + }); + }; + for (auto const& done : {agree(alice_secret, bob_public), agree(bob_secret, alice_public)}) { + BOOST_TEST(!done.code); + if (BOOST_TEST(done.value.has_value())) { + auto const bytes = std::get<0>(*done.value).bytes(); + BOOST_TEST(std::ranges::equal(bytes, shared)); + } + } + // Named backend. + auto const named = + complete>(context, [&](auto const& executor, auto&& token) { + return crypto::async_agree( + executor, alice_secret, bob_public, std::forward(token)); + }); + BOOST_TEST(!named.code); + + // Wycheproof x25519_test.json, tcId 63: a public key of order 8, whose shared secret is 0. + auto const weak = + agree(test::from_hex("e0f978dfcd3a8f1a5093418de54136a584c20b7b349afdf6c0520886f95b1272"), + test::from_hex("e0eb7a7c3b41b8ae1656e3faf19fc46ada098deb9c32b1fd866205165f49b800")); + BOOST_TEST(weak.code == crypto::error::weak_public_key); + if (BOOST_TEST(weak.value.has_value())) { + BOOST_TEST(all_zero(std::get<0>(*weak.value).bytes())); + } + auto const short_key = agree(std::span(alice_secret).first(31), bob_public); + BOOST_TEST(short_key.code == crypto::error::invalid_key_size); + auto const short_peer = agree(alice_secret, std::span(bob_public).first(31)); + BOOST_TEST(short_peer.code == crypto::error::invalid_public_key); +} + +void async_coroutine(asio::io_context& context) { + bool done = false; + asio::co_spawn( + context, + [&]() -> asio::awaitable { + auto const executor = co_await asio::this_coro::executor; + auto const& tested = rfc8032_cases[1]; + auto const seed = test::from_hex(tested.secret_key); + auto const public_key = test::from_hex(tested.public_key); + auto const message = test::from_hex(tested.message); + auto [made_code, key] = co_await crypto::async_make( + executor, seed, asio::as_tuple(asio::use_awaitable)); + BOOST_TEST(!made_code); + auto [sign_code, signature] = co_await crypto::async_sign( + executor, key, message, asio::as_tuple(asio::use_awaitable)); + BOOST_TEST(!sign_code); + BOOST_TEST(std::ranges::equal(signature, test::from_hex(tested.signature))); + auto [verify_code] = co_await crypto::async_verify( + executor, public_key, message, signature, asio::as_tuple(asio::use_awaitable)); + BOOST_TEST(!verify_code); + auto [generate_code, generated_key] = + co_await crypto::async_generate(executor, asio::as_tuple(asio::use_awaitable)); + BOOST_TEST(!generate_code); + BOOST_TEST(generated_key.public_key().has_value()); + auto [agree_code, shared] = co_await crypto::async_agree( + executor, + test::from_hex("77076d0a7318a57d3c16c17251b26645df4c2f87ebc0992ab177fba51db92c2a"), + test::from_hex("de9edb7d7b7dc1b4d35b61c2ece435373f8343c85b78674dadfc7e146f882b4f"), + asio::as_tuple(asio::use_awaitable)); + BOOST_TEST(!agree_code); + BOOST_TEST(std::ranges::equal( + shared.bytes(), test::from_hex("4a5d9d5ba4ce2de1728e3bf480350f25e07e21c947d19e3376" + "f09b3c1e161742"))); + done = true; + }, + [](std::exception_ptr const& failure) { BOOST_TEST(!failure); }); + context.restart(); + context.run(); // lint-run: the test's event loop + BOOST_TEST(done); +} + +} // namespace + +int main() { + asio::io_context context; + async_rfc8032(context); + async_verify_changed(context); + async_generate(context); + async_make_refused(context); + async_rfc7748(context); + async_coroutine(context); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/async_post_test.cpp b/test/async_post_test.cpp index dab33b14..4faf45d4 100644 --- a/test/async_post_test.cpp +++ b/test/async_post_test.cpp @@ -27,16 +27,23 @@ // - post_gcm: the same cases through AES-GCM's async_make, async_seal and async_open (the // functions the family really has, Task 4.A3): never inside the call, the work done when the // call returns, a bound executor, the handler's allocator, every token, an error's empty -// value. Task 4.A4 adds async_verify's. +// value. +// - post_verify_*: the same cases through Ed25519's async_verify (no value), RFC 8032's test 2, +// and, for the value shapes, async_sign (an array) and async_agree (a secret<32>): never +// inside the call, the work done when the call returns, a bound executor, the handler's +// allocator, every token, an error's empty value. // Each check takes the operation's start as a callable of (executor, token). #include #include +#include +#include #include #include #include #include "support/counting.hpp" +#include "support/hex.hpp" #include #include @@ -68,6 +75,7 @@ #include #include #include +#include namespace asio = webcpp::asio; namespace crypto = webcpp::crypto; @@ -724,6 +732,209 @@ void post_gcm_tokens(asio::io_context& context) { BOOST_TEST(done); } +// Ed25519's async_verify, async_sign and X25519's async_agree through the family's real +// functions, on the default backend. The fixture: RFC 8032's test 2 and RFC 7748's section 6.1. +struct verify_fixture { + std::vector seed = + webcpp::test::from_hex("4ccd089b28ff96da9db6c346ec114e0f5b8a319f35aba624da8cf6ed4fb8a6fb"); + std::vector public_key = + webcpp::test::from_hex("3d4017c3e843895a92b70aa74d1b7ebc9c982ccf2ec4968cc0cd55f12af4660c"); + std::vector message = webcpp::test::from_hex("72"); + std::vector signature = webcpp::test::from_hex( + "92a009a9f0d4cab8720e820b5f642540a2b27b5416503f8fb3762223ebdb69da085ac1e43e15996e458f3613d0" + "f" + "11d8c387b2eaeb4302aeeb00d291612bb0c00"); + std::vector secret_key = + webcpp::test::from_hex("77076d0a7318a57d3c16c17251b26645df4c2f87ebc0992ab177fba51db92c2a"); + std::vector peer_key = + webcpp::test::from_hex("de9edb7d7b7dc1b4d35b61c2ece435373f8343c85b78674dadfc7e146f882b4f"); + crypto::curves::ed25519::keypair key_pair = *crypto::curves::ed25519::keypair::make(seed); + + auto verify() { + return [this](auto const& executor, auto&& token) { + return crypto::async_verify(executor, public_key, message, signature, + std::forward(token)); + }; + } + + auto verify_refused() { + return [this](auto const& executor, auto&& token) { + return crypto::async_verify(executor, std::span(public_key).first(31), message, + signature, std::forward(token)); + }; + } + + auto sign() { + return [this](auto const& executor, auto&& token) { + return crypto::async_sign(executor, key_pair, message, + std::forward(token)); + }; + } + + auto agree() { + return [this](auto const& executor, auto&& token) { + return crypto::async_agree(executor, secret_key, peer_key, + std::forward(token)); + }; + } + + auto agree_refused() { + return [this](auto const& executor, auto&& token) { + return crypto::async_agree(executor, std::span(secret_key).first(31), peer_key, + std::forward(token)); + }; + } +}; + +// complete_by_callback of a real function, whose synchronous call is not counted by sync_runs: the +// completion comes after the initiating call returned, never inside it. +template +seen complete_later(asio::io_context& context, Start start) { + seen done; + bool returned = false; + start(context.get_executor(), + [&done, &returned](boost::system::error_code code, Value... value) { + ++done.calls; + done.after_return = returned; + done.code = code; + done.value = std::tuple(std::move(value)...); + }); + returned = true; + BOOST_TEST_EQ(done.calls, 0); + context.restart(); + context.run(); // lint-run: the test's event loop + BOOST_TEST_EQ(done.calls, 1); + BOOST_TEST(done.after_return); + return done; +} + +void post_verify_inline(asio::io_context& context) { + verify_fixture fixture; + auto const verified = complete_later<>(context, fixture.verify()); + BOOST_TEST(!verified.code); + // A changed signature is refused. + ++fixture.signature[3]; + auto const refused = complete_later<>(context, fixture.verify()); + BOOST_TEST(refused.code == crypto::error::invalid_signature); + --fixture.signature[3]; + auto const short_key = complete_later<>(context, fixture.verify_refused()); + BOOST_TEST(short_key.code == crypto::error::invalid_public_key); + // The value shapes: a signature (an array) and a shared secret, and an error's empty value. + auto const signed_message = complete_later(context, fixture.sign()); + BOOST_TEST(!signed_message.code); + BOOST_TEST(std::ranges::equal(std::get<0>(signed_message.value), fixture.signature)); + auto const agreed = complete_later(context, fixture.agree()); + BOOST_TEST(!agreed.code); + auto const agree_refused = complete_later(context, fixture.agree_refused()); + BOOST_TEST(agree_refused.code == crypto::error::invalid_key_size); + BOOST_TEST(all_bytes(std::get<0>(agree_refused.value), 0)); +} + +void post_verify_bound_executor() { + verify_fixture fixture; + complete_on_bound<>(fixture.verify()); + complete_on_bound(fixture.sign()); + complete_on_bound(fixture.agree()); +} + +void post_verify_allocator(asio::io_context& context) { + verify_fixture fixture; + allocator_call warm; + start_counted<>(context, fixture.verify(), warm); + BOOST_TEST_EQ(warm.calls, 1); + allocator_call verified; + start_counted<>(context, fixture.verify(), verified); + BOOST_TEST(!verified.code); + BOOST_TEST_EQ(verified.held_at_call, 0); + BOOST_TEST_GE(verified.taken, 1); + BOOST_TEST_EQ(verified.news, 0U); + allocator_call refused; + start_counted<>(context, fixture.verify_refused(), refused); + BOOST_TEST(refused.code == crypto::error::invalid_public_key); + BOOST_TEST_EQ(refused.held_at_call, 0); + BOOST_TEST_GE(refused.taken, 1); + BOOST_TEST_EQ(refused.news, 0U); + check_allocator_with(context, fixture.agree(), fixture.agree_refused(), + crypto::error::invalid_key_size); +} + +void post_verify_tokens(asio::io_context& context) { + verify_fixture fixture; + auto const executor = context.get_executor(); + +#ifndef WEBCPP_CRYPTO_NO_EXCEPTIONS + auto future_ok = fixture.verify()(executor, asio::use_future); + auto future_refused = fixture.verify_refused()(executor, asio::use_future); + auto future_secret = fixture.agree()(executor, asio::use_future); + context.restart(); + context.run(); // lint-run: the test's event loop + future_ok.get(); + BOOST_TEST(!all_bytes(future_secret.get(), 0)); + bool thrown = false; + try { + future_refused.get(); + } catch (boost::system::system_error const& failure) { + thrown = failure.code() == crypto::error::invalid_public_key; + } + BOOST_TEST(thrown); +#endif + + // deferred: the synchronous call runs when the operation is launched, not when it is made. + ++fixture.signature[0]; + auto operation = fixture.verify()(executor, asio::deferred); + --fixture.signature[0]; + int deferred_calls = 0; + // The signature is intact again when the operation is launched: the call reads it then. + std::move(operation)([&](boost::system::error_code code) { + ++deferred_calls; + BOOST_TEST(!code); + }); + BOOST_TEST_EQ(deferred_calls, 0); + context.restart(); + context.run(); // lint-run: the test's event loop + BOOST_TEST_EQ(deferred_calls, 1); + + // as_tuple: the code alone, and the code with the value of an error. + int tuples = 0; + fixture.verify_refused()(executor, + asio::as_tuple([&](std::tuple done) { + ++tuples; + BOOST_TEST(std::get<0>(done) == crypto::error::invalid_public_key); + })); + fixture.agree_refused()(executor, + asio::as_tuple([&](std::tuple done) { + ++tuples; + BOOST_TEST(std::get<0>(done) == crypto::error::invalid_key_size); + BOOST_TEST(all_bytes(std::get<1>(done), 0)); + })); + context.restart(); + context.run(); // lint-run: the test's event loop + BOOST_TEST_EQ(tuples, 2); + + // use_awaitable in a coroutine of the context: a refusal through as_tuple. + bool done = false; + asio::co_spawn( + context, + [&]() -> asio::awaitable { + auto const coro = co_await asio::this_coro::executor; + auto [verify_code] = + co_await fixture.verify()(coro, asio::as_tuple(asio::use_awaitable)); + BOOST_TEST(!verify_code); + auto [sign_code, signature] = + co_await fixture.sign()(coro, asio::as_tuple(asio::use_awaitable)); + BOOST_TEST(!sign_code); + BOOST_TEST(std::ranges::equal(signature, fixture.signature)); + auto [refused_code] = + co_await fixture.verify_refused()(coro, asio::as_tuple(asio::use_awaitable)); + BOOST_TEST(refused_code == crypto::error::invalid_public_key); + done = true; + }, + [](std::exception_ptr const& failure) { BOOST_TEST(!failure); }); + context.restart(); + context.run(); // lint-run: the test's event loop + BOOST_TEST(done); +} + // The asynchronous default is the synchronous one, on every target (ruling R-A4), and no // synchronous backend completes by itself: part B's backends::browser alone will. template @@ -748,5 +959,9 @@ int main() { post_gcm_bound_executor(); post_gcm_allocator(context); post_gcm_tokens(context); + post_verify_inline(context); + post_verify_bound_executor(); + post_verify_allocator(context); + post_verify_tokens(context); return webcpp::test::exit_status(boost::report_errors()); } diff --git a/test/messages/Jamfile b/test/messages/Jamfile index 79b3846c..6c0de297 100644 --- a/test/messages/Jamfile +++ b/test/messages/Jamfile @@ -30,6 +30,7 @@ build-project ed25519ph_sha256 ; build-project ed25519_default_not_linked ; build-project heavy_without_threads ; build-project async_seal_xchacha ; +build-project async_sign_secp256k1 ; build-project heavy_without_threads_first ; build-project chacha_default_not_linked ; build-project aead_not_a_family ; diff --git a/test/messages/async_sign_secp256k1/Jamfile b/test/messages/async_sign_secp256k1/Jamfile new file mode 100644 index 00000000..b9bdd639 --- /dev/null +++ b/test/messages/async_sign_secp256k1/Jamfile @@ -0,0 +1,15 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/crypto//crypto ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +webcpp.compile-diagnostic async_sign_secp256k1 : async_sign_secp256k1.cpp + : /webcpp/asio//asio /third_party//sodium /third_party//secp256k1 + : native wasip2 wasip3 : alone ; diff --git a/test/messages/async_sign_secp256k1/async_sign_secp256k1.cpp b/test/messages/async_sign_secp256k1/async_sign_secp256k1.cpp new file mode 100644 index 00000000..ab9d9182 --- /dev/null +++ b/test/messages/async_sign_secp256k1/async_sign_secp256k1.cpp @@ -0,0 +1,40 @@ +// 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) + +// async_sign on a key pair of an algorithm WebCrypto lacks, secp256k1's, stops with the key pair's +// own signing to call instead, and with that error alone, while the key pair's sign_ecdsa +// compiles. + +// clang-format off +// expected-error@webcpp/crypto/async.hpp:* {{webcpp::crypto: async_sign takes a key pair of an algorithm WebCrypto has (Ed25519, P-256): call the key pair's sign for the others.}} +// clang-format on +#include +#include + +#include + +#include + +#include +#include + +int main() { + namespace crypto = webcpp::crypto; + std::array const seed{1}; + std::array const message{}; + auto made = crypto::curves::secp256k1::keypair::make(seed); + if (!made) { + return 1; + } + // The synchronous signing compiles. + if (!made->sign_ecdsa(message)) { + return 1; + } + webcpp::asio::io_context context; + crypto::async_sign(context.get_executor(), *made, message, + [](boost::system::error_code, std::array) {}); + return 0; +} diff --git a/test/msvc/Jamfile b/test/msvc/Jamfile index 20778e17..cf350848 100644 --- a/test/msvc/Jamfile +++ b/test/msvc/Jamfile @@ -49,6 +49,7 @@ build-project ed25519ph_sha256 ; build-project ed25519_default_not_linked ; build-project heavy_without_threads ; build-project async_seal_xchacha ; +build-project async_sign_secp256k1 ; build-project chacha_default_not_linked ; build-project aead_not_a_family ; build-project chacha_on_ctaes ; diff --git a/test/msvc/async_sign_secp256k1/Jamfile b/test/msvc/async_sign_secp256k1/Jamfile new file mode 100644 index 00000000..29721cb2 --- /dev/null +++ b/test/msvc/async_sign_secp256k1/Jamfile @@ -0,0 +1,12 @@ +# 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) + +import webcpp ; + +webcpp.compile-fail async_sign_secp256k1 : app.cpp + : /webcpp/crypto//crypto /webcpp/asio//asio /third_party//sodium + /third_party//secp256k1 + : native ; diff --git a/test/msvc/async_sign_secp256k1/app.cpp b/test/msvc/async_sign_secp256k1/app.cpp new file mode 100644 index 00000000..cad59427 --- /dev/null +++ b/test/msvc/async_sign_secp256k1/app.cpp @@ -0,0 +1,32 @@ +// 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) + +// async_sign on a key pair of an algorithm WebCrypto lacks, secp256k1's, stops where it is +// called: on MSVC the compile fails. The text is checked on clang, in +// test/messages/async_sign_secp256k1. +#include +#include + +#include + +#include + +#include +#include + +int main() { + namespace crypto = webcpp::crypto; + std::array const seed{1}; + std::array const message{}; + auto made = crypto::curves::secp256k1::keypair::make(seed); + if (!made) { + return 1; + } + webcpp::asio::io_context context; + crypto::async_sign(context.get_executor(), *made, message, + [](boost::system::error_code, std::array) {}); + return 0; +} diff --git a/test/support/timing_coverage.hpp b/test/support/timing_coverage.hpp index 347f7ade..62d5eaa2 100644 --- a/test/support/timing_coverage.hpp +++ b/test/support/timing_coverage.hpp @@ -19,6 +19,8 @@ #include #include #include +#include +#include #include #include @@ -410,6 +412,115 @@ void cover_async_gcm(std::string const& family, std::string const& backend) { BOOST_TEST_EQ(completions, 6); } +/** + * Ed25519's asynchronous functions, `async_make`, `async_generate`, `async_sign` and + * `async_verify`, each called with valid input and with input refused before the backend (a seed + * or public key of 31 bytes, a moved-from key pair), an `io_context` run after each call so that + * its completion is delivered. The first guard each enters is its own (the synchronous call it + * makes holds another, which runs second). + * + * @tparam Keypair `curves::ed25519::basic_keypair`. + * @param backend The backend's name. + */ +template +void cover_async_ed25519(std::string const& backend) { + namespace crypto = webcpp::crypto; + using signature_type = std::array; + using backend_type = Keypair::backend_type; + std::string const on = " on " + backend; + webcpp::asio::io_context context; + auto const executor = context.get_executor(); + auto const seed = coverage_key(); + std::array const message{1, 2, 3}; + int completions = 0; + signature_type kept{}; + async_gcm_completion const counted{&completions}; + async_gcm_completion const keeping{&completions, &kept}; + // Each call's completion is delivered before the next call. + auto const deliver = [&context] { + context.restart(); + context.run(); // lint-run: the test's event loop + }; + covered("ed25519::async_make" + on, "crypto::async_make", [&] { + crypto::async_make(executor, seed, counted); + deliver(); + }); + covered("ed25519::async_make with a short seed" + on, "crypto::async_make", [&] { + crypto::async_make(executor, std::span(seed).first(Keypair::seed_size - 1), + counted); + deliver(); + }); + covered("ed25519::async_generate" + on, "crypto::async_generate", [&] { + crypto::async_generate(executor, counted); + deliver(); + }); + auto made = Keypair::make(seed); + if (!BOOST_TEST(made.has_value())) { + return; + } + auto const public_key = made->public_key(); + if (!BOOST_TEST(public_key.has_value())) { + return; + } + covered("ed25519::async_sign" + on, "crypto::async_sign", [&] { + crypto::async_sign(executor, *made, message, keeping); + deliver(); + }); + covered("ed25519::async_verify" + on, "crypto::async_verify", [&] { + crypto::async_verify(executor, *public_key, + message, kept, counted); + deliver(); + }); + covered("ed25519::async_verify with a short key" + on, "crypto::async_verify", [&] { + crypto::async_verify( + executor, std::span(*public_key).first(31), message, kept, counted); + deliver(); + }); + [[maybe_unused]] Keypair const taken(std::move(*made)); + covered("ed25519::async_sign moved from" + on, "crypto::async_sign", [&] { + // NOLINTNEXTLINE(bugprone-use-after-move): the moved-from key pair's refusal + crypto::async_sign(executor, *made, message, counted); + deliver(); + }); + BOOST_TEST_EQ(completions, 7); +} + +/** + * X25519's asynchronous `async_agree`, called with valid input and with a key of 31 bytes, an + * `io_context` run after each call so that its completion is delivered. Its first guard is its + * own (the synchronous call it makes holds others, which run after). + * + * @tparam Backend The backend of X25519. + * @param backend The backend's name. + */ +template +void cover_async_x25519(std::string const& backend) { + namespace crypto = webcpp::crypto; + std::string const on = " on " + backend; + webcpp::asio::io_context context; + auto const executor = context.get_executor(); + auto const alice = coverage_key<32>(); + auto bob_secret = coverage_key<32>(); + bob_secret[0] ^= 0x42U; + auto const bob = crypto::curves::x25519::public_key(bob_secret); + if (!BOOST_TEST(bob.has_value())) { + return; + } + int completions = 0; + async_gcm_completion> const counted{&completions}; + covered("x25519::async_agree" + on, "crypto::async_agree", [&] { + crypto::async_agree(executor, alice, *bob, counted); + context.restart(); + context.run(); // lint-run: the test's event loop + }); + covered("x25519::async_agree with a short key" + on, "crypto::async_agree", [&] { + crypto::async_agree(executor, std::span(alice).first(31), *bob, counted); + context.restart(); + context.run(); // lint-run: the test's event loop + }); + BOOST_TEST_EQ(completions, 2); +} + /** * ciphers::aead's guarded functions: `make`, a key of the wrong size included, `seal` and * `open`, a nonce of the wrong size included. diff --git a/test/timing_coverage_sodium_test.cpp b/test/timing_coverage_sodium_test.cpp index c672e09f..0453091a 100644 --- a/test/timing_coverage_sodium_test.cpp +++ b/test/timing_coverage_sodium_test.cpp @@ -20,8 +20,9 @@ // - Ed25519, basic_keypair: make, generate, public_key, sign, x25519_secret; the free verify and // to_x25519_public. Ed25519ph, ph: begin, update, sign, verify. Its formats: decode_spki, // decode_pkcs8 (the encoders call no backend and hold no guard, ruling R4). -// - X25519, algorithm: public_key, agree; the free public_key and agree, which forward. Its -// formats: decode_spki, decode_pkcs8. +// - Ed25519's asynchronous functions: async_make, async_generate, async_sign, async_verify. +// - X25519, algorithm: public_key, agree; the free public_key and agree, which forward, and +// the asynchronous async_agree. Its formats: decode_spki, decode_pkcs8. // - crypto_kx, kx_keypair: make, generate, client_session_keys, server_session_keys. #include "support/timing_seam.hpp" @@ -479,6 +480,8 @@ void cover_kx() { /** Ed25519, Ed25519ph, X25519, crypto_kx, and the decoders of the key formats. */ void cover_curves() { cover_ed25519_keypair(); + webcpp::test::cover_async_ed25519>("sodium"); + webcpp::test::cover_async_x25519("sodium"); cover_ed25519_free(); cover_ed25519ph(); cover_ed25519ph_refusals(); From f7c314dde8146b5507c98fa2df79676a04a436c9 Mon Sep 17 00:00:00 2001 From: R Date: Sat, 21 Nov 2026 22:25:39 -0300 Subject: [PATCH 06/14] crypto: refusal texts name the synchronous function to call, the coverage counter is generic, and the review's minors of 4.A3 and 4.A4 are closed --- include/webcpp/crypto/async.hpp | 15 ++++--- test/async_25519_test.cpp | 45 +++++++++++++++++++ test/async_gcm_test.cpp | 37 +++++++++++++++ test/async_post_test.cpp | 7 ++- test/messages/Jamfile | 2 + test/messages/async_make_xchacha/Jamfile | 14 ++++++ .../async_make_xchacha/async_make_xchacha.cpp | 42 +++++++++++++++++ test/messages/async_open_xchacha/Jamfile | 14 ++++++ .../async_open_xchacha/async_open_xchacha.cpp | 42 +++++++++++++++++ .../async_sign_secp256k1.cpp | 2 +- test/msvc/Jamfile | 2 + test/msvc/async_make_xchacha/Jamfile | 11 +++++ test/msvc/async_make_xchacha/app.cpp | 34 ++++++++++++++ test/msvc/async_open_xchacha/Jamfile | 11 +++++ test/msvc/async_open_xchacha/app.cpp | 34 ++++++++++++++ test/support/timing_coverage.hpp | 18 ++++---- 16 files changed, 309 insertions(+), 21 deletions(-) create mode 100644 test/messages/async_make_xchacha/Jamfile create mode 100644 test/messages/async_make_xchacha/async_make_xchacha.cpp create mode 100644 test/messages/async_open_xchacha/Jamfile create mode 100644 test/messages/async_open_xchacha/async_open_xchacha.cpp create mode 100644 test/msvc/async_make_xchacha/Jamfile create mode 100644 test/msvc/async_make_xchacha/app.cpp create mode 100644 test/msvc/async_open_xchacha/Jamfile create mode 100644 test/msvc/async_open_xchacha/app.cpp diff --git a/include/webcpp/crypto/async.hpp b/include/webcpp/crypto/async.hpp index ea0ae8e1..e84ae0fa 100644 --- a/include/webcpp/crypto/async.hpp +++ b/include/webcpp/crypto/async.hpp @@ -244,7 +244,7 @@ auto async_make(Executor const& executor, std::span key_byte if constexpr (!detail::is_gcm_v && !detail::is_ed25519_keypair_v) { static_assert(detail::refused_v, "webcpp::crypto: async_make takes AES-GCM or a key pair of an algorithm " - "WebCrypto has (Ed25519, P-256): call make for the others."); + "WebCrypto has (Ed25519, P-256): call the synchronous make for the others."); } else { using backend = Algorithm::backend_type; if constexpr (detail::asynchronous_backend_v) { @@ -276,7 +276,7 @@ auto async_generate(Executor const& executor, CompletionToken&& token) { if constexpr (!detail::is_ed25519_keypair_v) { static_assert(detail::refused_v, "webcpp::crypto: async_generate takes a key pair of an algorithm WebCrypto " - "has (Ed25519, P-256): call generate for the others."); + "has (Ed25519, P-256): call the synchronous generate for the others."); } else { using backend = Keypair::backend_type; if constexpr (detail::asynchronous_backend_v) { @@ -396,9 +396,10 @@ auto async_sign(Executor const& executor, Keypair const& key_pair, std::span message, CompletionToken&& token) { detail::timing_guard const timing; if constexpr (!detail::is_ed25519_keypair_v) { - static_assert(detail::refused_v, - "webcpp::crypto: async_sign takes a key pair of an algorithm WebCrypto has " - "(Ed25519, P-256): call the key pair's sign for the others."); + static_assert( + detail::refused_v, + "webcpp::crypto: async_sign takes a key pair of an algorithm WebCrypto has " + "(Ed25519, P-256): call the key pair's synchronous signing function for the others."); } else { using backend = Keypair::backend_type; if constexpr (detail::asynchronous_backend_v) { @@ -417,14 +418,14 @@ auto async_sign(Executor const& executor, Keypair const& key_pair, * run when the operation is initiated, its result posted to `executor`. The spans are the * caller's until the completion. * - * @tparam Policy The verification policy, `curves::ed25519::strict`. + * @tparam Policy The verification policy; `curves::ed25519::strict` is the only one declared. * @tparam Backend The backend; by default the asynchronous family's. * @param executor The executor the completion is posted to. * @param public_key 32 bytes. * @param message The signed bytes. * @param signature 64 bytes. * @param token The completion token, of signature `void(boost::system::error_code)`: - * `invalid_public_key` for a key of another size, `invalid_signature`. + * `invalid_public_key` for a key of another size, `invalid_signature`, `backend_failure`. * @return What the completion token's `async_result` gives. */ template @@ -45,6 +49,7 @@ #include #include #include +#include #include #include #include @@ -320,6 +325,45 @@ void async_rfc7748(asio::io_context& context) { BOOST_TEST(short_peer.code == crypto::error::invalid_public_key); } +void async_destroyed(asio::io_context& context) { + auto const& tested = rfc8032_cases[0]; + auto const expected = test::from_hex(tested.signature); + signature_type signature{}; + boost::system::error_code sign_code; + boost::system::error_code agree_code; + std::array shared{}; + { + auto key = keypair::make(test::from_hex(tested.secret_key)); + auto message = std::make_unique>(test::from_hex(tested.message)); + auto secret_key = std::make_unique>( + test::from_hex("77076d0a7318a57d3c16c17251b26645df4c2f87ebc0992ab177fba51db92c2a")); + auto peer = std::make_unique>( + test::from_hex("de9edb7d7b7dc1b4d35b61c2ece435373f8343c85b78674dadfc7e146f882b4f")); + if (!BOOST_TEST(key.has_value())) { + return; + } + crypto::async_sign(context.get_executor(), *key, *message, + [&](boost::system::error_code code, signature_type done) { + sign_code = code; + signature = done; + }); + crypto::async_agree(context.get_executor(), *secret_key, *peer, + [&](boost::system::error_code code, crypto::secret<32> done) { + agree_code = code; + std::ranges::copy(done.bytes(), shared.begin()); + }); + // Everything the calls read goes out of scope here, before the completions. + } + context.restart(); + context.run(); // lint-run: the test's event loop + BOOST_TEST(!sign_code); + BOOST_TEST(std::ranges::equal(signature, expected)); + BOOST_TEST(!agree_code); + BOOST_TEST(std::ranges::equal( + shared, + test::from_hex("4a5d9d5ba4ce2de1728e3bf480350f25e07e21c947d19e3376f09b3c1e161742"))); +} + void async_coroutine(asio::io_context& context) { bool done = false; asio::co_spawn( @@ -370,6 +414,7 @@ int main() { async_generate(context); async_make_refused(context); async_rfc7748(context); + async_destroyed(context); async_coroutine(context); return webcpp::test::exit_status(boost::report_errors()); } diff --git a/test/async_gcm_test.cpp b/test/async_gcm_test.cpp index 1eebb260..217aab1a 100644 --- a/test/async_gcm_test.cpp +++ b/test/async_gcm_test.cpp @@ -15,6 +15,8 @@ // seal (with a zeroed tag) and the open. // - async_make_refused: a 31-byte key completes with invalid_key_size and an empty gcm, which // refuses every member with invalid_state (review focus 5). +// - async_destroyed: the object destroyed after the initiating call and before the completion +// still completes with the synchronous result (the work ran before the call returned). // - async_coroutine: the example of async.hpp's header, in a coroutine of the context. #include @@ -285,6 +287,40 @@ void async_make_refused(asio::io_context& context) { } // The example of async.hpp's header, in a coroutine of the context: make, seal, open. +// The object and the key destroyed after the initiating call and before the completion: a +// synchronous backend has sealed already, so the tag and the ciphertext are the synchronous ones. +void async_destroyed(asio::io_context& context) { + std::array const iv{}; + std::array const additional_data{1, 2, 3, 4}; + std::array data{}; + data.fill(0x5a); + auto expected_data = data; + gcm256::result_type expected_tag{}; + { + gcm256 reference = keyed(context); + auto const sealed = reference.seal(iv, additional_data, expected_data); + if (!BOOST_TEST(sealed.has_value())) { + return; + } + expected_tag = *sealed; + } + gcm256::result_type tag{}; + boost::system::error_code code; + { + gcm256 aead = keyed(context); + crypto::async_seal(context.get_executor(), aead, iv, additional_data, data, + [&](boost::system::error_code done_code, gcm256::result_type done) { + code = done_code; + tag = done; + }); + } + context.restart(); + context.run(); // lint-run: the test's event loop + BOOST_TEST(!code); + BOOST_TEST(data == expected_data); + BOOST_TEST(tag == expected_tag); +} + void async_coroutine(asio::io_context& context) { bool done = false; asio::co_spawn( @@ -325,6 +361,7 @@ int main() { async_wrong_tag(context); async_long_iv(context); async_make_refused(context); + async_destroyed(context); async_coroutine(context); return webcpp::test::exit_status(boost::report_errors()); } diff --git a/test/async_post_test.cpp b/test/async_post_test.cpp index 4faf45d4..9b60bf41 100644 --- a/test/async_post_test.cpp +++ b/test/async_post_test.cpp @@ -740,10 +740,9 @@ struct verify_fixture { std::vector public_key = webcpp::test::from_hex("3d4017c3e843895a92b70aa74d1b7ebc9c982ccf2ec4968cc0cd55f12af4660c"); std::vector message = webcpp::test::from_hex("72"); - std::vector signature = webcpp::test::from_hex( - "92a009a9f0d4cab8720e820b5f642540a2b27b5416503f8fb3762223ebdb69da085ac1e43e15996e458f3613d0" - "f" - "11d8c387b2eaeb4302aeeb00d291612bb0c00"); + // clang-format off + std::vector signature = webcpp::test::from_hex("92a009a9f0d4cab8720e820b5f642540a2b27b5416503f8fb3762223ebdb69da085ac1e43e15996e458f3613d0f11d8c387b2eaeb4302aeeb00d291612bb0c00"); + // clang-format on std::vector secret_key = webcpp::test::from_hex("77076d0a7318a57d3c16c17251b26645df4c2f87ebc0992ab177fba51db92c2a"); std::vector peer_key = diff --git a/test/messages/Jamfile b/test/messages/Jamfile index 6c0de297..a55aa77f 100644 --- a/test/messages/Jamfile +++ b/test/messages/Jamfile @@ -30,6 +30,8 @@ build-project ed25519ph_sha256 ; build-project ed25519_default_not_linked ; build-project heavy_without_threads ; build-project async_seal_xchacha ; +build-project async_open_xchacha ; +build-project async_make_xchacha ; build-project async_sign_secp256k1 ; build-project heavy_without_threads_first ; build-project chacha_default_not_linked ; diff --git a/test/messages/async_make_xchacha/Jamfile b/test/messages/async_make_xchacha/Jamfile new file mode 100644 index 00000000..8be7589a --- /dev/null +++ b/test/messages/async_make_xchacha/Jamfile @@ -0,0 +1,14 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/crypto//crypto ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +webcpp.compile-diagnostic async_make_xchacha : async_make_xchacha.cpp + : /webcpp/asio//asio /third_party//sodium : native wasip2 wasip3 : alone ; diff --git a/test/messages/async_make_xchacha/async_make_xchacha.cpp b/test/messages/async_make_xchacha/async_make_xchacha.cpp new file mode 100644 index 00000000..8061eb27 --- /dev/null +++ b/test/messages/async_make_xchacha/async_make_xchacha.cpp @@ -0,0 +1,42 @@ +// 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) + +// async_make on an AEAD WebCrypto lacks, XChaCha20-Poly1305, stops with the synchronous call to +// make instead, and with that error alone, while the AEAD's own seal compiles. + +// clang-format off +// expected-error@webcpp/crypto/async.hpp:* {{webcpp::crypto: async_make takes AES-GCM or a key pair of an algorithm WebCrypto has (Ed25519, P-256): call the synchronous make for the others.}} +// clang-format on +#include +#include + +#include + +#include +#include + +#include +#include + +int main() { + namespace crypto = webcpp::crypto; + std::array const key{}; + auto made = crypto::ciphers::xchacha20_poly1305<>::make(key); + if (!made) { + return 1; + } + std::array const iv{}; + std::array data{}; + // The synchronous seal compiles. + if (!made->seal(iv, {}, data)) { + return 1; + } + webcpp::asio::io_context context; + crypto::async_make>( + context.get_executor(), key, + [](boost::system::error_code, crypto::ciphers::xchacha20_poly1305<>) {}); + return 0; +} diff --git a/test/messages/async_open_xchacha/Jamfile b/test/messages/async_open_xchacha/Jamfile new file mode 100644 index 00000000..88133991 --- /dev/null +++ b/test/messages/async_open_xchacha/Jamfile @@ -0,0 +1,14 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/crypto//crypto ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +webcpp.compile-diagnostic async_open_xchacha : async_open_xchacha.cpp + : /webcpp/asio//asio /third_party//sodium : native wasip2 wasip3 : alone ; diff --git a/test/messages/async_open_xchacha/async_open_xchacha.cpp b/test/messages/async_open_xchacha/async_open_xchacha.cpp new file mode 100644 index 00000000..1388abe4 --- /dev/null +++ b/test/messages/async_open_xchacha/async_open_xchacha.cpp @@ -0,0 +1,42 @@ +// 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) + +// async_open on an AEAD WebCrypto lacks, XChaCha20-Poly1305, stops with the synchronous call to +// make instead, and with that error alone, while the AEAD's own seal compiles. + +// clang-format off +// expected-error@webcpp/crypto/async.hpp:* {{webcpp::crypto: async_open takes AES-GCM, the AEAD WebCrypto has: call open for the others.}} +// clang-format on +#include +#include + +#include + +#include +#include + +#include +#include + +int main() { + namespace crypto = webcpp::crypto; + std::array const key{}; + auto made = crypto::ciphers::xchacha20_poly1305<>::make(key); + if (!made) { + return 1; + } + std::array const iv{}; + std::array data{}; + // The synchronous seal compiles. + if (!made->seal(iv, {}, data)) { + return 1; + } + webcpp::asio::io_context context; + std::array const tag{}; + crypto::async_open(context.get_executor(), *made, iv, {}, data, tag, + [](boost::system::error_code) {}); + return 0; +} diff --git a/test/messages/async_sign_secp256k1/async_sign_secp256k1.cpp b/test/messages/async_sign_secp256k1/async_sign_secp256k1.cpp index ab9d9182..9f329ad9 100644 --- a/test/messages/async_sign_secp256k1/async_sign_secp256k1.cpp +++ b/test/messages/async_sign_secp256k1/async_sign_secp256k1.cpp @@ -9,7 +9,7 @@ // compiles. // clang-format off -// expected-error@webcpp/crypto/async.hpp:* {{webcpp::crypto: async_sign takes a key pair of an algorithm WebCrypto has (Ed25519, P-256): call the key pair's sign for the others.}} +// expected-error@webcpp/crypto/async.hpp:* {{webcpp::crypto: async_sign takes a key pair of an algorithm WebCrypto has (Ed25519, P-256): call the key pair's synchronous signing function for the others.}} // clang-format on #include #include diff --git a/test/msvc/Jamfile b/test/msvc/Jamfile index cf350848..ded9b636 100644 --- a/test/msvc/Jamfile +++ b/test/msvc/Jamfile @@ -49,6 +49,8 @@ build-project ed25519ph_sha256 ; build-project ed25519_default_not_linked ; build-project heavy_without_threads ; build-project async_seal_xchacha ; +build-project async_open_xchacha ; +build-project async_make_xchacha ; build-project async_sign_secp256k1 ; build-project chacha_default_not_linked ; build-project aead_not_a_family ; diff --git a/test/msvc/async_make_xchacha/Jamfile b/test/msvc/async_make_xchacha/Jamfile new file mode 100644 index 00000000..757c929b --- /dev/null +++ b/test/msvc/async_make_xchacha/Jamfile @@ -0,0 +1,11 @@ +# 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) + +import webcpp ; + +webcpp.compile-fail async_make_xchacha : app.cpp + : /webcpp/crypto//crypto /webcpp/asio//asio /third_party//sodium + : native ; diff --git a/test/msvc/async_make_xchacha/app.cpp b/test/msvc/async_make_xchacha/app.cpp new file mode 100644 index 00000000..3c7cb413 --- /dev/null +++ b/test/msvc/async_make_xchacha/app.cpp @@ -0,0 +1,34 @@ +// 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) + +// async_make on an AEAD WebCrypto lacks, XChaCha20-Poly1305, stops where it is called: on MSVC the +// compile fails. The text is checked on clang, in test/messages/async_make_xchacha. +#include +#include + +#include + +#include +#include + +#include +#include + +int main() { + namespace crypto = webcpp::crypto; + std::array const key{}; + auto made = crypto::ciphers::xchacha20_poly1305<>::make(key); + if (!made) { + return 1; + } + std::array const iv{}; + std::array data{}; + webcpp::asio::io_context context; + crypto::async_make>( + context.get_executor(), key, + [](boost::system::error_code, crypto::ciphers::xchacha20_poly1305<>) {}); + return 0; +} diff --git a/test/msvc/async_open_xchacha/Jamfile b/test/msvc/async_open_xchacha/Jamfile new file mode 100644 index 00000000..a2848d3b --- /dev/null +++ b/test/msvc/async_open_xchacha/Jamfile @@ -0,0 +1,11 @@ +# 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) + +import webcpp ; + +webcpp.compile-fail async_open_xchacha : app.cpp + : /webcpp/crypto//crypto /webcpp/asio//asio /third_party//sodium + : native ; diff --git a/test/msvc/async_open_xchacha/app.cpp b/test/msvc/async_open_xchacha/app.cpp new file mode 100644 index 00000000..a0d1b46a --- /dev/null +++ b/test/msvc/async_open_xchacha/app.cpp @@ -0,0 +1,34 @@ +// 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) + +// async_open on an AEAD WebCrypto lacks, XChaCha20-Poly1305, stops where it is called: on MSVC the +// compile fails. The text is checked on clang, in test/messages/async_open_xchacha. +#include +#include + +#include + +#include +#include + +#include +#include + +int main() { + namespace crypto = webcpp::crypto; + std::array const key{}; + auto made = crypto::ciphers::xchacha20_poly1305<>::make(key); + if (!made) { + return 1; + } + std::array const iv{}; + std::array data{}; + webcpp::asio::io_context context; + std::array const tag{}; + crypto::async_open(context.get_executor(), *made, iv, {}, data, tag, + [](boost::system::error_code) {}); + return 0; +} diff --git a/test/support/timing_coverage.hpp b/test/support/timing_coverage.hpp index 62d5eaa2..5a5636cd 100644 --- a/test/support/timing_coverage.hpp +++ b/test/support/timing_coverage.hpp @@ -325,12 +325,12 @@ void cover_gcm(std::string const& family, std::string const& backend) { } /** - * A completion handler of `cover_async_gcm` that counts its completions and, given a tag's - * address, keeps the tag. Not a lambda: a lambda in a template argument keeps + * A completion handler of the `cover_async_*` functions that counts its completions and, given a + * tag's address, keeps the tag. Not a lambda: a lambda in a template argument keeps * `names_function` from reading the guard's function (support/timing_seam.hpp). */ -template -struct async_gcm_completion { +template +struct async_completion_counter { /** Counts the completion. */ int* completions; /** Where a seal's tag is kept, or null. */ @@ -370,8 +370,8 @@ void cover_async_gcm(std::string const& family, std::string const& backend) { auto const key = coverage_key(); int completions = 0; typename Gcm::result_type kept{}; - async_gcm_completion const counted{&completions}; - async_gcm_completion const keeping{&completions, &kept}; + async_completion_counter const counted{&completions}; + async_completion_counter const keeping{&completions, &kept}; // Each call's completion is delivered before the next call. auto const deliver = [&context] { context.restart(); @@ -434,8 +434,8 @@ void cover_async_ed25519(std::string const& backend) { std::array const message{1, 2, 3}; int completions = 0; signature_type kept{}; - async_gcm_completion const counted{&completions}; - async_gcm_completion const keeping{&completions, &kept}; + async_completion_counter const counted{&completions}; + async_completion_counter const keeping{&completions, &kept}; // Each call's completion is delivered before the next call. auto const deliver = [&context] { context.restart(); @@ -507,7 +507,7 @@ void cover_async_x25519(std::string const& backend) { return; } int completions = 0; - async_gcm_completion> const counted{&completions}; + async_completion_counter<> const counted{&completions}; covered("x25519::async_agree" + on, "crypto::async_agree", [&] { crypto::async_agree(executor, alice, *bob, counted); context.restart(); From 27d53a5cff41de7f3a9ad80b7a99c2c9587bea27 Mon Sep 17 00:00:00 2001 From: R Date: Sat, 21 Nov 2026 22:43:11 -0300 Subject: [PATCH 07/14] crypto: the asynchronous family's page and examples --- doc/Jamfile | 6 +- doc/async.adoc | 255 ++++++++++++++++++++++++++++++ doc/changelog.adoc | 2 +- doc/crypto.adoc | 2 + doc/generated/backends-async.adoc | 30 ++++ doc/generated/matrix.adoc | 21 +++ doc/generated/messages.adoc | 40 +++++ doc/llms.txt | 10 ++ doc/tables/crypto.json | 19 +++ example/Jamfile | 9 ++ example/async_seal.cpp | 112 +++++++++++++ example/async_seal.expected | 3 + example/async_sign.cpp | 100 ++++++++++++ example/async_sign.expected | 4 + include/webcpp/crypto/async.hpp | 51 ++++-- 15 files changed, 645 insertions(+), 19 deletions(-) create mode 100644 doc/async.adoc create mode 100644 doc/generated/backends-async.adoc create mode 100644 example/async_seal.cpp create mode 100644 example/async_seal.expected create mode 100644 example/async_sign.cpp create mode 100644 example/async_sign.expected diff --git a/doc/Jamfile b/doc/Jamfile index ea9ae746..91e306bb 100644 --- a/doc/Jamfile +++ b/doc/Jamfile @@ -9,9 +9,11 @@ import webcpp ; webcpp.doc crypto : crypto.adoc ; # The reference reads the backend headers, which refuse a build that does not # link their library: it links every backend, OpenSSL natively the default -# whose header ciphers/aes256_gcm.hpp and ciphers/aes_block.hpp include. +# whose header ciphers/aes256_gcm.hpp and ciphers/aes_block.hpp include; and +# webcpp::asio's, for async.hpp. webcpp.reference crypto : /webcpp/crypto//openssl /third_party//bearssl - /third_party//ctaes /third_party//secp256k1 /third_party//sodium ; + /third_party//ctaes /third_party//secp256k1 /third_party//sodium + /webcpp/asio//asio ; # The generated tables and llms.txt are what doc/tables/generate.py writes # from doc/tables/crypto.json and the tests: the build fails when they are diff --git a/doc/async.adoc b/doc/async.adoc new file mode 100644 index 00000000..ecee6d8b --- /dev/null +++ b/doc/async.adoc @@ -0,0 +1,255 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +[#crypto-async] +== Asynchronous calls + +Many programs are built around an event loop: a server that answers thousands +of connections on a few threads, a browser page, a chat client that keeps its +window responsive. Such a program must never wait inside a handler, because +every other connection, every click and every animation waits with it. The +browser's cryptography library, WebCrypto (`crypto.subtle`, +https://www.w3.org/TR/WebCryptoAPI/[W3C]), answers every call with a promise +for that reason: it runs in the browser's native code, off the page's thread, +and the answer arrives later. A program written for it, and a program that +wants one shape for its code on every target, needs the same shape from the +library. + +`` gives the functions of crypto that WebCrypto has +an asynchronous form in webcpp::asio's model: each returns at once, and its +completion arrives later through the event loop, with a +`boost::system::error_code` and, for an operation that returns a value, the +value. Each takes any completion token: a callback, `use_awaitable` for +`co_await` in Asio, Cobalt's `use_op`, `deferred`, `as_tuple`, `use_future`. A +program names `/webcpp/asio//asio` in its Jamfile, besides the backend of what +it calls, and includes the header by itself: `` leaves it +out, so that a program without an event loop does not build webcpp::asio. + +Every function takes, first, the executor its completion is posted to, as +webcpp::hash's asynchronous functions do (the executor of an `io_context`, or +of a strand). Without it, Asio would post to the system executor, a thread of +its own, and the handler would run off the program's loop. + +.The asynchronous functions +[cols="2,3,3"] +|=== +| Algorithm | Functions | Completion + +| AES-GCM (<>) +| `async_make(executor, key, token)`, `async_seal(executor, aead, iv, additional_data, data, token)`, `async_open(executor, aead, iv, additional_data, data, tag, token)` +| `void(error_code, Gcm)` for `async_make`, `void(error_code, tag)` for `async_seal`, `void(error_code)` for `async_open` + +| Ed25519 (<>) +| `async_make(executor, seed, token)`, `async_generate(executor, token)`, `async_sign(executor, key_pair, message, token)`, `async_verify(executor, public_key, message, signature, token)` +| `void(error_code, Keypair)` for `async_make` and `async_generate`, `void(error_code, signature)` for `async_sign`, `void(error_code)` for `async_verify` + +| X25519 (<>) +| `async_agree(executor, secret_key, peer_public_key, token)` +| `void(error_code, secret<32>)` +|=== + +The other algorithms of crypto (the ChaCha20-Poly1305 AEADs, the secret boxes, +secp256k1) are not in WebCrypto, and have no asynchronous function: naming one +stops the build, with the message "call the synchronous function", whose text +and fix are in <>. Their synchronous functions are as cheap +as these, and are called inside a handler. + +include::generated/backends-async.adoc[] + +[#crypto-async-kinds] +=== The two kinds + +The functions come in two kinds: + +* *The cheap functions*, all of the table above, cost microseconds: they run +at once and complete through the event loop, never inside the call. They exist +on every target, so that a program written once builds and runs everywhere. +* *The heavy functions* run their work on another thread, on an executor the +program gives (the executor of a `webcpp::asio::thread_pool`), and complete on +the event loop. They exist only where the build has threads +(`WEBCPP_CRYPTO_HAS_THREADS`). No function of this version is heavy: the +operations that take long enough to freeze a loop (RSA key generation, for +one) are not in it, and each arrives with its own `async_` function, which +follows the rules of <>. + +Each runs, by default, on the synchronous function's backend: the default of +its family (<>), on every target, Emscripten +included. The browser's WebCrypto is a backend of its own, which a program +names in the type where it wants it (<>); it is never +a default, so that one program gives the same bytes on every target. + +[#crypto-async-cheap] +=== The cheap functions through the event loop + +A cheap function runs the synchronous call at once, its guards first, and posts +the completion to the executor the call gives, whence it reaches the handler's +associated executor. The completion never runs inside the call, so a handler +written for the browser's WebCrypto, which always completes later, behaves the +same on every target. An audit record sealed with AES-256-GCM and opened again, +each step started by the handler of the one before: + +[source] +---- +include::{examples}/async_seal.cpp[tag=program,indent=0] +---- + +[listing] +---- +include::{examples}/async_seal.expected[] +---- + +The same functions in a coroutine, which reads as the synchronous code does: +Ed25519's key pair made from a seed, a message signed and the signature +verified, each step a `co_await` with `use_awaitable`. The coroutine ends, and +the loop with it, when the last completion has run: + +[source] +---- +include::{examples}/async_sign.cpp[tag=program,indent=0] +---- + +[listing] +---- +include::{examples}/async_sign.expected[] +---- + +*The completion's value on an error.* A value that is a keyed object or a +secret has no meaning when the call failed, and the completion gives the +empty object a move leaves: a `gcm` or a key pair without a key, a `secret<32>` +or a signature of zeros, a tag of zeros. A program that reads the object by +mistake gets `invalid_state` from every member of a `gcm` or a key pair, and +zeros from a secret, never a key. Check the error code first. An operation +without a value, `async_open` and `async_verify`, completes with the code +alone. + +*What the guards say.* The completion's code is the synchronous function's, +unchanged: `invalid_key_size`, `invalid_iv_size`, `message_too_long`, +`authentication_failed`, `invalid_public_key`, `weak_public_key`, +`invalid_signature`, `entropy_unavailable`, `backend_failure` +(<>). A refusal is posted like a success, and the data a guard +refuses is untouched; a failed `async_seal` or `async_open` zeroes it, as +`seal` and `open` do. + +*Pitfalls.* + +* *The object and the spans are the caller's until the completion.* The +key, the IV, the additional data, the data, the message and the signature are +read and written by the call, which on a synchronous backend finishes before +it returns; the browser's backend reads them later. A program written +for either keeps them alive, and does not touch the data, until the handler +runs: the key pair and the message of a coroutine live in its frame, and the +record of the first example in `main`. An `aead` is not used by another call +meanwhile. The parameters that are values are copied. +* *The completion is later.* It never runs inside the call: code that follows +the call runs first. A handler that needs a value from the call's caller +captures it, as the examples do. +* *Bind the completion to the loop.* The completion is dispatched to the +handler's associated executor, else to the one the call was given; a handler +bound to another executor with `bind_executor` runs there, and code that +touches the loop's state from it races with it. +* *The storage is the handler's.* The post allocates with the handler's +associated allocator (`bind_allocator`), as every Asio operation does; a +program that counts or pools its allocations binds its own. webcpp's own code +calls neither `operator new` nor the C allocator in this family. +* *`use_future` without exceptions.* An error completes a future with an +exception; a program built without exceptions reads errors with a callback or +`as_tuple`. +* *A call that never completes destroys its handler.* An event loop destroyed +with the completion queued destroys the handler without calling it and gives +its storage back, as Asio does for any operation: a `use_future` future then +reports a broken promise. + +[#crypto-async-heavy] +=== The heavy functions on another thread + +A heavy function takes the work executor first, the executor of a +`webcpp::asio::thread_pool` the program keeps for the slow work, and +completes on the handler's associated executor: the program binds the +completion to its loop with `bind_executor`, so that the handler runs on the +loop's thread. It checks its guards on the caller's thread, as the synchronous +function does, and posts a refusal to the handler's executor without waiting +for the pool; then the work runs on a thread of the pool, the completion is +dispatched to the handler's associated executor, and the event loop, which has +work while the operation is pending, does not return from `run` early. The +machinery is the one of webcpp::hash's heavy functions +(link:{webcpp-libs}/hash/{webcpp-page}#hash-async-heavy[Asynchronous calls] +in its page), so that a program that uses both knows one set of rules. + +Where the build has threads, `WEBCPP_CRYPTO_HAS_THREADS` is defined: + +[cols="1,3"] +|=== +| Target | The heavy functions + +| Native +| Always: every native build has threads, b2's default `threading=single` +included. A program that must never start work on another thread defines +`WEBCPP_CRYPTO_NO_THREADS`. + +| Emscripten +| With `-pthread`, which b2's `threading=multi` adds: each thread of the pool +is a Web Worker. A page needs cross-origin isolation for workers to share +memory +(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer#security_requirements[MDN, +SharedArrayBuffer's security requirements]); under node they run as they +are. A program that blocks its main thread (`run`, `join`) links +`-sPTHREAD_POOL_SIZE=` so that the workers start before it blocks. + +| wasip2, wasip3 +| Never: wasip2 has no threads, and wasip3's threads are cooperative, so the +work would still block the loop. Call the synchronous function. +|=== + +Without threads each heavy name still exists, as a template whose call stops +the build with "webcpp::crypto: runs on another thread and needs a +build with threads (...). Without threads, call .", +so that a program never blocks its loop under an asynchronous name; the text +and its fix are in <>. + +*Cancellation of the heavy ones.* + +* A cancellation through the handler's slot before the work starts completes +at once with `operation_aborted`, whatever the type, even when every thread of +the pool is busy, and the work never runs. It completes on the handler's +executor: a handler not bound to the loop's completes on the pool, and so +waits for one of its threads. +* After the work starts, it is not interrupted. A `terminal` or `partial` +cancellation lets it run to its end, destroys its value (which wipes a +`secret` or a key pair) and completes with `operation_aborted`. A `total` +one is then ignored, since the value's destruction is a side effect already +under way. +* The signal is emitted on the handler's executor, as Asio's slots require: +bind the loop's executor with `bind_executor` and emit from the loop, never +from another thread. It must outlive the call until its handler is called or +destroyed, since the operation clears its slot then: declare the signal before +the `io_context` and the pool, which are then destroyed first. +* A pool destroyed with the work still queued, or an event loop destroyed with +the completion queued, destroys the handler without calling it, as above. + +*Pitfalls.* + +* *A pool sized for the costs.* Each heavy operation holds its memory on its +thread until it ends: a pool of n threads can hold n times the memory at once. +Size the pool to what the program may spend, not to the number of requests. +* *The storage is the handler's.* The operation's state and its completion +are allocated with the handler's associated allocator, and all of it is given +back before the handler runs, a cancellation's completion included; the pool +allocates the job it queues as Asio does, with the work executor's own +allocator when it has one. + +[#crypto-async-webcrypto] +=== The browser's WebCrypto + +This section is for a later version. A program built with Emscripten will +reach WebCrypto (`crypto.subtle`) as a backend named in the type of an +asynchronous function, `backends::browser`: nothing of it compiled into the +program, the key held by the browser, and a completion that arrives when the +browser's promise settles. The functions of this page are the shape it plugs +into: the same names, the same completions, the same errors, so that a program +written against them today runs on it unchanged where the browser has the +algorithm. In this version every asynchronous function runs on a synchronous +backend, on every target, Emscripten included; naming a backend that is not +built stops the build as it does for the synchronous functions. diff --git a/doc/changelog.adoc b/doc/changelog.adoc index e6ce2c4c..1d3c7ca7 100644 --- a/doc/changelog.adoc +++ b/doc/changelog.adoc @@ -16,7 +16,7 @@ of every version are on webcpp's index page. === Unreleased // tag::unreleased[] -* Added crypto, C-backed primitives setting DIT on arm64 macOS, iOS, Linux and Android: ciphers, curves, randomness, fixed-value webcpp.crypto errors, `+[[nodiscard]]+` results, WEBCPP_CRYPTO_HAS_THREADS natively and with Emscripten's -pthread unless WEBCPP_CRYPTO_NO_THREADS is. +* Added crypto, C-backed primitives setting DIT on arm64 macOS, iOS, Linux and Android: ciphers, curves, randomness, fixed-value webcpp.crypto errors, `+[[nodiscard]]+` results, WEBCPP_CRYPTO_HAS_THREADS natively and with Emscripten's -pthread unless WEBCPP_CRYPTO_NO_THREADS is, and async_make, async_seal, async_open, async_generate, async_sign, async_verify and async_agree completing through an Asio event loop. * Added equal, random_device, pem on libsodium, the AES block cipher ciphers::aes128, aes192 and aes256 with a per-target default, and ciphers::gcm, aes128_gcm and aes256_gcm: incremental seal, two-pass open, failures zeroing data. * Added supports_v with its family tags, the capability table per target, default_backend_t and /webcpp/crypto//-default per family and target (secp256k1's modules among them), and refusals naming their Jamfile line. * Added backends::bearssl (AES-GCM alone, allocating nothing), backends::openssl via /webcpp/crypto//openssl natively and on WASI (allocating at make only, or natively in openssl_memory_resource with WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE), and backends::ctaes (block cipher alone). diff --git a/doc/crypto.adoc b/doc/crypto.adoc index a3dc4cdb..f4950e65 100644 --- a/doc/crypto.adoc +++ b/doc/crypto.adoc @@ -66,6 +66,8 @@ include::formats.adoc[] include::hybrid.adoc[] +include::async.adoc[] + include::choosing_backend.adoc[] include::backends.adoc[] diff --git a/doc/generated/backends-async.adoc b/doc/generated/backends-async.adoc new file mode 100644 index 00000000..7ac656e2 --- /dev/null +++ b/doc/generated/backends-async.adoc @@ -0,0 +1,30 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// Generated by doc/tables/generate.py from doc/tables/crypto.json, the test Jamfiles, +// the message tests and the Jamfile fixtures: run it again, never edit this file. + +The backends of `+async_make+`, `+async_seal+`, `+async_open+`, `+async_generate+`, `+async_sign+`, `+async_verify+`, `+async_agree+`, from the test programs that run it: + +[cols="1,2,2,4",options="header"] +|=== +|Backend |Jamfile |Header |Targets + +|BearSSL +|`+/third_party//bearssl+` +|`++` +|native, wasip2, wasip3, emscripten (tested by `+async_gcm+`) + +|OpenSSL +|`+/webcpp/crypto//openssl+` +|`++` +|native, wasip2, wasip3 (tested by `+async_gcm_openssl+`); not on emscripten: `+/webcpp/crypto//openssl+` stops the build there + +|libsodium +|`+/third_party//sodium+` +|`++` +|native, wasip2, wasip3, emscripten (tested by `+async_25519+`, `+async_post+`) +|=== diff --git a/doc/generated/matrix.adoc b/doc/generated/matrix.adoc index 69b27ca6..23492c09 100644 --- a/doc/generated/matrix.adoc +++ b/doc/generated/matrix.adoc @@ -16,6 +16,21 @@ |native, wasip2, wasip3, emscripten |`+random_device+` +|`+async_make+`, `+async_seal+`, `+async_open+`, `+async_generate+`, `+async_sign+`, `+async_verify+`, `+async_agree+` +|BearSSL +|native, wasip2, wasip3, emscripten +|`+async_gcm+` + +|`+async_make+`, `+async_seal+`, `+async_open+`, `+async_generate+`, `+async_sign+`, `+async_verify+`, `+async_agree+` +|OpenSSL +|native, wasip2, wasip3; not on emscripten: `+/webcpp/crypto//openssl+` stops the build there +|`+async_gcm_openssl+` + +|`+async_make+`, `+async_seal+`, `+async_open+`, `+async_generate+`, `+async_sign+`, `+async_verify+`, `+async_agree+` +|libsodium +|native, wasip2, wasip3, emscripten +|`+async_25519+`, `+async_post+` + |`+equal+` |no backend |native, wasip2, wasip3, emscripten @@ -239,6 +254,12 @@ The same, by target: the backends each operation runs on. |the system's generator |the system's generator +|`+async_make+`, `+async_seal+`, `+async_open+`, `+async_generate+`, `+async_sign+`, `+async_verify+`, `+async_agree+` +|BearSSL, OpenSSL, libsodium +|BearSSL, OpenSSL, libsodium +|BearSSL, OpenSSL, libsodium +|BearSSL, libsodium + |`+equal+` |no backend |no backend diff --git a/doc/generated/messages.adoc b/doc/generated/messages.adoc index 6b5fad8f..2fa7aaae 100644 --- a/doc/generated/messages.adoc +++ b/doc/generated/messages.adoc @@ -37,6 +37,30 @@ The fix: On WASI the block cipher's default is ctaes: add `+/webcpp/crypto//aes_ The fix: Name `+ciphers::aes256+`, include `++` and add `+/third_party//ctaes+`. +|`+async_make_xchacha+` +|native, wasip2, wasip3 +|`+webcpp::crypto: async_make takes AES-GCM or a key pair of an algorithm WebCrypto has (Ed25519, P-256): call the synchronous make for the others.+` + +The fix: Call the synchronous `+make+`: XChaCha20-Poly1305 is not in WebCrypto, so it has no asynchronous form. + +|`+async_open_xchacha+` +|native, wasip2, wasip3 +|`+webcpp::crypto: async_open takes AES-GCM, the AEAD WebCrypto has: call open for the others.+` + +The fix: Call the AEAD's own `+open+`: only AES-GCM has `+async_open+`. + +|`+async_seal_xchacha+` +|native, wasip2, wasip3 +|`+webcpp::crypto: async_seal takes AES-GCM, the AEAD WebCrypto has: call seal for the others.+` + +The fix: Call the AEAD's own `+seal+`: only AES-GCM has `+async_seal+`. + +|`+async_sign_secp256k1+` +|native, wasip2, wasip3 +|`+webcpp::crypto: async_sign takes a key pair of an algorithm WebCrypto has (Ed25519, P-256): call the key pair's synchronous signing function for the others.+` + +The fix: Call the key pair's own signing function: secp256k1 is not in WebCrypto, so only Ed25519's key pair has `+async_sign+`. + |`+bearssl_not_linked+` |native, wasip2 |`+webcpp::crypto: the backend BearSSL is used and not linked. In the program's Jamfile, add /third_party//bearssl beside /webcpp/crypto//crypto. (without b2: define WEBCPP_CRYPTO_HAS_BEARSSL=1 and link BearSSL built with webcpp's src/canary_bearssl.c)+` @@ -888,6 +912,22 @@ On MSVC, each case of `test/msvc` is proven to stop the build, at compile or at |the compile |Name `+ciphers::aes256+`, include `++` and add `+/third_party//ctaes+`. +|`+async_make_xchacha+` +|the compile +|Call the synchronous `+make+`: XChaCha20-Poly1305 is not in WebCrypto, so it has no asynchronous form. + +|`+async_open_xchacha+` +|the compile +|Call the AEAD's own `+open+`: only AES-GCM has `+async_open+`. + +|`+async_seal_xchacha+` +|the compile +|Call the AEAD's own `+seal+`: only AES-GCM has `+async_seal+`. + +|`+async_sign_secp256k1+` +|the compile +|Call the key pair's own signing function: secp256k1 is not in WebCrypto, so only Ed25519's key pair has `+async_sign+`. + |`+bearssl_not_linked+` |the compile |Add `+/third_party//bearssl+`. diff --git a/doc/llms.txt b/doc/llms.txt index f222a428..c6f49698 100644 --- a/doc/llms.txt +++ b/doc/llms.txt @@ -12,6 +12,14 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - min: The smallest value `operator()` gives. - max: The largest value `operator()` gives. - entropy: The entropy of a value, in bits: every bit is the system's. +- [async_make, async_seal, async_open, async_generate, async_sign, async_verify, async_agree](https://webcpporg.github.io/libs/crypto/#crypto-async): The asynchronous family: AES-GCM's make, seal and open, Ed25519's generate, make, sign and verify, and X25519's agree, each completing through a post to the executor the call gives, with any Asio completion token. Header . Backends: BearSSL (/third_party//bearssl) on native, wasip2, wasip3, emscripten; OpenSSL (/webcpp/crypto//openssl) on native, wasip2, wasip3; libsodium (/third_party//sodium) on native, wasip2, wasip3, emscripten. + - async_make: Makes an AES-GCM object or an Ed25519 key pair from its key bytes, asynchronously: `Algorithm::make(key_bytes)` run when the operation is initiated, its result posted to `executor` (design D23). + - async_seal: Seals a message in place, asynchronously: `aead.seal` run when the operation is initiated, its result posted to `executor`. + - async_open: Opens a message in place, asynchronously: `aead.open` run when the operation is initiated, its result posted to `executor`. + - async_generate: Makes an Ed25519 key pair from a fresh seed, asynchronously: `Keypair::generate()` run when the operation is initiated (the system's generator is drawn from then), its result posted to `executor`. + - async_sign: Signs a message with an Ed25519 key pair, asynchronously: `key_pair.sign(message)` run when the operation is initiated, its result posted to `executor`. + - async_verify: Verifies an Ed25519 signature, asynchronously: `curves::ed25519::verify` run when the operation is initiated, its result posted to `executor`. + - async_agree: Agrees an X25519 shared secret, asynchronously: `curves::x25519::agree` run when the operation is initiated, its result posted to `executor`. - [equal](https://webcpporg.github.io/libs/crypto/#crypto-equal): Compares two tags or MACs in constant time. Header . Backends: no backend (/webcpp/crypto//crypto) on native, wasip2, wasip3, emscripten. Use it to: check a webhook's or an API's HMAC signature. - equal: Whether two byte sequences are equal, in a time that does not depend on their contents. - [error](https://webcpporg.github.io/libs/crypto/#crypto-errors): Every failure's value, fixed and never reused, in the category webcpp.crypto. Header . Backends: no backend (/webcpp/crypto//crypto) on native, wasip2, wasip3, emscripten. Use it to: tell a forged message from a malformed one. @@ -293,6 +301,8 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - example/aes256_gcm_bearssl.cpp: Seals one zero block with AES-256-GCM on BearSSL, names the backend in the type, checks the result against test case 14 of the GCM specification, and opens it again. Naming the backend pins the implementation, so the same bytes and the same code run on every target. - example/arena_signer.cpp: Gives the secp256k1 key pair its one allocation from a fixed buffer owned by the program, and counts it. With a null upstream nothing else can allocate, so a program with strict memory limits knows exactly what the library needs and that it never reaches for the heap. +- example/async_seal.cpp: An audit record sealed and opened through an event loop: the GCM specification's test case 16 (AES-256, 12-byte IV, additional data), a published key, never a real one. Each completion runs from the loop's run, after the call that started it has returned, on every target; the handler of the seal prints the tag and starts the open, the handler of the open compares the plaintext. The loop ends when no operation is pending: nothing waits for a time. +- example/async_sign.cpp: A coroutine on an event loop makes an Ed25519 key pair from RFC 8032's second test seed (a published seed, never a real key), signs the test's message, and verifies the signature with the public key alone, each step a co_await of an asynchronous function with use_awaitable. The coroutine ends, and the loop with it, when the last completion has run: nothing waits for a time. - example/bearssl_prng.cpp: Seeds BearSSL's own HMAC-DRBG from webcpp::crypto::random_device and draws bytes from it. A generator is only as good as its seed: the seed must come from the system's entropy, never from the clock or a counter. - example/box_messages.cpp: Two people who know each other's X25519 public keys exchange messages in libsodium's box: each makes a box from the own secret key and the other's public key, agreeing one key for the pair, then seals each message with a nonce drawn at random. What one seals the other opens; a stranger's box, from another key pair, does not. Prints what each reads. - example/ecdh_session.cpp: Two peers agree on a shared secret with ECDH, derive a session key from it with HKDF-SHA-256 and talk over AES-256-GCM. The raw ECDH output is not a key: HKDF turns it into one and ties it to this application with a context string. diff --git a/doc/tables/crypto.json b/doc/tables/crypto.json index 25324683..37359d89 100644 --- a/doc/tables/crypto.json +++ b/doc/tables/crypto.json @@ -228,6 +228,21 @@ "section": "crypto-entropy", "backends": {"system": {"tests": ["random_device"]}} }, + { + "id": "async", + "free": true, + "functions": ["async_make", "async_seal", "async_open", "async_generate", "async_sign", "async_verify", "async_agree"], + "namespace": "root", + "api": "async_make, async_seal, async_open, async_generate, async_sign, async_verify, async_agree", + "header": "", + "what": "The asynchronous family: AES-GCM's make, seal and open, Ed25519's generate, make, sign and verify, and X25519's agree, each completing through a post to the executor the call gives, with any Asio completion token.", + "section": "crypto-async", + "backends": { + "bearssl": {"tests": ["async_gcm"]}, + "openssl": {"tests": ["async_gcm_openssl"]}, + "sodium": {"tests": ["async_25519", "async_post"]} + } + }, { "id": "equal", "functions": ["equal"], @@ -1216,6 +1231,10 @@ "ed25519_default_not_linked_on_emscripten": "As `ed25519_default_not_linked`.", "heavy_without_threads": "Call the synchronous operation the message names, or build with threads: natively without `WEBCPP_CRYPTO_NO_THREADS`, on Emscripten with `-pthread`; WASI has none.", "heavy_without_threads_first": "As `heavy_without_threads`.", + "async_make_xchacha": "Call the synchronous `make`: XChaCha20-Poly1305 is not in WebCrypto, so it has no asynchronous form.", + "async_seal_xchacha": "Call the AEAD's own `seal`: only AES-GCM has `async_seal`.", + "async_open_xchacha": "Call the AEAD's own `open`: only AES-GCM has `async_open`.", + "async_sign_secp256k1": "Call the key pair's own signing function: secp256k1 is not in WebCrypto, so only Ed25519's key pair has `async_sign`.", "heavy_without_threads_on_emscripten": "As `heavy_without_threads`: on Emscripten, add `multi`.", "chacha_on_ctaes_on_emscripten": "As `chacha_on_ctaes`.", "aead_not_a_family_on_emscripten": "As `aead_not_a_family`.", diff --git a/example/Jamfile b/example/Jamfile index 4cf6c178..4458bf90 100644 --- a/example/Jamfile +++ b/example/Jamfile @@ -152,3 +152,12 @@ webcpp.example file_share.cpp webcpp.example box_messages.cpp : /webcpp/crypto//box_xsalsa20poly1305-default /webcpp/crypto//x25519-default ; + +# The asynchronous family over webcpp::asio's event loop: an audit record +# sealed and opened by callbacks on AES-256-GCM's default, then an Ed25519 +# signature made and verified in a coroutine with use_awaitable, on the +# defaults; each completion arrives from the loop's run, on every target. +webcpp.example async_seal.cpp : /webcpp/asio//asio + /webcpp/crypto//gcm-default ; +webcpp.example async_sign.cpp : /webcpp/asio//asio + /webcpp/crypto//ed25519-default ; diff --git a/example/async_seal.cpp b/example/async_seal.cpp new file mode 100644 index 00000000..0bcdc072 --- /dev/null +++ b/example/async_seal.cpp @@ -0,0 +1,112 @@ +// 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) + +// An audit record sealed and opened through an event loop: the GCM specification's test case 16 +// (AES-256, 12-byte IV, additional data), a published key, never a real one. Each completion runs +// from the loop's run, after the call that started it has returned, on every target; the handler +// of the seal prints the tag and starts the open, the handler of the open compares the plaintext. +// The loop ends when no operation is pending: nothing waits for a time. +// tag::program[] +#include +#include + +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace asio = webcpp::asio; +namespace crypto = webcpp::crypto; +using aead_type = crypto::ciphers::aes256_gcm; + +namespace { + +// The bytes a string of hex digits writes, two per byte. +std::vector bytes_of(std::string_view hex) { + auto const digit = [](char c) { + return static_cast(c <= '9' ? c - '0' : c - 'a' + 10); + }; + std::vector bytes(hex.size() / 2); + for (std::size_t i = 0; i < bytes.size(); ++i) { + bytes[i] = static_cast((digit(hex[2 * i]) << 4U) | digit(hex[(2 * i) + 1])); + } + return bytes; +} + +void print(char const* name, std::span bytes) { + std::printf("%s ", name); + for (std::uint8_t const byte : bytes) { + std::printf("%02x", byte); + } + std::printf("\n"); +} + +} // namespace + +int main() { + auto const key = bytes_of("feffe9928665731c6d6a8f9467308308feffe9928665731c6d6a8f9467308308"); + auto const iv = bytes_of("cafebabefacedbaddecaf888"); + auto const additional_data = bytes_of("feedfacedeadbeeffeedfacedeadbeefabaddad2"); + auto const record = bytes_of( + "d9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a721c3c0c95956809532fcf0e2449" + "a6b525b16aedf5aa0de657ba637b39"); + + asio::io_context loop; + // What a call reads and writes is the program's until the completion: the key, the IV, the + // additional data and the record outlive the loop's run. The record is sealed in place. + std::vector data = record; + std::optional aead; + bool returned = false; + int status = 1; + + crypto::async_make( + loop.get_executor(), key, [&](boost::system::error_code made, aead_type keyed) { + if (made) { + std::printf("make: %s\n", made.message().c_str()); + return; + } + aead.emplace(std::move(keyed)); + std::printf("made after the call returned: %s\n", returned ? "yes" : "no"); + crypto::async_seal( + loop.get_executor(), *aead, iv, additional_data, data, + [&](boost::system::error_code sealed, aead_type::result_type digest) { + if (sealed) { + std::printf("seal: %s\n", sealed.message().c_str()); + return; + } + std::array tag{}; + std::ranges::copy(digest, tag.begin()); + print("tag", tag); + // The ciphertext replaced the record, and the tag opens it back. + crypto::async_open(loop.get_executor(), *aead, iv, additional_data, data, tag, + [&](boost::system::error_code opened) { + if (opened) { + std::printf("open: %s\n", opened.message().c_str()); + return; + } + bool const same = std::ranges::equal(data, record); + std::printf("opened, the record is back: %s\n", + same ? "yes" : "no"); + status = same ? 0 : 1; + }); + }); + }); + returned = true; + loop.run(); // lint-run: the program's event loop + return status; +} + +// end::program[] diff --git a/example/async_seal.expected b/example/async_seal.expected new file mode 100644 index 00000000..bac8e274 --- /dev/null +++ b/example/async_seal.expected @@ -0,0 +1,3 @@ +made after the call returned: yes +tag 76fc6ece0f4e1768cddf8853bb2d551b +opened, the record is back: yes diff --git a/example/async_sign.cpp b/example/async_sign.cpp new file mode 100644 index 00000000..7e680589 --- /dev/null +++ b/example/async_sign.cpp @@ -0,0 +1,100 @@ +// 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 coroutine on an event loop makes an Ed25519 key pair from RFC 8032's second test seed (a +// published seed, never a real key), signs the test's message, and verifies the signature with +// the public key alone, each step a co_await of an asynchronous function with use_awaitable. The +// coroutine ends, and the loop with it, when the last completion has run: nothing waits for a +// time. +// tag::program[] +#include +#include + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace asio = webcpp::asio; +namespace crypto = webcpp::crypto; +namespace ed25519 = webcpp::crypto::curves::ed25519; + +namespace { + +// Prints bytes in hex after a name, 32 bytes (64 digits) to a line, the lines after the first +// indented under the first. +void print(char const* name, std::span bytes) { + int const indent = std::printf("%s ", name); + for (std::size_t i = 0; i < bytes.size(); ++i) { + if (i != 0 && i % 32 == 0) { + std::printf("\n%*s", indent, ""); + } + std::printf("%02x", bytes[i]); + } + std::printf("\n"); +} + +// Each co_await completes through the loop; the key pair and the message are the coroutine's own, +// alive until it ends, as the functions ask. +asio::awaitable sign_and_verify() { + // RFC 8032 section 7.1, TEST 2: a published seed, never a real key. + std::array const seed{ + 0x4c, 0xcd, 0x08, 0x9b, 0x28, 0xff, 0x96, 0xda, 0x9d, 0xb6, 0xc3, + 0x46, 0xec, 0x11, 0x4e, 0x0f, 0x5b, 0x8a, 0x31, 0x9f, 0x35, 0xab, + 0xa6, 0x24, 0xda, 0x8c, 0xf6, 0xed, 0x4f, 0xb8, 0xa6, 0xfb, + }; + std::array const message{0x72}; + auto const executor = co_await asio::this_coro::executor; + auto const use = asio::as_tuple(asio::use_awaitable); + + auto [made, key] = co_await crypto::async_make(executor, seed, use); + if (made) { + std::printf("make: %s\n", made.message().c_str()); + co_return false; + } + auto const public_key = key.public_key(); + if (!public_key) { + co_return false; + } + auto [signed_code, signature] = co_await crypto::async_sign(executor, key, message, use); + if (signed_code) { + std::printf("sign: %s\n", signed_code.message().c_str()); + co_return false; + } + print("public key", *public_key); + print("signature ", signature); + // The verifier holds the public key, the message and the signature; nothing secret. + auto [verified] = co_await crypto::async_verify(executor, *public_key, message, signature, use); + if (verified) { + std::printf("verify: %s\n", verified.message().c_str()); + co_return false; + } + co_return true; +} + +} // namespace + +int main() { + asio::io_context loop; + bool ok = false; + asio::co_spawn(loop, sign_and_verify(), [&](std::exception_ptr const& failure, bool result) { + ok = !failure && result; + }); + loop.run(); // lint-run: the program's event loop + std::printf(ok ? "verified\n" : "failed\n"); + return ok ? 0 : 1; +} + +// end::program[] diff --git a/example/async_sign.expected b/example/async_sign.expected new file mode 100644 index 00000000..1afc27fd --- /dev/null +++ b/example/async_sign.expected @@ -0,0 +1,4 @@ +public key 3d4017c3e843895a92b70aa74d1b7ebc9c982ccf2ec4968cc0cd55f12af4660c +signature 92a009a9f0d4cab8720e820b5f642540a2b27b5416503f8fb3762223ebdb69da + 085ac1e43e15996e458f3613d0f11d8c387b2eaeb4302aeeb00d291612bb0c00 +verified diff --git a/include/webcpp/crypto/async.hpp b/include/webcpp/crypto/async.hpp index e84ae0fa..c3b7434d 100644 --- a/include/webcpp/crypto/async.hpp +++ b/include/webcpp/crypto/async.hpp @@ -97,8 +97,9 @@ namespace webcpp::crypto { /** * The backend of the asynchronous family when a call names none (ruling R-A4): the synchronous - * function's, `default_backend_t`, on every target, Emscripten included. The browser's - * backend is never a default: a program names it in the type to reach WebCrypto. + * function's, `default_backend_t`, on every target, Emscripten included. + * + * The browser's backend is never a default: a program names it in the type to reach WebCrypto. * * @tparam Family A family tag of `families` that has a default. */ @@ -224,12 +225,16 @@ inline constexpr bool refused_v = false; /** * Makes an AES-GCM object or an Ed25519 key pair from its key bytes, asynchronously: * `Algorithm::make(key_bytes)` run when the operation is initiated, its result posted to - * `executor` (design D23). The key is read before the call returns on a synchronous backend, + * `executor` (design D23). + * + * The key is read before the call returns on a synchronous backend, * later on the browser's: it is the caller's until the completion. * * @tparam Algorithm A `ciphers::gcm` or a `curves::ed25519::basic_keypair`, on * any backend that has it; the other algorithms crypto has are not in WebCrypto: call their * `make`. + * @tparam Executor The executor's type, an Asio executor (an `io_context`'s or a strand's). + * @tparam CompletionToken Any completion token for the signature `token` states. * @param executor The executor the completion is posted to. * @param key_bytes `Algorithm::key_size` bytes for AES-GCM, the seed's `seed_size` for a key pair. * @param token The completion token, of signature `void(boost::system::error_code, Algorithm)`; @@ -264,6 +269,8 @@ auto async_make(Executor const& executor, std::span key_byte * * @tparam Keypair A `curves::ed25519::basic_keypair`, by default the family's * `curves::ed25519::keypair`; the other key pairs are not in WebCrypto: call their `generate`. + * @tparam Executor The executor's type, an Asio executor (an `io_context`'s or a strand's). + * @tparam CompletionToken Any completion token for the signature `token` states. * @param executor The executor the completion is posted to. * @param token The completion token, of signature `void(boost::system::error_code, Keypair)`; * on an error the key pair is empty, and every member refuses with `invalid_state` @@ -290,8 +297,8 @@ auto async_generate(Executor const& executor, CompletionToken&& token) { } /** - * Seals a message in place, asynchronously: `aead.seal(iv_bytes, additional_data_bytes, - * data_bytes)` run when the operation is initiated, its result posted to `executor`. + * Seals a message in place, asynchronously: `aead.seal` run when the operation is initiated, its + * result posted to `executor`. * * `aead` and the spans are the caller's until the completion: a synchronous backend reads and * writes them before the call returns, the browser's later. `data_bytes` holds the ciphertext at @@ -299,6 +306,8 @@ auto async_generate(Executor const& executor, CompletionToken&& token) { * leaves it untouched, a backend's failure zeroes it, as `seal` does. * * @tparam Gcm A `ciphers::gcm`; the other AEADs are not in WebCrypto: call their `seal`. + * @tparam Executor The executor's type, an Asio executor (an `io_context`'s or a strand's). + * @tparam CompletionToken Any completion token for the signature `token` states. * @param executor The executor the completion is posted to. * @param aead The keyed object. * @param iv_bytes 1 to `max_iv_size` bytes, never reused under this key. @@ -333,14 +342,16 @@ auto async_seal(Executor const& executor, Gcm& aead, std::span`; the other AEADs are not in WebCrypto: call their `open`. + * @tparam Executor The executor's type, an Asio executor (an `io_context`'s or a strand's). + * @tparam CompletionToken Any completion token for the signature `token` states. * @param executor The executor the completion is posted to. * @param aead The keyed object. * @param iv_bytes The IV of the seal. @@ -378,17 +389,19 @@ auto async_open(Executor const& executor, Gcm& aead, std::span`; the other key pairs are not in * WebCrypto: call their `sign`. + * @tparam Executor The executor's type, an Asio executor (an `io_context`'s or a strand's). + * @tparam CompletionToken Any completion token for the signature `token` states. * @param executor The executor the completion is posted to. * @param key_pair The key pair. * @param message Any bytes. - * @param token The completion token, of signature `void(boost::system::error_code, - * std::array)`: the signature; on an error 64 zeros (`invalid_state`, - * `backend_failure`). + * @param token The completion token, of signature `void(error_code, signature)`, the signature + * a `std::array` of 64 bytes; on an error it is 64 zeros (`invalid_state`, `backend_failure`). * @return What the completion token's `async_result` gives. */ template @@ -415,11 +428,14 @@ auto async_sign(Executor const& executor, Keypair const& key_pair, /** * Verifies an Ed25519 signature, asynchronously: `curves::ed25519::verify` - * run when the operation is initiated, its result posted to `executor`. The spans are the - * caller's until the completion. + * run when the operation is initiated, its result posted to `executor`. + * + * The spans are the caller's until the completion. * * @tparam Policy The verification policy; `curves::ed25519::strict` is the only one declared. * @tparam Backend The backend; by default the asynchronous family's. + * @tparam Executor The executor's type, an Asio executor (an `io_context`'s or a strand's). + * @tparam CompletionToken Any completion token for the signature `token` states. * @param executor The executor the completion is posted to. * @param public_key 32 bytes. * @param message The signed bytes. @@ -448,10 +464,13 @@ auto async_verify(Executor const& executor, std::span public /** * Agrees an X25519 shared secret, asynchronously: `curves::x25519::agree` run when the - * operation is initiated, its result posted to `executor`. The spans are the caller's until the - * completion. + * operation is initiated, its result posted to `executor`. + * + * The spans are the caller's until the completion. * * @tparam Backend The backend; by default the asynchronous family's. + * @tparam Executor The executor's type, an Asio executor (an `io_context`'s or a strand's). + * @tparam CompletionToken Any completion token for the signature `token` states. * @param executor The executor the completion is posted to. * @param secret_key 32 bytes. * @param peer_public_key 32 bytes. From 3d567f52aea36337af579c19e95a951bb65535d9 Mon Sep 17 00:00:00 2001 From: R Date: Sat, 21 Nov 2026 22:45:35 -0300 Subject: [PATCH 08/14] crypto: the asynchronous family's tables list each backend's own functions, with use cases, and the sign example reports a missing public key --- doc/async.adoc | 6 ++- doc/generated/backends-async_ed25519.adoc | 20 ++++++++++ ...nds-async.adoc => backends-async_gcm.adoc} | 7 +--- doc/generated/backends-async_x25519.adoc | 20 ++++++++++ doc/generated/matrix.adoc | 33 +++++++++++++---- doc/generated/use-cases.adoc | 16 ++++++++ doc/llms.txt | 9 ++++- doc/tables/crypto.json | 37 ++++++++++++++++--- example/async_sign.cpp | 1 + include/webcpp/crypto/async.hpp | 2 +- 10 files changed, 128 insertions(+), 23 deletions(-) create mode 100644 doc/generated/backends-async_ed25519.adoc rename doc/generated/{backends-async.adoc => backends-async_gcm.adoc} (76%) create mode 100644 doc/generated/backends-async_x25519.adoc diff --git a/doc/async.adoc b/doc/async.adoc index ecee6d8b..2be3ecff 100644 --- a/doc/async.adoc +++ b/doc/async.adoc @@ -57,7 +57,11 @@ stops the build, with the message "call the synchronous function", whose text and fix are in <>. Their synchronous functions are as cheap as these, and are called inside a handler. -include::generated/backends-async.adoc[] +include::generated/backends-async_gcm.adoc[] + +include::generated/backends-async_ed25519.adoc[] + +include::generated/backends-async_x25519.adoc[] [#crypto-async-kinds] === The two kinds diff --git a/doc/generated/backends-async_ed25519.adoc b/doc/generated/backends-async_ed25519.adoc new file mode 100644 index 00000000..0e9c9831 --- /dev/null +++ b/doc/generated/backends-async_ed25519.adoc @@ -0,0 +1,20 @@ +// 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) + +// Generated by doc/tables/generate.py from doc/tables/crypto.json, the test Jamfiles, +// the message tests and the Jamfile fixtures: run it again, never edit this file. + +The backends of `+async_make+`, `+async_generate+`, `+async_sign+`, `+async_verify+`, from the test programs that run it: + +[cols="1,2,2,4",options="header"] +|=== +|Backend |Jamfile |Header |Targets + +|libsodium +|`+/third_party//sodium+` +|`++` +|native, wasip2, wasip3, emscripten (tested by `+async_25519+`, `+async_post+`) +|=== diff --git a/doc/generated/backends-async.adoc b/doc/generated/backends-async_gcm.adoc similarity index 76% rename from doc/generated/backends-async.adoc rename to doc/generated/backends-async_gcm.adoc index 7ac656e2..c76e3122 100644 --- a/doc/generated/backends-async.adoc +++ b/doc/generated/backends-async_gcm.adoc @@ -7,7 +7,7 @@ // Generated by doc/tables/generate.py from doc/tables/crypto.json, the test Jamfiles, // the message tests and the Jamfile fixtures: run it again, never edit this file. -The backends of `+async_make+`, `+async_seal+`, `+async_open+`, `+async_generate+`, `+async_sign+`, `+async_verify+`, `+async_agree+`, from the test programs that run it: +The backends of `+async_make+`, `+async_seal+`, `+async_open+`, from the test programs that run it: [cols="1,2,2,4",options="header"] |=== @@ -22,9 +22,4 @@ The backends of `+async_make+`, `+async_seal+`, `+async_open+`, `+async_generate |`+/webcpp/crypto//openssl+` |`++` |native, wasip2, wasip3 (tested by `+async_gcm_openssl+`); not on emscripten: `+/webcpp/crypto//openssl+` stops the build there - -|libsodium -|`+/third_party//sodium+` -|`++` -|native, wasip2, wasip3, emscripten (tested by `+async_25519+`, `+async_post+`) |=== diff --git a/doc/generated/backends-async_x25519.adoc b/doc/generated/backends-async_x25519.adoc new file mode 100644 index 00000000..6dabaafc --- /dev/null +++ b/doc/generated/backends-async_x25519.adoc @@ -0,0 +1,20 @@ +// 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) + +// Generated by doc/tables/generate.py from doc/tables/crypto.json, the test Jamfiles, +// the message tests and the Jamfile fixtures: run it again, never edit this file. + +The backends of `+async_agree+`, from the test programs that run it: + +[cols="1,2,2,4",options="header"] +|=== +|Backend |Jamfile |Header |Targets + +|libsodium +|`+/third_party//sodium+` +|`++` +|native, wasip2, wasip3, emscripten (tested by `+async_25519+`) +|=== diff --git a/doc/generated/matrix.adoc b/doc/generated/matrix.adoc index 23492c09..be6d0e15 100644 --- a/doc/generated/matrix.adoc +++ b/doc/generated/matrix.adoc @@ -16,21 +16,26 @@ |native, wasip2, wasip3, emscripten |`+random_device+` -|`+async_make+`, `+async_seal+`, `+async_open+`, `+async_generate+`, `+async_sign+`, `+async_verify+`, `+async_agree+` +|`+async_make+`, `+async_seal+`, `+async_open+` |BearSSL |native, wasip2, wasip3, emscripten |`+async_gcm+` -|`+async_make+`, `+async_seal+`, `+async_open+`, `+async_generate+`, `+async_sign+`, `+async_verify+`, `+async_agree+` +|`+async_make+`, `+async_seal+`, `+async_open+` |OpenSSL |native, wasip2, wasip3; not on emscripten: `+/webcpp/crypto//openssl+` stops the build there |`+async_gcm_openssl+` -|`+async_make+`, `+async_seal+`, `+async_open+`, `+async_generate+`, `+async_sign+`, `+async_verify+`, `+async_agree+` +|`+async_make+`, `+async_generate+`, `+async_sign+`, `+async_verify+` |libsodium |native, wasip2, wasip3, emscripten |`+async_25519+`, `+async_post+` +|`+async_agree+` +|libsodium +|native, wasip2, wasip3, emscripten +|`+async_25519+` + |`+equal+` |no backend |native, wasip2, wasip3, emscripten @@ -254,11 +259,23 @@ The same, by target: the backends each operation runs on. |the system's generator |the system's generator -|`+async_make+`, `+async_seal+`, `+async_open+`, `+async_generate+`, `+async_sign+`, `+async_verify+`, `+async_agree+` -|BearSSL, OpenSSL, libsodium -|BearSSL, OpenSSL, libsodium -|BearSSL, OpenSSL, libsodium -|BearSSL, libsodium +|`+async_make+`, `+async_seal+`, `+async_open+` +|BearSSL, OpenSSL +|BearSSL, OpenSSL +|BearSSL, OpenSSL +|BearSSL + +|`+async_make+`, `+async_generate+`, `+async_sign+`, `+async_verify+` +|libsodium +|libsodium +|libsodium +|libsodium + +|`+async_agree+` +|libsodium +|libsodium +|libsodium +|libsodium |`+equal+` |no backend diff --git a/doc/generated/use-cases.adoc b/doc/generated/use-cases.adoc index 8a4c9ec1..f0ffe2b0 100644 --- a/doc/generated/use-cases.adoc +++ b/doc/generated/use-cases.adoc @@ -11,6 +11,22 @@ |=== |I need to |Use |Backend |Jamfile |Example +|Seal or open a record inside an event loop without waiting +|`+async_seal+`, `+async_open+` +|the default of AES-GCM +|`+/webcpp/crypto//crypto+` + +`+/webcpp/crypto//gcm-default+` + +`+/webcpp/asio//asio+` +|<> + +|Sign and verify with Ed25519 in a coroutine +|`+async_sign+`, `+async_verify+` +|the default of Ed25519 +|`+/webcpp/crypto//crypto+` + +`+/webcpp/crypto//ed25519-default+` + +`+/webcpp/asio//asio+` +|<> + |Generate a session token, a password-reset link or an API key |`+random_device::fill+` |the system's generator diff --git a/doc/llms.txt b/doc/llms.txt index c6f49698..a3d6ac84 100644 --- a/doc/llms.txt +++ b/doc/llms.txt @@ -12,13 +12,16 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - min: The smallest value `operator()` gives. - max: The largest value `operator()` gives. - entropy: The entropy of a value, in bits: every bit is the system's. -- [async_make, async_seal, async_open, async_generate, async_sign, async_verify, async_agree](https://webcpporg.github.io/libs/crypto/#crypto-async): The asynchronous family: AES-GCM's make, seal and open, Ed25519's generate, make, sign and verify, and X25519's agree, each completing through a post to the executor the call gives, with any Asio completion token. Header . Backends: BearSSL (/third_party//bearssl) on native, wasip2, wasip3, emscripten; OpenSSL (/webcpp/crypto//openssl) on native, wasip2, wasip3; libsodium (/third_party//sodium) on native, wasip2, wasip3, emscripten. - - async_make: Makes an AES-GCM object or an Ed25519 key pair from its key bytes, asynchronously: `Algorithm::make(key_bytes)` run when the operation is initiated, its result posted to `executor` (design D23). +- [async_make, async_seal, async_open](https://webcpporg.github.io/libs/crypto/#crypto-async): AES-GCM's asynchronous make, seal and open, each completing through a post to the executor the call gives, with any Asio completion token. Header . Backends: BearSSL (/third_party//bearssl) on native, wasip2, wasip3, emscripten; OpenSSL (/webcpp/crypto//openssl) on native, wasip2, wasip3. Use it to: seal or open a record inside an event loop without waiting. + - async_make: Makes an AES-GCM object or an Ed25519 key pair from its key bytes, asynchronously: `Algorithm::make(key_bytes)` run when the operation is initiated, its result posted to `executor`. - async_seal: Seals a message in place, asynchronously: `aead.seal` run when the operation is initiated, its result posted to `executor`. - async_open: Opens a message in place, asynchronously: `aead.open` run when the operation is initiated, its result posted to `executor`. +- [async_make, async_generate, async_sign, async_verify](https://webcpporg.github.io/libs/crypto/#crypto-async): Ed25519's asynchronous make, generate, sign and verify, each completing through a post to the executor the call gives, with any Asio completion token. Header . Backends: libsodium (/third_party//sodium) on native, wasip2, wasip3, emscripten. Use it to: sign and verify with Ed25519 in a coroutine. + - async_make: Makes an AES-GCM object or an Ed25519 key pair from its key bytes, asynchronously: `Algorithm::make(key_bytes)` run when the operation is initiated, its result posted to `executor`. - async_generate: Makes an Ed25519 key pair from a fresh seed, asynchronously: `Keypair::generate()` run when the operation is initiated (the system's generator is drawn from then), its result posted to `executor`. - async_sign: Signs a message with an Ed25519 key pair, asynchronously: `key_pair.sign(message)` run when the operation is initiated, its result posted to `executor`. - async_verify: Verifies an Ed25519 signature, asynchronously: `curves::ed25519::verify` run when the operation is initiated, its result posted to `executor`. +- [async_agree](https://webcpporg.github.io/libs/crypto/#crypto-async): X25519's asynchronous agree, completing through a post to the executor the call gives, with any Asio completion token. Header . Backends: libsodium (/third_party//sodium) on native, wasip2, wasip3, emscripten. - async_agree: Agrees an X25519 shared secret, asynchronously: `curves::x25519::agree` run when the operation is initiated, its result posted to `executor`. - [equal](https://webcpporg.github.io/libs/crypto/#crypto-equal): Compares two tags or MACs in constant time. Header . Backends: no backend (/webcpp/crypto//crypto) on native, wasip2, wasip3, emscripten. Use it to: check a webhook's or an API's HMAC signature. - equal: Whether two byte sequences are equal, in a time that does not depend on their contents. @@ -262,6 +265,8 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp ## Choose by use case +- [Seal or open a record inside an event loop without waiting](https://webcpporg.github.io/libs/crypto/#crypto-async): `async_seal`, `async_open` (webcpp::crypto); backend the default of AES-GCM; Jamfile /webcpp/crypto//crypto /webcpp/crypto//gcm-default /webcpp/asio//asio. Example: example/async_seal.cpp. +- [Sign and verify with Ed25519 in a coroutine](https://webcpporg.github.io/libs/crypto/#crypto-async): `async_sign`, `async_verify` (webcpp::crypto); backend the default of Ed25519; Jamfile /webcpp/crypto//crypto /webcpp/crypto//ed25519-default /webcpp/asio//asio. Example: example/async_sign.cpp. - [Generate a session token, a password-reset link or an API key](https://webcpporg.github.io/libs/crypto/#crypto-entropy): `random_device::fill` (webcpp::crypto); backend the system's generator; Jamfile /webcpp/crypto//crypto. Example: example/reset_token.cpp. - [Draw an unbiased number in a range, such as a six-digit code](https://webcpporg.github.io/libs/crypto/#crypto-entropy): `random_device` with `std::uniform_int_distribution` (webcpp::crypto); backend the system's generator; Jamfile /webcpp/crypto//crypto. Example: example/reset_token.cpp. - [Check a webhook's or an API's HMAC signature](https://webcpporg.github.io/libs/crypto/#crypto-equal): `equal`, with Boost.Hash2's `hmac` (webcpp::crypto); backend none; Jamfile /webcpp/crypto//crypto. Example: example/equal_hmac.cpp. diff --git a/doc/tables/crypto.json b/doc/tables/crypto.json index 37359d89..1fd9d617 100644 --- a/doc/tables/crypto.json +++ b/doc/tables/crypto.json @@ -229,20 +229,45 @@ "backends": {"system": {"tests": ["random_device"]}} }, { - "id": "async", + "id": "async_gcm", "free": true, - "functions": ["async_make", "async_seal", "async_open", "async_generate", "async_sign", "async_verify", "async_agree"], + "functions": ["async_make", "async_seal", "async_open"], "namespace": "root", - "api": "async_make, async_seal, async_open, async_generate, async_sign, async_verify, async_agree", + "api": "async_make, async_seal, async_open", "header": "", - "what": "The asynchronous family: AES-GCM's make, seal and open, Ed25519's generate, make, sign and verify, and X25519's agree, each completing through a post to the executor the call gives, with any Asio completion token.", + "what": "AES-GCM's asynchronous make, seal and open, each completing through a post to the executor the call gives, with any Asio completion token.", "section": "crypto-async", "backends": { "bearssl": {"tests": ["async_gcm"]}, - "openssl": {"tests": ["async_gcm_openssl"]}, + "openssl": {"tests": ["async_gcm_openssl"]} + } + }, + { + "id": "async_ed25519", + "free": true, + "functions": ["async_make", "async_generate", "async_sign", "async_verify"], + "namespace": "root", + "api": "async_make, async_generate, async_sign, async_verify", + "header": "", + "what": "Ed25519's asynchronous make, generate, sign and verify, each completing through a post to the executor the call gives, with any Asio completion token.", + "section": "crypto-async", + "backends": { "sodium": {"tests": ["async_25519", "async_post"]} } }, + { + "id": "async_x25519", + "free": true, + "functions": ["async_agree"], + "namespace": "root", + "api": "async_agree", + "header": "", + "what": "X25519's asynchronous agree, completing through a post to the executor the call gives, with any Asio completion token.", + "section": "crypto-async", + "backends": { + "sodium": {"tests": ["async_25519"]} + } + }, { "id": "equal", "functions": ["equal"], @@ -1070,6 +1095,8 @@ } }, "use_cases": [ + {"need": "Seal or open a record inside an event loop without waiting", "namespace": "webcpp::crypto", "api": "`async_seal`, `async_open`", "backend": "the default of AES-GCM", "jamfile": "/webcpp/crypto//crypto /webcpp/crypto//gcm-default /webcpp/asio//asio", "example": "async_seal", "section": "crypto-async"}, + {"need": "Sign and verify with Ed25519 in a coroutine", "namespace": "webcpp::crypto", "api": "`async_sign`, `async_verify`", "backend": "the default of Ed25519", "jamfile": "/webcpp/crypto//crypto /webcpp/crypto//ed25519-default /webcpp/asio//asio", "example": "async_sign", "section": "crypto-async"}, {"need": "Generate a session token, a password-reset link or an API key", "namespace": "webcpp::crypto", "api": "`random_device::fill`", "backend": "the system's generator", "jamfile": "/webcpp/crypto//crypto", "example": "reset_token", "section": "crypto-entropy"}, {"need": "Draw an unbiased number in a range, such as a six-digit code", "namespace": "webcpp::crypto", "api": "`random_device` with `std::uniform_int_distribution`", "backend": "the system's generator", "jamfile": "/webcpp/crypto//crypto", "example": "reset_token", "section": "crypto-entropy"}, {"need": "Check a webhook's or an API's HMAC signature", "namespace": "webcpp::crypto", "api": "`equal`, with Boost.Hash2's `hmac`", "backend": "none", "jamfile": "/webcpp/crypto//crypto", "example": "equal_hmac", "section": "crypto-equal"}, diff --git a/example/async_sign.cpp b/example/async_sign.cpp index 7e680589..45d52e0d 100644 --- a/example/async_sign.cpp +++ b/example/async_sign.cpp @@ -66,6 +66,7 @@ asio::awaitable sign_and_verify() { } auto const public_key = key.public_key(); if (!public_key) { + std::printf("public key: %s\n", public_key.error().message().c_str()); co_return false; } auto [signed_code, signature] = co_await crypto::async_sign(executor, key, message, use); diff --git a/include/webcpp/crypto/async.hpp b/include/webcpp/crypto/async.hpp index c3b7434d..c5dd5769 100644 --- a/include/webcpp/crypto/async.hpp +++ b/include/webcpp/crypto/async.hpp @@ -225,7 +225,7 @@ inline constexpr bool refused_v = false; /** * Makes an AES-GCM object or an Ed25519 key pair from its key bytes, asynchronously: * `Algorithm::make(key_bytes)` run when the operation is initiated, its result posted to - * `executor` (design D23). + * `executor`. * * The key is read before the call returns on a synchronous backend, * later on the browser's: it is the caller's until the completion. From 68f2976e7f27c6e096b90dfbc24be96ef2e9e83a Mon Sep 17 00:00:00 2001 From: R Date: Sat, 21 Nov 2026 23:03:06 -0300 Subject: [PATCH 09/14] crypto: the asynchronous family's remaining wording matches its behavior, a const AES-GCM object gets the constness error, and crypto.hpp names the header it leaves out --- doc/async.adoc | 10 ++++++---- include/webcpp/crypto.hpp | 3 +++ include/webcpp/crypto/async.hpp | 9 +++++---- test/async_post_test.cpp | 2 +- 4 files changed, 15 insertions(+), 9 deletions(-) diff --git a/doc/async.adoc b/doc/async.adoc index 2be3ecff..09a0d7b7 100644 --- a/doc/async.adoc +++ b/doc/async.adoc @@ -53,7 +53,7 @@ its own, and the handler would run off the program's loop. The other algorithms of crypto (the ChaCha20-Poly1305 AEADs, the secret boxes, secp256k1) are not in WebCrypto, and have no asynchronous function: naming one -stops the build, with the message "call the synchronous function", whose text +stops the build with a message that names the synchronous function to call, whose text and fix are in <>. Their synchronous functions are as cheap as these, and are called inside a handler. @@ -69,7 +69,7 @@ include::generated/backends-async_x25519.adoc[] The functions come in two kinds: * *The cheap functions*, all of the table above, cost microseconds: they run -at once and complete through the event loop, never inside the call. They exist +their work when initiated and complete through the event loop, never inside the call. They exist on every target, so that a program written once builds and runs everywhere. * *The heavy functions* run their work on another thread, on an executor the program gives (the executor of a `webcpp::asio::thread_pool`), and complete on @@ -88,7 +88,8 @@ a default, so that one program gives the same bytes on every target. [#crypto-async-cheap] === The cheap functions through the event loop -A cheap function runs the synchronous call at once, its guards first, and posts +A cheap function runs the synchronous call when the operation is initiated (at the call +for a callback, at the `co_await` for `use_awaitable`, at the launch for `deferred`), its guards first, and posts the completion to the executor the call gives, whence it reaches the handler's associated executor. The completion never runs inside the call, so a handler written for the browser's WebCrypto, which always completes later, behaves the @@ -157,7 +158,8 @@ touches the loop's state from it races with it. * *The storage is the handler's.* The post allocates with the handler's associated allocator (`bind_allocator`), as every Asio operation does; a program that counts or pools its allocations binds its own. webcpp's own code -calls neither `operator new` nor the C allocator in this family. +calls neither `operator new` nor the C allocator in this family; a backend that allocates at +`make` (OpenSSL) does so here too, as the synchronous `make` does (see <>). * *`use_future` without exceptions.* An error completes a future with an exception; a program built without exceptions reads errors with a callback or `as_tuple`. diff --git a/include/webcpp/crypto.hpp b/include/webcpp/crypto.hpp index 7895be63..e3fdee1b 100644 --- a/include/webcpp/crypto.hpp +++ b/include/webcpp/crypto.hpp @@ -15,6 +15,9 @@ `ciphers::gcm>` on WebAssembly or `ciphers::chacha20_poly1305`, or, for the original ChaCha20-Poly1305, XChaCha20-Poly1305 and the secret boxes, which libsodium alone has, links libsodium. + + It leaves out ``, the asynchronous family, which brings webcpp::asio + (`/webcpp/asio//asio`): a program includes it by itself. */ #ifndef WEBCPP_CRYPTO_HPP #define WEBCPP_CRYPTO_HPP diff --git a/include/webcpp/crypto/async.hpp b/include/webcpp/crypto/async.hpp index c5dd5769..652f78aa 100644 --- a/include/webcpp/crypto/async.hpp +++ b/include/webcpp/crypto/async.hpp @@ -25,7 +25,8 @@ (ChaCha20-Poly1305 and its forms, the secret boxes) are not in WebCrypto: call their `seal`. - Ed25519: `async_make` (a key pair from its seed), `async_generate`, `async_sign` and `async_verify`, over `curves::ed25519::basic_keypair` and `curves::ed25519::verify`. A key - pair of an algorithm WebCrypto lacks (secp256k1) is not here: call its own `sign`. + pair of an algorithm WebCrypto lacks (secp256k1) is not here: call its own signing function + (`sign_ecdsa`, `sign_schnorr`). - X25519: `async_agree`, over `curves::x25519::agree`. - The heavy functions (design D32's list) take the work executor first (a `webcpp::asio::thread_pool`'s): they check their guards on the caller's thread, run the work on @@ -322,7 +323,7 @@ auto async_seal(Executor const& executor, Gcm& aead, std::span additional_data_bytes, std::span data_bytes, CompletionToken&& token) { detail::timing_guard const timing; - if constexpr (!detail::is_gcm_v) { + if constexpr (!detail::is_gcm_v>) { static_assert(detail::refused_v, "webcpp::crypto: async_seal takes AES-GCM, the AEAD WebCrypto has: call seal " "for the others."); @@ -367,7 +368,7 @@ auto async_open(Executor const& executor, Gcm& aead, std::span data_bytes, std::span tag_bytes, CompletionToken&& token) { detail::timing_guard const timing; - if constexpr (!detail::is_gcm_v) { + if constexpr (!detail::is_gcm_v>) { static_assert(detail::refused_v, "webcpp::crypto: async_open takes AES-GCM, the AEAD WebCrypto has: call open " "for the others."); @@ -394,7 +395,7 @@ auto async_open(Executor const& executor, Gcm& aead, std::span`; the other key pairs are not in - * WebCrypto: call their `sign`. + * WebCrypto: call the key pair's own signing function. * @tparam Executor The executor's type, an Asio executor (an `io_context`'s or a strand's). * @tparam CompletionToken Any completion token for the signature `token` states. * @param executor The executor the completion is posted to. diff --git a/test/async_post_test.cpp b/test/async_post_test.cpp index 9b60bf41..4f1dfb6a 100644 --- a/test/async_post_test.cpp +++ b/test/async_post_test.cpp @@ -6,7 +6,7 @@ // The cheap functions of the asynchronous family on a synchronous backend (ruling R-A4: the // default everywhere), through detail::complete_by_post, the initiation each of them makes: the -// synchronous call runs at once, inside the initiating call, and its result, split by +// synchronous call runs when the operation is initiated, and its result, split by // detail::completion_of, completes through a post, never inside the call (rulings R-A2, R-A3). // Three test-only operations, declared as the family's functions are, exercise it on every // result shape: async_key (a secret<32> of bytes all `value`), async_block (an array of 64 bytes From 0ba6463d48a74c78ec13d99c5de2776b5afb9f40 Mon Sep 17 00:00:00 2001 From: R Date: Sun, 22 Nov 2026 00:34:35 -0300 Subject: [PATCH 10/14] crypto: the asynchronous family's lint findings are fixed at their cause, and the changelog's first line fits its word limit --- doc/changelog.adoc | 2 +- example/async_seal.cpp | 2 +- example/async_sign.cpp | 3 +- include/webcpp/crypto/async.hpp | 30 ++++++++++++------ test/async_25519_test.cpp | 1 - test/async_gcm_test.cpp | 11 ++++--- test/async_post_test.cpp | 52 +++++++++++++++++++++++++++----- test/support/timing_coverage.hpp | 18 +++++++---- 8 files changed, 86 insertions(+), 33 deletions(-) diff --git a/doc/changelog.adoc b/doc/changelog.adoc index 1d3c7ca7..8fac22e9 100644 --- a/doc/changelog.adoc +++ b/doc/changelog.adoc @@ -16,7 +16,7 @@ of every version are on webcpp's index page. === Unreleased // tag::unreleased[] -* Added crypto, C-backed primitives setting DIT on arm64 macOS, iOS, Linux and Android: ciphers, curves, randomness, fixed-value webcpp.crypto errors, `+[[nodiscard]]+` results, WEBCPP_CRYPTO_HAS_THREADS natively and with Emscripten's -pthread unless WEBCPP_CRYPTO_NO_THREADS is, and async_make, async_seal, async_open, async_generate, async_sign, async_verify and async_agree completing through an Asio event loop. +* Added crypto, C-backed primitives setting DIT on arm64: ciphers, curves, randomness, errors, `+[[nodiscard]]+` results, WEBCPP_CRYPTO_HAS_THREADS, and async_make, async_seal, async_open, async_generate, async_sign, async_verify, async_agree on Asio. * Added equal, random_device, pem on libsodium, the AES block cipher ciphers::aes128, aes192 and aes256 with a per-target default, and ciphers::gcm, aes128_gcm and aes256_gcm: incremental seal, two-pass open, failures zeroing data. * Added supports_v with its family tags, the capability table per target, default_backend_t and /webcpp/crypto//-default per family and target (secp256k1's modules among them), and refusals naming their Jamfile line. * Added backends::bearssl (AES-GCM alone, allocating nothing), backends::openssl via /webcpp/crypto//openssl natively and on WASI (allocating at make only, or natively in openssl_memory_resource with WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE), and backends::ctaes (block cipher alone). diff --git a/example/async_seal.cpp b/example/async_seal.cpp index 0bcdc072..fb847739 100644 --- a/example/async_seal.cpp +++ b/example/async_seal.cpp @@ -37,7 +37,7 @@ namespace { // The bytes a string of hex digits writes, two per byte. std::vector bytes_of(std::string_view hex) { auto const digit = [](char c) { - return static_cast(c <= '9' ? c - '0' : c - 'a' + 10); + return static_cast(c <= '9' ? c - '0' : c - 'a' + 10); }; std::vector bytes(hex.size() / 2); for (std::size_t i = 0; i < bytes.size(); ++i) { diff --git a/example/async_sign.cpp b/example/async_sign.cpp index 45d52e0d..b24449b0 100644 --- a/example/async_sign.cpp +++ b/example/async_sign.cpp @@ -66,7 +66,8 @@ asio::awaitable sign_and_verify() { } auto const public_key = key.public_key(); if (!public_key) { - std::printf("public key: %s\n", public_key.error().message().c_str()); + auto const public_key_error = public_key.error(); + std::printf("public key: %s\n", public_key_error.message().c_str()); co_return false; } auto [signed_code, signature] = co_await crypto::async_sign(executor, key, message, use); diff --git a/include/webcpp/crypto/async.hpp b/include/webcpp/crypto/async.hpp index 652f78aa..dff44bb1 100644 --- a/include/webcpp/crypto/async.hpp +++ b/include/webcpp/crypto/async.hpp @@ -160,21 +160,31 @@ struct post_initiation { */ template void operator()(Handler&& handler, Executor const& executor, Operation operation) const { - auto done = operation(); - using value_type = completion_of::value_type; - if constexpr (std::is_void_v) { - boost::system::error_code const code = - done ? boost::system::error_code{} : done.error(); - webcpp::asio::post(executor, - webcpp::asio::append(std::forward(handler), code)); - } else if (done) { + deliver(std::forward(handler), executor, operation()); + } + +private: + // A call without a value completes with its error code alone. + template + static void deliver(Handler&& handler, Executor const& executor, + boost::system::result const& done) { + boost::system::error_code const code = done ? boost::system::error_code{} : done.error(); + webcpp::asio::post(executor, webcpp::asio::append(std::forward(handler), code)); + } + + // A call with a value completes with it, or on an error with the empty one. + template + requires(!std::is_void_v) + static void deliver(Handler&& handler, Executor const& executor, + boost::system::result&& done) { + if (done) { webcpp::asio::post(executor, webcpp::asio::append(std::forward(handler), - boost::system::error_code{}, std::move(*done))); + boost::system::error_code{}, *std::move(done))); } else { webcpp::asio::post(executor, webcpp::asio::append(std::forward(handler), done.error(), - async_access::empty())); + async_access::empty())); } } }; diff --git a/test/async_25519_test.cpp b/test/async_25519_test.cpp index 28c1a40c..c00ef3cd 100644 --- a/test/async_25519_test.cpp +++ b/test/async_25519_test.cpp @@ -59,7 +59,6 @@ namespace asio = webcpp::asio; namespace crypto = webcpp::crypto; namespace ed25519 = webcpp::crypto::curves::ed25519; -namespace x25519 = webcpp::crypto::curves::x25519; namespace test = webcpp::test; namespace { diff --git a/test/async_gcm_test.cpp b/test/async_gcm_test.cpp index 217aab1a..14a5af06 100644 --- a/test/async_gcm_test.cpp +++ b/test/async_gcm_test.cpp @@ -20,7 +20,7 @@ // - async_coroutine: the example of async.hpp's header, in a coroutine of the context. #include -#if defined(WEBCPP_TEST_ASYNC_GCM_OPENSSL) +#ifdef WEBCPP_TEST_ASYNC_GCM_OPENSSL #include #else #include @@ -58,7 +58,7 @@ namespace crypto = webcpp::crypto; namespace { -#if defined(WEBCPP_TEST_ASYNC_GCM_OPENSSL) +#ifdef WEBCPP_TEST_ASYNC_GCM_OPENSSL using backend = crypto::backends::openssl; #else using backend = crypto::backends::bearssl; @@ -279,9 +279,10 @@ void async_make_refused(asio::io_context& context) { BOOST_TEST(empty.result().error() == crypto::error::invalid_state); BOOST_TEST(same_bytes(data, untouched)); // Through the asynchronous functions too. - auto sealed = complete(context, [&](auto const& executor, auto&& token) { - crypto::async_seal(executor, empty, iv, {}, data, std::forward(token)); - }); + auto const sealed = + complete(context, [&](auto const& executor, auto&& token) { + crypto::async_seal(executor, empty, iv, {}, data, std::forward(token)); + }); BOOST_TEST(sealed.code == crypto::error::invalid_state); BOOST_TEST(same_bytes(data, untouched)); } diff --git a/test/async_post_test.cpp b/test/async_post_test.cpp index 4f1dfb6a..a4241e5f 100644 --- a/test/async_post_test.cpp +++ b/test/async_post_test.cpp @@ -371,10 +371,9 @@ void post_allocator(asio::io_context& context) { check_allocator<>(context, check_of(1), check_of(0)); } -void post_tokens(asio::io_context& context) { - auto const executor = context.get_executor(); - #ifndef WEBCPP_CRYPTO_NO_EXCEPTIONS +void post_future_token(asio::io_context& context) { + auto const executor = context.get_executor(); // use_future: a single-threaded program runs the context before get(). auto made = async_key(executor, 5, asio::use_future); auto filled = async_block(executor, 5, asio::use_future); @@ -392,8 +391,11 @@ void post_tokens(asio::io_context& context) { thrown = failure.code() == crypto::error::invalid_input_size; } BOOST_TEST(thrown); +} #endif +void post_deferred_token(asio::io_context& context) { + auto const executor = context.get_executor(); // deferred: the operation runs when it is launched, and completes through the post. int const runs_before = sync_runs; auto operation = async_key(executor, 6, asio::deferred); @@ -414,7 +416,10 @@ void post_tokens(asio::io_context& context) { context.restart(); context.run(); // lint-run: the test's event loop BOOST_TEST_EQ(deferred_calls, 2); +} +void post_tuple_token(asio::io_context& context) { + auto const executor = context.get_executor(); // as_tuple: the error code and the value in one argument. int tuples = 0; async_block(executor, 7, asio::as_tuple([&](std::tuple done) { @@ -429,7 +434,9 @@ void post_tokens(asio::io_context& context) { context.restart(); context.run(); // lint-run: the test's event loop BOOST_TEST_EQ(tuples, 2); +} +void post_awaitable_token(asio::io_context& context) { // use_awaitable in a coroutine of the context. bool done = false; asio::co_spawn( @@ -467,6 +474,15 @@ void post_tokens(asio::io_context& context) { BOOST_TEST(done); } +void post_tokens(asio::io_context& context) { +#ifndef WEBCPP_CRYPTO_NO_EXCEPTIONS + post_future_token(context); +#endif + post_deferred_token(context); + post_tuple_token(context); + post_awaitable_token(context); +} + void post_error_value(asio::io_context& context) { auto const refused_key = complete_by_callback(context, key_of(0)); BOOST_TEST(refused_key.code == crypto::error::invalid_input_size); @@ -633,12 +649,10 @@ void post_gcm_allocator(asio::io_context& context) { crypto::error::invalid_key_size); } -void post_gcm_tokens(asio::io_context& context) { - gcm_fixture fixture; - auto const plaintext = fixture.data; - auto const executor = context.get_executor(); - #ifndef WEBCPP_CRYPTO_NO_EXCEPTIONS +void post_gcm_future_token(asio::io_context& context, gcm_fixture& fixture, + std::array const& plaintext) { + auto const executor = context.get_executor(); auto future_tag = crypto::async_seal(executor, fixture.aead, fixture.iv, fixture.additional_data, fixture.data, asio::use_future); context.restart(); @@ -666,8 +680,12 @@ void post_gcm_tokens(asio::io_context& context) { thrown = failure.code() == crypto::error::invalid_key_size; } BOOST_TEST(thrown); +} #endif +void post_gcm_deferred_token(asio::io_context& context, gcm_fixture& fixture, + std::array const& plaintext) { + auto const executor = context.get_executor(); // deferred: the synchronous call runs when the operation is launched, not when it is made. auto operation = crypto::async_seal(executor, fixture.aead, fixture.iv, fixture.additional_data, fixture.data, asio::deferred); @@ -683,7 +701,11 @@ void post_gcm_tokens(asio::io_context& context) { context.restart(); context.run(); // lint-run: the test's event loop BOOST_TEST_EQ(deferred_calls, 1); +} +void post_gcm_tuple_token(asio::io_context& context, gcm_fixture& fixture, + std::array const& plaintext) { + auto const executor = context.get_executor(); // as_tuple: the code and the value in one argument; the open, the code alone. int tuples = 0; crypto::async_open(executor, fixture.aead, fixture.iv, fixture.additional_data, fixture.data, @@ -702,7 +724,10 @@ void post_gcm_tokens(asio::io_context& context) { context.run(); // lint-run: the test's event loop BOOST_TEST_EQ(tuples, 2); BOOST_TEST(fixture.data == plaintext); +} +void post_gcm_awaitable_token(asio::io_context& context, gcm_fixture& fixture, + std::array const& plaintext) { // use_awaitable in a coroutine of the context: a refusal through as_tuple. bool done = false; asio::co_spawn( @@ -732,6 +757,17 @@ void post_gcm_tokens(asio::io_context& context) { BOOST_TEST(done); } +void post_gcm_tokens(asio::io_context& context) { + gcm_fixture fixture; + auto const plaintext = fixture.data; +#ifndef WEBCPP_CRYPTO_NO_EXCEPTIONS + post_gcm_future_token(context, fixture, plaintext); +#endif + post_gcm_deferred_token(context, fixture, plaintext); + post_gcm_tuple_token(context, fixture, plaintext); + post_gcm_awaitable_token(context, fixture, plaintext); +} + // Ed25519's async_verify, async_sign and X25519's async_agree through the family's real // functions, on the default backend. The fixture: RFC 8032's test 2 and RFC 7748's section 6.1. struct verify_fixture { diff --git a/test/support/timing_coverage.hpp b/test/support/timing_coverage.hpp index 5a5636cd..6beb864a 100644 --- a/test/support/timing_coverage.hpp +++ b/test/support/timing_coverage.hpp @@ -332,7 +332,7 @@ void cover_gcm(std::string const& family, std::string const& backend) { template struct async_completion_counter { /** Counts the completion. */ - int* completions; + int* completions = nullptr; /** Where a seal's tag is kept, or null. */ Tag* tag = nullptr; @@ -370,8 +370,11 @@ void cover_async_gcm(std::string const& family, std::string const& backend) { auto const key = coverage_key(); int completions = 0; typename Gcm::result_type kept{}; - async_completion_counter const counted{&completions}; - async_completion_counter const keeping{&completions, &kept}; + async_completion_counter const counted{.completions = &completions}; + async_completion_counter const keeping{ + .completions = &completions, + .tag = &kept, + }; // Each call's completion is delivered before the next call. auto const deliver = [&context] { context.restart(); @@ -434,8 +437,11 @@ void cover_async_ed25519(std::string const& backend) { std::array const message{1, 2, 3}; int completions = 0; signature_type kept{}; - async_completion_counter const counted{&completions}; - async_completion_counter const keeping{&completions, &kept}; + async_completion_counter const counted{.completions = &completions}; + async_completion_counter const keeping{ + .completions = &completions, + .tag = &kept, + }; // Each call's completion is delivered before the next call. auto const deliver = [&context] { context.restart(); @@ -507,7 +513,7 @@ void cover_async_x25519(std::string const& backend) { return; } int completions = 0; - async_completion_counter<> const counted{&completions}; + async_completion_counter<> const counted{.completions = &completions}; covered("x25519::async_agree" + on, "crypto::async_agree", [&] { crypto::async_agree(executor, alice, *bob, counted); context.restart(); From ee0747ec2c0ea38bf247b67c09aa28759f43dc84 Mon Sep 17 00:00:00 2001 From: R Date: Sun, 22 Nov 2026 03:53:27 -0300 Subject: [PATCH 11/14] crypto: the asynchronous tests and the sign example build warning-free on GCC 15 release, with the counting operators never inlined and each awaited result named before it is bound --- example/async_sign.cpp | 4 ++- test/async_25519_test.cpp | 9 +++-- test/async_gcm_test.cpp | 3 +- test/async_post_test.cpp | 6 ++-- test/support/counting.hpp | 75 ++++++++++++++++++++++----------------- 5 files changed, 57 insertions(+), 40 deletions(-) diff --git a/example/async_sign.cpp b/example/async_sign.cpp index b24449b0..73d2eea5 100644 --- a/example/async_sign.cpp +++ b/example/async_sign.cpp @@ -59,7 +59,9 @@ asio::awaitable sign_and_verify() { auto const executor = co_await asio::this_coro::executor; auto const use = asio::as_tuple(asio::use_awaitable); - auto [made, key] = co_await crypto::async_make(executor, seed, use); + auto made_result = co_await crypto::async_make(executor, seed, use); + + auto& [made, key] = made_result; if (made) { std::printf("make: %s\n", made.message().c_str()); co_return false; diff --git a/test/async_25519_test.cpp b/test/async_25519_test.cpp index c00ef3cd..3d3e842b 100644 --- a/test/async_25519_test.cpp +++ b/test/async_25519_test.cpp @@ -373,8 +373,9 @@ void async_coroutine(asio::io_context& context) { auto const seed = test::from_hex(tested.secret_key); auto const public_key = test::from_hex(tested.public_key); auto const message = test::from_hex(tested.message); - auto [made_code, key] = co_await crypto::async_make( + auto made_code_result = co_await crypto::async_make( executor, seed, asio::as_tuple(asio::use_awaitable)); + auto& [made_code, key] = made_code_result; BOOST_TEST(!made_code); auto [sign_code, signature] = co_await crypto::async_sign( executor, key, message, asio::as_tuple(asio::use_awaitable)); @@ -383,15 +384,17 @@ void async_coroutine(asio::io_context& context) { auto [verify_code] = co_await crypto::async_verify( executor, public_key, message, signature, asio::as_tuple(asio::use_awaitable)); BOOST_TEST(!verify_code); - auto [generate_code, generated_key] = + auto generate_code_result = co_await crypto::async_generate(executor, asio::as_tuple(asio::use_awaitable)); + auto& [generate_code, generated_key] = generate_code_result; BOOST_TEST(!generate_code); BOOST_TEST(generated_key.public_key().has_value()); - auto [agree_code, shared] = co_await crypto::async_agree( + auto agree_code_result = co_await crypto::async_agree( executor, test::from_hex("77076d0a7318a57d3c16c17251b26645df4c2f87ebc0992ab177fba51db92c2a"), test::from_hex("de9edb7d7b7dc1b4d35b61c2ece435373f8343c85b78674dadfc7e146f882b4f"), asio::as_tuple(asio::use_awaitable)); + auto& [agree_code, shared] = agree_code_result; BOOST_TEST(!agree_code); BOOST_TEST(std::ranges::equal( shared.bytes(), test::from_hex("4a5d9d5ba4ce2de1728e3bf480350f25e07e21c947d19e3376" diff --git a/test/async_gcm_test.cpp b/test/async_gcm_test.cpp index 14a5af06..672a6c7e 100644 --- a/test/async_gcm_test.cpp +++ b/test/async_gcm_test.cpp @@ -334,8 +334,9 @@ void async_coroutine(asio::io_context& context) { std::array data{}; data.fill(0x33); auto const plaintext = data; - auto [made_code, aead] = co_await crypto::async_make( + auto made_code_result = co_await crypto::async_make( executor, key, asio::as_tuple(asio::use_awaitable)); + auto& [made_code, aead] = made_code_result; BOOST_TEST(!made_code); auto [code, tag] = co_await crypto::async_seal( executor, aead, iv, additional_data, data, asio::as_tuple(asio::use_awaitable)); diff --git a/test/async_post_test.cpp b/test/async_post_test.cpp index a4241e5f..62413544 100644 --- a/test/async_post_test.cpp +++ b/test/async_post_test.cpp @@ -443,8 +443,9 @@ void post_awaitable_token(asio::io_context& context) { context, [&]() -> asio::awaitable { auto const coro = co_await asio::this_coro::executor; - auto [made_code, made_key] = + auto made_code_result = co_await async_key(coro, 8, asio::as_tuple(asio::use_awaitable)); + auto& [made_code, made_key] = made_code_result; BOOST_TEST(!made_code); BOOST_TEST(all_bytes(made_key, 8)); auto [refused_code, refused_block] = @@ -734,8 +735,9 @@ void post_gcm_awaitable_token(asio::io_context& context, gcm_fixture& fixture, context, [&]() -> asio::awaitable { auto const coro = co_await asio::this_coro::executor; - auto [made_code, made] = co_await crypto::async_make( + auto made_code_result = co_await crypto::async_make( coro, std::span(fixture.key).first(31), asio::as_tuple(asio::use_awaitable)); + auto& [made_code, made] = made_code_result; BOOST_TEST(made_code == crypto::error::invalid_key_size); BOOST_TEST(made.seal(fixture.iv, {}, fixture.data).error() == crypto::error::invalid_state); diff --git a/test/support/counting.hpp b/test/support/counting.hpp index 1bda61f2..310c6652 100644 --- a/test/support/counting.hpp +++ b/test/support/counting.hpp @@ -36,6 +36,8 @@ #include #include +#include + #ifdef __APPLE__ #include #elif defined(__EMSCRIPTEN__) @@ -101,121 +103,128 @@ inline void* new_block(std::size_t size, std::size_t alignment, bool aligned) { } // The replaceable global allocation functions cannot be inline: they are defined here, in the -// one translation unit of a program that includes this header, under the standard's names. +// one translation unit of a program that includes this header, under the standard's names. None is +// ever inlined: GCC 15 at -O3, seeing the malloc or the free inside one, pairs it with the other's +// call (a std::allocator's operator new, an exception's) and warns of a mismatch +// (-Wmismatched-new-delete), though both replaced forms use the C library. // NOLINTBEGIN(misc-definitions-in-headers,readability-inconsistent-declaration-parameter-name) -void* operator new(std::size_t size) { +BOOST_NOINLINE void* operator new(std::size_t size) { if (void* const p = webcpp::test::new_block(size, alignof(std::max_align_t), false)) { return p; } webcpp_test_out_of_memory(); } -void* operator new[](std::size_t size) { +BOOST_NOINLINE void* operator new[](std::size_t size) { return operator new(size); } -void* operator new(std::size_t size, std::align_val_t alignment) { +BOOST_NOINLINE void* operator new(std::size_t size, std::align_val_t alignment) { if (void* const p = webcpp::test::new_block(size, static_cast(alignment), true)) { return p; } webcpp_test_out_of_memory(); } -void* operator new[](std::size_t size, std::align_val_t alignment) { +BOOST_NOINLINE void* operator new[](std::size_t size, std::align_val_t alignment) { return operator new(size, alignment); } -void* operator new(std::size_t size, std::nothrow_t const& /*unused*/) noexcept { +BOOST_NOINLINE void* operator new(std::size_t size, std::nothrow_t const& /*unused*/) noexcept { return webcpp::test::new_block(size, alignof(std::max_align_t), false); } -void* operator new[](std::size_t size, std::nothrow_t const& /*unused*/) noexcept { +BOOST_NOINLINE void* operator new[](std::size_t size, std::nothrow_t const& /*unused*/) noexcept { return webcpp::test::new_block(size, alignof(std::max_align_t), false); } -void* operator new(std::size_t size, std::align_val_t alignment, - std::nothrow_t const& /*unused*/) noexcept { +BOOST_NOINLINE void* operator new(std::size_t size, std::align_val_t alignment, + std::nothrow_t const& /*unused*/) noexcept { return webcpp::test::new_block(size, static_cast(alignment), true); } -void* operator new[](std::size_t size, std::align_val_t alignment, - std::nothrow_t const& /*unused*/) noexcept { +BOOST_NOINLINE void* operator new[](std::size_t size, std::align_val_t alignment, + std::nothrow_t const& /*unused*/) noexcept { return webcpp::test::new_block(size, static_cast(alignment), true); } -void operator delete(void* p) noexcept { +BOOST_NOINLINE void operator delete(void* p) noexcept { std::free(p); } -void operator delete[](void* p) noexcept { +BOOST_NOINLINE void operator delete[](void* p) noexcept { std::free(p); } -void operator delete(void* p, std::size_t /*unused*/) noexcept { +BOOST_NOINLINE void operator delete(void* p, std::size_t /*unused*/) noexcept { std::free(p); } -void operator delete[](void* p, std::size_t /*unused*/) noexcept { +BOOST_NOINLINE void operator delete[](void* p, std::size_t /*unused*/) noexcept { std::free(p); } -void operator delete(void* p, std::nothrow_t const& /*unused*/) noexcept { +BOOST_NOINLINE void operator delete(void* p, std::nothrow_t const& /*unused*/) noexcept { std::free(p); } -void operator delete[](void* p, std::nothrow_t const& /*unused*/) noexcept { +BOOST_NOINLINE void operator delete[](void* p, std::nothrow_t const& /*unused*/) noexcept { std::free(p); } #ifdef _WIN32 -void operator delete(void* p, std::align_val_t /*unused*/) noexcept { +BOOST_NOINLINE void operator delete(void* p, std::align_val_t /*unused*/) noexcept { _aligned_free(p); } -void operator delete[](void* p, std::align_val_t /*unused*/) noexcept { +BOOST_NOINLINE void operator delete[](void* p, std::align_val_t /*unused*/) noexcept { _aligned_free(p); } -void operator delete(void* p, std::size_t /*unused*/, std::align_val_t /*unused*/) noexcept { +BOOST_NOINLINE void operator delete(void* p, std::size_t /*unused*/, + std::align_val_t /*unused*/) noexcept { _aligned_free(p); } -void operator delete[](void* p, std::size_t /*unused*/, std::align_val_t /*unused*/) noexcept { +BOOST_NOINLINE void operator delete[](void* p, std::size_t /*unused*/, + std::align_val_t /*unused*/) noexcept { _aligned_free(p); } -void operator delete(void* p, std::align_val_t /*unused*/, - std::nothrow_t const& /*unused*/) noexcept { +BOOST_NOINLINE void operator delete(void* p, std::align_val_t /*unused*/, + std::nothrow_t const& /*unused*/) noexcept { _aligned_free(p); } -void operator delete[](void* p, std::align_val_t /*unused*/, - std::nothrow_t const& /*unused*/) noexcept { +BOOST_NOINLINE void operator delete[](void* p, std::align_val_t /*unused*/, + std::nothrow_t const& /*unused*/) noexcept { _aligned_free(p); } #else -void operator delete(void* p, std::align_val_t /*unused*/) noexcept { +BOOST_NOINLINE void operator delete(void* p, std::align_val_t /*unused*/) noexcept { std::free(p); } -void operator delete[](void* p, std::align_val_t /*unused*/) noexcept { +BOOST_NOINLINE void operator delete[](void* p, std::align_val_t /*unused*/) noexcept { std::free(p); } -void operator delete(void* p, std::size_t /*unused*/, std::align_val_t /*unused*/) noexcept { +BOOST_NOINLINE void operator delete(void* p, std::size_t /*unused*/, + std::align_val_t /*unused*/) noexcept { std::free(p); } -void operator delete[](void* p, std::size_t /*unused*/, std::align_val_t /*unused*/) noexcept { +BOOST_NOINLINE void operator delete[](void* p, std::size_t /*unused*/, + std::align_val_t /*unused*/) noexcept { std::free(p); } -void operator delete(void* p, std::align_val_t /*unused*/, - std::nothrow_t const& /*unused*/) noexcept { +BOOST_NOINLINE void operator delete(void* p, std::align_val_t /*unused*/, + std::nothrow_t const& /*unused*/) noexcept { std::free(p); } -void operator delete[](void* p, std::align_val_t /*unused*/, - std::nothrow_t const& /*unused*/) noexcept { +BOOST_NOINLINE void operator delete[](void* p, std::align_val_t /*unused*/, + std::nothrow_t const& /*unused*/) noexcept { std::free(p); } #endif From 973913bbe9009669b275f4ff5a65cd6da3be77ed Mon Sep 17 00:00:00 2001 From: R Date: Sun, 22 Nov 2026 06:47:13 -0300 Subject: [PATCH 12/14] crypto: P-256's asynchronous functions, posted on every target --- doc/async.adoc | 16 + doc/changelog.adoc | 2 +- doc/generated/backends-async_p256.adoc | 20 + doc/generated/matrix.adoc | 11 + doc/generated/messages.adoc | 4 +- doc/llms.txt | 14 +- doc/tables/crypto.json | 15 +- include/webcpp/crypto/async.hpp | 179 +++++++-- include/webcpp/crypto/curves/p256.hpp | 4 + test/Jamfile | 7 + test/async_p256_test.cpp | 500 +++++++++++++++++++++++++ test/timing_coverage_bearssl_test.cpp | 83 +++- 12 files changed, 825 insertions(+), 30 deletions(-) create mode 100644 doc/generated/backends-async_p256.adoc create mode 100644 test/async_p256_test.cpp diff --git a/doc/async.adoc b/doc/async.adoc index 09a0d7b7..2fb51145 100644 --- a/doc/async.adoc +++ b/doc/async.adoc @@ -49,8 +49,22 @@ its own, and the handler would run off the program's loop. | X25519 (<>) | `async_agree(executor, secret_key, peer_public_key, token)` | `void(error_code, secret<32>)` + +| P-256 (<>) +| `async_make(executor, secret_scalar, token)`, `async_generate(executor, token)`, `async_sign(executor, key_pair, message, token)`, `async_verify(executor, public_key, message, signature, token)`, `async_agree(executor, key_pair, peer_public_key, token)` +| `void(error_code, Keypair)` for `async_make` and `async_generate`, `void(error_code, signature)` for `async_sign`, `void(error_code)` for `async_verify`, `void(error_code, secret<32>)` for `async_agree` |=== +P-256's `async_sign` and `async_verify` take the message, not its digest: each +hashes it with SHA-256 first and calls `sign_ecdsa` or `verify_ecdsa` on the 32 +bytes, as WebCrypto's `+sign({name: "ECDSA", hash: "SHA-256"}, ...)+` hashes and +signs in one call (link:https://www.w3.org/TR/WebCryptoAPI/#ecdsa-operations[W3C, +ECDSA's operations]). The signature is r then s, 64 bytes, WebCrypto's form; one +of another size completes `async_verify` with `invalid_signature`. Their keys are +P-256's own types, the key pair and the validated `public_key`, and +`async_agree` gives the shared point's raw x, as WebCrypto's `deriveBits` does +(<>). + The other algorithms of crypto (the ChaCha20-Poly1305 AEADs, the secret boxes, secp256k1) are not in WebCrypto, and have no asynchronous function: naming one stops the build with a message that names the synchronous function to call, whose text @@ -63,6 +77,8 @@ include::generated/backends-async_ed25519.adoc[] include::generated/backends-async_x25519.adoc[] +include::generated/backends-async_p256.adoc[] + [#crypto-async-kinds] === The two kinds diff --git a/doc/changelog.adoc b/doc/changelog.adoc index fede372a..7810a533 100644 --- a/doc/changelog.adoc +++ b/doc/changelog.adoc @@ -16,7 +16,7 @@ of every version are on webcpp's index page. === Unreleased // tag::unreleased[] -* Added crypto, C-backed primitives setting DIT on arm64: ciphers, curves, randomness, errors, `+[[nodiscard]]+` results, WEBCPP_CRYPTO_HAS_THREADS, and async_make, async_seal, async_open, async_generate, async_sign, async_verify, async_agree on Asio. +* Added crypto, C-backed primitives setting DIT on arm64 macOS, iOS, Linux and Android: ciphers, curves, randomness, errors, `+[[nodiscard]]+` results, WEBCPP_CRYPTO_HAS_THREADS, and async_make, async_seal, async_open, async_generate, async_sign, async_verify, async_agree on Asio. * Added equal, random_device, pem on libsodium, the AES block cipher ciphers::aes128, aes192 and aes256 with a per-target default, and ciphers::gcm, aes128_gcm and aes256_gcm: incremental seal, two-pass open, failures zeroing data. * Added supports_v with its family tags, the capability table per target, default_backend_t and /webcpp/crypto//-default per family and target (secp256k1's modules among them), and refusals naming their Jamfile line. * Added backends::bearssl (AES-GCM, ChaCha20-Poly1305, curves::p256: keys, ECDSA, ECDH, SPKI/PKCS#8; allocating nothing), backends::openssl natively and on WASI (allocating at make only, or in openssl_memory_resource with WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE), and backends::ctaes. diff --git a/doc/generated/backends-async_p256.adoc b/doc/generated/backends-async_p256.adoc new file mode 100644 index 00000000..b75657f6 --- /dev/null +++ b/doc/generated/backends-async_p256.adoc @@ -0,0 +1,20 @@ +// 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) + +// Generated by doc/tables/generate.py from doc/tables/crypto.json, the test Jamfiles, +// the message tests and the Jamfile fixtures: run it again, never edit this file. + +The backends of `+async_make+`, `+async_generate+`, `+async_sign+`, `+async_verify+`, `+async_agree+`, from the test programs that run it: + +[cols="1,2,2,4",options="header"] +|=== +|Backend |Jamfile |Header |Targets + +|BearSSL +|`+/third_party//bearssl+` +|`++` +|native, wasip2, wasip3, emscripten (tested by `+async_p256+`) +|=== diff --git a/doc/generated/matrix.adoc b/doc/generated/matrix.adoc index c68ab98d..a7cbfea4 100644 --- a/doc/generated/matrix.adoc +++ b/doc/generated/matrix.adoc @@ -36,6 +36,11 @@ |native, wasip2, wasip3, emscripten |`+async_25519+` +|`+async_make+`, `+async_generate+`, `+async_sign+`, `+async_verify+`, `+async_agree+` +|BearSSL +|native, wasip2, wasip3, emscripten +|`+async_p256+` + |`+equal+` |no backend |native, wasip2, wasip3, emscripten @@ -327,6 +332,12 @@ The same, by target: the backends each operation runs on. |libsodium |libsodium +|`+async_make+`, `+async_generate+`, `+async_sign+`, `+async_verify+`, `+async_agree+` +|BearSSL +|BearSSL +|BearSSL +|BearSSL + |`+equal+` |no backend |no backend diff --git a/doc/generated/messages.adoc b/doc/generated/messages.adoc index 6976cdaa..eedb3338 100644 --- a/doc/generated/messages.adoc +++ b/doc/generated/messages.adoc @@ -59,7 +59,7 @@ The fix: Call the AEAD's own `+seal+`: only AES-GCM has `+async_seal+`. |native, wasip2, wasip3 |`+webcpp::crypto: async_sign takes a key pair of an algorithm WebCrypto has (Ed25519, P-256): call the key pair's synchronous signing function for the others.+` -The fix: Call the key pair's own signing function: secp256k1 is not in WebCrypto, so only Ed25519's key pair has `+async_sign+`. +The fix: Call the key pair's own signing function: secp256k1 is not in WebCrypto, so only Ed25519's and P-256's key pairs have `+async_sign+`. |`+bearssl_not_linked+` |native, wasip2 @@ -966,7 +966,7 @@ On MSVC, each case of `test/msvc` is proven to stop the build, at compile or at |`+async_sign_secp256k1+` |the compile -|Call the key pair's own signing function: secp256k1 is not in WebCrypto, so only Ed25519's key pair has `+async_sign+`. +|Call the key pair's own signing function: secp256k1 is not in WebCrypto, so only Ed25519's and P-256's key pairs have `+async_sign+`. |`+bearssl_not_linked+` |the compile diff --git a/doc/llms.txt b/doc/llms.txt index a12d1d00..b2f7f23e 100644 --- a/doc/llms.txt +++ b/doc/llms.txt @@ -13,16 +13,22 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - max: The largest value `operator()` gives. - entropy: The entropy of a value, in bits: every bit is the system's. - [async_make, async_seal, async_open](https://webcpporg.github.io/libs/crypto/#crypto-async): AES-GCM's asynchronous make, seal and open, each completing through a post to the executor the call gives, with any Asio completion token. Header . Backends: BearSSL (/third_party//bearssl) on native, wasip2, wasip3, emscripten; OpenSSL (/webcpp/crypto//openssl) on native, wasip2, wasip3. Use it to: seal or open a record inside an event loop without waiting. - - async_make: Makes an AES-GCM object or an Ed25519 key pair from its key bytes, asynchronously: `Algorithm::make(key_bytes)` run when the operation is initiated, its result posted to `executor`. + - async_make: Makes an AES-GCM object, an Ed25519 key pair or a P-256 key pair from its key bytes, asynchronously: `Algorithm::make(key_bytes)` run when the operation is initiated, its result posted to `executor`. - async_seal: Seals a message in place, asynchronously: `aead.seal` run when the operation is initiated, its result posted to `executor`. - async_open: Opens a message in place, asynchronously: `aead.open` run when the operation is initiated, its result posted to `executor`. - [async_make, async_generate, async_sign, async_verify](https://webcpporg.github.io/libs/crypto/#crypto-async): Ed25519's asynchronous make, generate, sign and verify, each completing through a post to the executor the call gives, with any Asio completion token. Header . Backends: libsodium (/third_party//sodium) on native, wasip2, wasip3, emscripten. Use it to: sign and verify with Ed25519 in a coroutine. - - async_make: Makes an AES-GCM object or an Ed25519 key pair from its key bytes, asynchronously: `Algorithm::make(key_bytes)` run when the operation is initiated, its result posted to `executor`. - - async_generate: Makes an Ed25519 key pair from a fresh seed, asynchronously: `Keypair::generate()` run when the operation is initiated (the system's generator is drawn from then), its result posted to `executor`. - - async_sign: Signs a message with an Ed25519 key pair, asynchronously: `key_pair.sign(message)` run when the operation is initiated, its result posted to `executor`. + - async_make: Makes an AES-GCM object, an Ed25519 key pair or a P-256 key pair from its key bytes, asynchronously: `Algorithm::make(key_bytes)` run when the operation is initiated, its result posted to `executor`. + - async_generate: Makes an Ed25519 or a P-256 key pair from a fresh seed or scalar, asynchronously: `Keypair::generate()` run when the operation is initiated (the system's generator is drawn from then), its result posted to `executor`. + - async_sign: Signs a message with an Ed25519 or a P-256 key pair, asynchronously, when the operation is initiated, its result posted to `executor`: Ed25519's `key_pair.sign(message)`; P-256's ECDSA, `key_pair.sign_ecdsa` of the message's SHA-256 digest, as WebCrypto's ECDSA with SHA-256 signs (RFC 6979's nonce: the same key and message give the same signature). - async_verify: Verifies an Ed25519 signature, asynchronously: `curves::ed25519::verify` run when the operation is initiated, its result posted to `executor`. - [async_agree](https://webcpporg.github.io/libs/crypto/#crypto-async): X25519's asynchronous agree, completing through a post to the executor the call gives, with any Asio completion token. Header . Backends: libsodium (/third_party//sodium) on native, wasip2, wasip3, emscripten. - async_agree: Agrees an X25519 shared secret, asynchronously: `curves::x25519::agree` run when the operation is initiated, its result posted to `executor`. +- [async_make, async_generate, async_sign, async_verify, async_agree](https://webcpporg.github.io/libs/crypto/#crypto-async): P-256's asynchronous make, generate, ECDSA sign and verify of a message hashed with SHA-256, and ECDH's raw x, each completing through a post to the executor the call gives, with any Asio completion token. Header . Backends: BearSSL (/third_party//bearssl) on native, wasip2, wasip3, emscripten. Use it to: sign and verify with Ed25519 in a coroutine. + - async_make: Makes an AES-GCM object, an Ed25519 key pair or a P-256 key pair from its key bytes, asynchronously: `Algorithm::make(key_bytes)` run when the operation is initiated, its result posted to `executor`. + - async_generate: Makes an Ed25519 or a P-256 key pair from a fresh seed or scalar, asynchronously: `Keypair::generate()` run when the operation is initiated (the system's generator is drawn from then), its result posted to `executor`. + - async_sign: Signs a message with an Ed25519 or a P-256 key pair, asynchronously, when the operation is initiated, its result posted to `executor`: Ed25519's `key_pair.sign(message)`; P-256's ECDSA, `key_pair.sign_ecdsa` of the message's SHA-256 digest, as WebCrypto's ECDSA with SHA-256 signs (RFC 6979's nonce: the same key and message give the same signature). + - async_verify: Verifies an Ed25519 signature, asynchronously: `curves::ed25519::verify` run when the operation is initiated, its result posted to `executor`. + - async_agree: Agrees an X25519 shared secret, asynchronously: `curves::x25519::agree` run when the operation is initiated, its result posted to `executor`. - [equal](https://webcpporg.github.io/libs/crypto/#crypto-equal): Compares two tags or MACs in constant time. Header . Backends: no backend (/webcpp/crypto//crypto) on native, wasip2, wasip3, emscripten. Use it to: check a webhook's or an API's HMAC signature. - equal: Whether two byte sequences are equal, in a time that does not depend on their contents. - [error](https://webcpporg.github.io/libs/crypto/#crypto-errors): Every failure's value, fixed and never reused, in the category webcpp.crypto. Header . Backends: no backend (/webcpp/crypto//crypto) on native, wasip2, wasip3, emscripten. Use it to: tell a forged message from a malformed one. diff --git a/doc/tables/crypto.json b/doc/tables/crypto.json index 028222cf..fe101993 100644 --- a/doc/tables/crypto.json +++ b/doc/tables/crypto.json @@ -286,6 +286,19 @@ "sodium": {"tests": ["async_25519"]} } }, + { + "id": "async_p256", + "free": true, + "functions": ["async_make", "async_generate", "async_sign", "async_verify", "async_agree"], + "namespace": "root", + "api": "async_make, async_generate, async_sign, async_verify, async_agree", + "header": "", + "what": "P-256's asynchronous make, generate, ECDSA sign and verify of a message hashed with SHA-256, and ECDH's raw x, each completing through a post to the executor the call gives, with any Asio completion token.", + "section": "crypto-async", + "backends": { + "bearssl": {"tests": ["async_p256"]} + } + }, { "id": "equal", "functions": ["equal"], @@ -1377,7 +1390,7 @@ "async_make_xchacha": "Call the synchronous `make`: XChaCha20-Poly1305 is not in WebCrypto, so it has no asynchronous form.", "async_seal_xchacha": "Call the AEAD's own `seal`: only AES-GCM has `async_seal`.", "async_open_xchacha": "Call the AEAD's own `open`: only AES-GCM has `async_open`.", - "async_sign_secp256k1": "Call the key pair's own signing function: secp256k1 is not in WebCrypto, so only Ed25519's key pair has `async_sign`.", + "async_sign_secp256k1": "Call the key pair's own signing function: secp256k1 is not in WebCrypto, so only Ed25519's and P-256's key pairs have `async_sign`.", "heavy_without_threads_on_emscripten": "As `heavy_without_threads`: on Emscripten, add `multi`.", "chacha_on_ctaes_on_emscripten": "As `chacha_on_ctaes`.", "aead_not_a_family_on_emscripten": "As `aead_not_a_family`.", diff --git a/include/webcpp/crypto/async.hpp b/include/webcpp/crypto/async.hpp index dff44bb1..0d43a545 100644 --- a/include/webcpp/crypto/async.hpp +++ b/include/webcpp/crypto/async.hpp @@ -28,6 +28,11 @@ pair of an algorithm WebCrypto lacks (secp256k1) is not here: call its own signing function (`sign_ecdsa`, `sign_schnorr`). - X25519: `async_agree`, over `curves::x25519::agree`. + - P-256: `async_make` (a key pair from its secret scalar), `async_generate`, `async_sign` and + `async_verify`, ECDSA over `curves::p256::basic_keypair::sign_ecdsa` and + `curves::p256::verify_ecdsa`, each hashing the message with SHA-256 first, as WebCrypto's + ECDSA with SHA-256 does; and `async_agree`, ECDH's raw x coordinate (WebCrypto's + `deriveBits`), over `curves::p256::basic_keypair::ecdh_x`. - The heavy functions (design D32's list) take the work executor first (a `webcpp::asio::thread_pool`'s): they check their guards on the caller's thread, run the work on the work executor and complete on the handler's associated executor, with webcpp::hash's @@ -75,6 +80,7 @@ #include #include +#include #include #include #include @@ -82,13 +88,18 @@ #include #include +#include // webcpp::hash::sha2_256, P-256's ECDSA's hash + #include #include #include +#include #include #include +#include +#include #include #include #include @@ -133,8 +144,12 @@ inline constexpr bool asynchronous_backend_v = false; * - `seal(executor, aead, iv_bytes, additional_data_bytes, data_bytes, token)` and * `open(executor, aead, iv_bytes, additional_data_bytes, data_bytes, tag_bytes, token)`; * - `sign(executor, key_pair, message, token)`; - * - `verify(executor, public_key, message, signature, token)`; - * - `agree(executor, secret_key, peer_public_key, token)`. + * - `verify(executor, public_key, message, signature, token)` for Ed25519, and + * `verify(executor, public_key, message, signature, token)` for P-256, its key P-256's + * `basic_public_key`; + * - `agree(executor, secret_key, peer_public_key, token)` for X25519, and + * `agree(executor, key_pair, peer_public_key, token)` for P-256, its key pair and its peer's + * key P-256's types. * The signatures of the completions are the public functions'. The function's guard * (`detail::timing_guard`) is held by the public function before it calls the engine. * @@ -227,6 +242,37 @@ inline constexpr bool is_ed25519_keypair_v = false; template inline constexpr bool is_ed25519_keypair_v> = true; +/** Whether `Type` is a P-256 key pair, `curves::p256::basic_keypair`. */ +template +inline constexpr bool is_p256_keypair_v = false; + +template +inline constexpr bool is_p256_keypair_v> = true; + +/** Whether `Type` is a key pair of an algorithm WebCrypto has: Ed25519's or P-256's. */ +template +inline constexpr bool is_webcrypto_keypair_v = + is_ed25519_keypair_v || is_p256_keypair_v; + +/** + * The digest P-256's ECDSA signs and verifies: SHA-256 of the message (webcpp::hash's + * `sha2_256`, Boost.Hash2's), as WebCrypto's ECDSA with SHA-256 hashes it. + * + * @param message Public bytes, of any size. + * @return The 32-byte digest. + */ +[[nodiscard]] inline std::array p256_digest( + std::span message) noexcept { + ::webcpp::hash::sha2_256 hasher; + hasher.update(message.data(), message.size()); + static_assert(std::is_same_v<::webcpp::hash::sha2_256::result_type, + boost::hash2::digest>); + auto const hashed = hasher.result(); + std::array digest{}; + std::copy_n(hashed.data(), digest.size(), digest.begin()); + return digest; +} + /** False for every type, so that a refusal's `static_assert` fires only when it is reached. */ template inline constexpr bool refused_v = false; @@ -234,30 +280,34 @@ inline constexpr bool refused_v = false; } // namespace detail /** - * Makes an AES-GCM object or an Ed25519 key pair from its key bytes, asynchronously: + * Makes an AES-GCM object, an Ed25519 key pair or a P-256 key pair from its key bytes, + * asynchronously: * `Algorithm::make(key_bytes)` run when the operation is initiated, its result posted to * `executor`. * * The key is read before the call returns on a synchronous backend, * later on the browser's: it is the caller's until the completion. * - * @tparam Algorithm A `ciphers::gcm` or a `curves::ed25519::basic_keypair`, on - * any backend that has it; the other algorithms crypto has are not in WebCrypto: call their - * `make`. + * @tparam Algorithm A `ciphers::gcm`, a `curves::ed25519::basic_keypair` or a + * `curves::p256::basic_keypair`, on any backend that has it; the other algorithms crypto + * has are not in WebCrypto: call their `make`. * @tparam Executor The executor's type, an Asio executor (an `io_context`'s or a strand's). * @tparam CompletionToken Any completion token for the signature `token` states. * @param executor The executor the completion is posted to. - * @param key_bytes `Algorithm::key_size` bytes for AES-GCM, the seed's `seed_size` for a key pair. + * @param key_bytes `Algorithm::key_size` bytes for AES-GCM, the seed's `seed_size` for an + * Ed25519 key pair, the secret scalar's `secret_key_size` (32 bytes, big-endian) for a P-256 key + * pair. * @param token The completion token, of signature `void(boost::system::error_code, Algorithm)`; * on an error the object is empty, and every member refuses with `invalid_state` - * (`invalid_key_size`, `errc::not_enough_memory`, `backend_failure`). + * (`invalid_key_size`, `invalid_secret_key` for a P-256 scalar 0 or not below the group order, + * `errc::not_enough_memory`, `backend_failure`). * @return What the completion token's `async_result` gives. */ template auto async_make(Executor const& executor, std::span key_bytes, CompletionToken&& token) { detail::timing_guard const timing; - if constexpr (!detail::is_gcm_v && !detail::is_ed25519_keypair_v) { + if constexpr (!detail::is_gcm_v && !detail::is_webcrypto_keypair_v) { static_assert(detail::refused_v, "webcpp::crypto: async_make takes AES-GCM or a key pair of an algorithm " "WebCrypto has (Ed25519, P-256): call the synchronous make for the others."); @@ -274,12 +324,13 @@ auto async_make(Executor const& executor, std::span key_byte } /** - * Makes an Ed25519 key pair from a fresh seed, asynchronously: `Keypair::generate()` run when - * the operation is initiated (the system's generator is drawn from then), its result posted to - * `executor`. + * Makes an Ed25519 or a P-256 key pair from a fresh seed or scalar, asynchronously: + * `Keypair::generate()` run when the operation is initiated (the system's generator is drawn from + * then), its result posted to `executor`. * * @tparam Keypair A `curves::ed25519::basic_keypair`, by default the family's - * `curves::ed25519::keypair`; the other key pairs are not in WebCrypto: call their `generate`. + * `curves::ed25519::keypair`, or a `curves::p256::basic_keypair`; the other key pairs + * are not in WebCrypto: call their `generate`. * @tparam Executor The executor's type, an Asio executor (an `io_context`'s or a strand's). * @tparam CompletionToken Any completion token for the signature `token` states. * @param executor The executor the completion is posted to. @@ -291,7 +342,7 @@ auto async_make(Executor const& executor, std::span key_byte template auto async_generate(Executor const& executor, CompletionToken&& token) { detail::timing_guard const timing; - if constexpr (!detail::is_ed25519_keypair_v) { + if constexpr (!detail::is_webcrypto_keypair_v) { static_assert(detail::refused_v, "webcpp::crypto: async_generate takes a key pair of an algorithm WebCrypto " "has (Ed25519, P-256): call the synchronous generate for the others."); @@ -399,27 +450,31 @@ auto async_open(Executor const& executor, Gcm& aead, std::span`; the other key pairs are not in - * WebCrypto: call the key pair's own signing function. + * @tparam Keypair A `curves::ed25519::basic_keypair` or a + * `curves::p256::basic_keypair`; the other key pairs are not in WebCrypto: call the key + * pair's own signing function. * @tparam Executor The executor's type, an Asio executor (an `io_context`'s or a strand's). * @tparam CompletionToken Any completion token for the signature `token` states. * @param executor The executor the completion is posted to. * @param key_pair The key pair. - * @param message Any bytes. + * @param message Any bytes; for P-256 the message itself, never its digest. * @param token The completion token, of signature `void(error_code, signature)`, the signature - * a `std::array` of 64 bytes; on an error it is 64 zeros (`invalid_state`, `backend_failure`). + * a `std::array` of 64 bytes (P-256's r then s, IEEE P1363's form, WebCrypto's); on an error it + * is 64 zeros (`invalid_state`, `backend_failure`). * @return What the completion token's `async_result` gives. */ template auto async_sign(Executor const& executor, Keypair const& key_pair, std::span message, CompletionToken&& token) { detail::timing_guard const timing; - if constexpr (!detail::is_ed25519_keypair_v) { + if constexpr (!detail::is_webcrypto_keypair_v) { static_assert( detail::refused_v, "webcpp::crypto: async_sign takes a key pair of an algorithm WebCrypto has " @@ -429,6 +484,10 @@ auto async_sign(Executor const& executor, Keypair const& key_pair, if constexpr (detail::asynchronous_backend_v) { return detail::async_engine::sign(executor, key_pair, message, std::forward(token)); + } else if constexpr (detail::is_p256_keypair_v) { + return detail::complete_by_post(executor, token, [&key_pair, message]() noexcept { + return key_pair.sign_ecdsa(detail::p256_digest(message)); + }); } else { return detail::complete_by_post(executor, token, [&key_pair, message]() noexcept { return key_pair.sign(message); @@ -473,6 +532,50 @@ auto async_verify(Executor const& executor, std::span public } } +/** + * Verifies a P-256 ECDSA signature of a message, asynchronously: `curves::p256::verify_ecdsa` of + * the message's SHA-256 digest run when the operation is initiated, its result posted to + * `executor`, as WebCrypto's ECDSA with SHA-256 verifies. + * + * A high S and a low S are both accepted, as `verify_ecdsa` and WebCrypto accept them. + * + * The key and the spans are the caller's until the completion. + * + * @tparam Backend The key's backend, which verifies. + * @tparam Executor The executor's type, an Asio executor (an `io_context`'s or a strand's). + * @tparam CompletionToken Any completion token for the signature `token` states. + * @param executor The executor the completion is posted to. + * @param public_key The signer's public key, validated when it was made. + * @param message The signed bytes, the message itself, never its digest. + * @param signature 64 bytes, r then s (IEEE P1363's form, WebCrypto's); `curves::p256::from_der` + * reads DER. + * @param token The completion token, of signature `void(boost::system::error_code)`: + * `invalid_signature` for a signature of another size, an r or an s that is 0 or not below n, and + * one that does not verify. + * @return What the completion token's `async_result` gives. + */ +template +auto async_verify(Executor const& executor, + curves::p256::basic_public_key const& public_key, + std::span message, std::span signature, + CompletionToken&& token) { + detail::timing_guard const timing; + if constexpr (detail::asynchronous_backend_v) { + return detail::async_engine::verify(executor, public_key, message, signature, + std::forward(token)); + } else { + return detail::complete_by_post( + executor, token, + [&public_key, message, signature]() noexcept -> boost::system::result { + if (signature.size() != curves::p256::signature_size) { + return error::invalid_signature; + } + return curves::p256::verify_ecdsa(signature.first(), + detail::p256_digest(message), public_key); + }); + } +} + /** * Agrees an X25519 shared secret, asynchronously: `curves::x25519::agree` run when the * operation is initiated, its result posted to `executor`. @@ -505,6 +608,40 @@ auto async_agree(Executor const& executor, std::span secret_ } } +/** + * Agrees a P-256 shared secret, ECDH's raw x coordinate, asynchronously: + * `key_pair.ecdh_x(peer_public_key)` run when the operation is initiated, its result posted to + * `executor`, as WebCrypto's `deriveBits` with ECDH on P-256 gives its 256 bits. + * + * The x coordinate is not a key: a protocol hashes it into its keys (with HKDF, for instance). + * The key pair and the peer's key are the caller's until the completion. + * + * @tparam Backend The backend of the key pair and of the peer's key. + * @tparam Executor The executor's type, an Asio executor (an `io_context`'s or a strand's). + * @tparam CompletionToken Any completion token for the signature `token` states. + * @param executor The executor the completion is posted to. + * @param key_pair This side's key pair. + * @param peer_public_key The peer's public key, validated when it was made. + * @param token The completion token, of signature `void(boost::system::error_code, secret<32>)`: + * the shared x, big-endian; on an error a secret of zeros (`invalid_state` for an empty key pair, + * `backend_failure`). + * @return What the completion token's `async_result` gives. + */ +template +auto async_agree(Executor const& executor, curves::p256::basic_keypair const& key_pair, + curves::p256::basic_public_key const& peer_public_key, + CompletionToken&& token) { + detail::timing_guard const timing; + if constexpr (detail::asynchronous_backend_v) { + return detail::async_engine::agree(executor, key_pair, peer_public_key, + std::forward(token)); + } else { + return detail::complete_by_post(executor, token, [&key_pair, &peer_public_key]() noexcept { + return key_pair.ecdh_x(peer_public_key); + }); + } +} + } // namespace webcpp::crypto #endif // WEBCPP_CRYPTO_ASYNC_HPP diff --git a/include/webcpp/crypto/curves/p256.hpp b/include/webcpp/crypto/curves/p256.hpp index 4b85f691..ac82b115 100644 --- a/include/webcpp/crypto/curves/p256.hpp +++ b/include/webcpp/crypto/curves/p256.hpp @@ -22,6 +22,7 @@ #include +#include #include #include #include @@ -159,6 +160,9 @@ class basic_keypair { using engine = detail::p_curve_engine; using traits = detail::p_curve_traits; + // The asynchronous family's error completions make the empty object a move leaves. + friend struct detail::async_access; + public: /** The family, for `supports_v`. */ using family_type = families::p256; diff --git a/test/Jamfile b/test/Jamfile index cd22b9cd..fdc3f0a1 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -132,6 +132,13 @@ crypto-run async_gcm_openssl : async_gcm_test.cpp # refused seed, a weak peer key, a coroutine. crypto-run async_25519 : async_25519_test.cpp : /webcpp/asio//asio /third_party//sodium ; +# P-256's asynchronous functions on BearSSL, every target: RFC 6979's +# signatures, Wycheproof's first 50 valid ECDSA P-256 SHA-256 cases and first +# 50 valid ECDH P-256 cases against the synchronous answers, refusals, an +# empty key pair, a coroutine. +crypto-run async_p256 : async_p256_test.cpp + : /webcpp/asio//asio /third_party//bearssl + /third_party//wycheproof /webcpp//boost_json ; # Without threads (WEBCPP_CRYPTO_NO_THREADS natively; WASI has none), a heavy # operation's async_ variant that forgets its refusal stops at # detail::run_on_work's stand-in, which names the refusal, and with that diff --git a/test/async_p256_test.cpp b/test/async_p256_test.cpp new file mode 100644 index 00000000..e4d9b552 --- /dev/null +++ b/test/async_p256_test.cpp @@ -0,0 +1,500 @@ +// 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) + +// P-256's asynchronous functions on BearSSL, on a callback and in a coroutine. async_sign and +// async_verify take the message and hash it with SHA-256, as WebCrypto's ECDSA with SHA-256 does; +// the synchronous answers they are checked against are sign_ecdsa and verify_ecdsa of its digest. +// - async_rfc6979: RFC 6979 section A.2.5's key through async_make, its messages "sample" and +// "test" through async_sign give the RFC's signatures and the synchronous ones, and async_verify +// accepts them; each completion arrives after the initiating call returned. +// - async_wycheproof_ecdsa: the first 50 valid cases of Wycheproof's ECDSA P-256 SHA-256 file in +// WebCrypto's form (IEEE P1363's r || s) verify through async_verify as through verify_ecdsa; +// with a changed byte of the message both refuse them with invalid_signature. +// - async_wycheproof_ecdh: the first 50 valid cases of Wycheproof's ECDH P-256 file on points +// through async_make and async_agree give the file's shared x and ecdh_x's. +// - async_verify_refused: a changed byte of the signature, a signature of 63 bytes and one whose +// r is 0 complete with invalid_signature. +// - async_generate: async_generate gives a key pair whose signature verifies, on the default +// backend and on BearSSL named. +// - async_make_refused: a scalar of 31 bytes completes with invalid_key_size, the group order +// with invalid_secret_key, each with an empty key pair, which refuses every member with +// invalid_state (review focus 5), async_sign and async_agree on it too, with zeros. +// - async_destroyed: the key pair, the message and the peer's key destroyed after the initiating +// call returns and before the completion: a synchronous backend has read them already, so the +// completion gives the right result. +// - async_coroutine: the same in one coroutine of the context. + +#include +#include +#include +#include +#include +#include +#include + +#include "support/hex.hpp" +#include "support/p256_data.hpp" +#include "support/test_data.hpp" + +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace asio = webcpp::asio; +namespace crypto = webcpp::crypto; +namespace p256 = webcpp::crypto::curves::p256; +namespace data = webcpp::test::p256; +namespace test = webcpp::test; +namespace json = boost::json; + +namespace { + +using keypair = p256::basic_keypair; +using public_key = p256::basic_public_key; +using signature_type = std::array; + +// The number of cases of each Wycheproof file run through the asynchronous functions. +constexpr int wycheproof_cases = 50; + +// What a completion saw: its calls, whether the initiating call had returned, its error code and +// its value, if it has one. +template +struct completed { + int calls = 0; + bool after_return = false; + boost::system::error_code code; + std::optional> value; +}; + +// Starts `start(executor, token)` with a callback, runs the context and returns what the +// callback saw: one completion, after the initiating call returned. +template +completed complete(asio::io_context& context, Start start) { + completed done; + bool returned = false; + start(context.get_executor(), + [&done, &returned](boost::system::error_code code, Value... value) { + ++done.calls; + done.after_return = returned; + done.code = code; + done.value = std::tuple(std::move(value)...); + }); + returned = true; + BOOST_TEST_EQ(done.calls, 0); + context.restart(); + context.run(); // lint-run: the test's event loop + BOOST_TEST_EQ(done.calls, 1); + BOOST_TEST(done.after_return); + return done; +} + +// The completion of an operation with no value. +template +boost::system::error_code complete_code(asio::io_context& context, Start start) { + completed<> done; + bool returned = false; + start(context.get_executor(), [&done, &returned](boost::system::error_code code) { + ++done.calls; + done.after_return = returned; + done.code = code; + }); + returned = true; + BOOST_TEST_EQ(done.calls, 0); + context.restart(); + context.run(); // lint-run: the test's event loop + BOOST_TEST_EQ(done.calls, 1); + BOOST_TEST(done.after_return); + return done.code; +} + +// The synchronous answers' digest: SHA-256 of the message, as WebCrypto's ECDSA hashes it. +std::array sha256(std::span message) { + std::array out{}; + BOOST_TEST(webcpp::hash::digest_of(out, message).has_value()); + return out; +} + +/** Whether every byte of `bytes` is zero. */ +template +bool all_zero(Bytes const& bytes) { + return std::ranges::all_of(bytes, [](std::uint8_t byte) { return byte == 0; }); +} + +std::vector bytes_of(std::string_view text) { + return {text.begin(), text.end()}; +} + +// async_make's key pair, or nothing. +std::optional made_async(asio::io_context& context, std::span scalar) { + auto made = complete(context, [&](auto const& executor, auto&& token) { + return crypto::async_make(executor, scalar, std::forward(token)); + }); + BOOST_TEST(!made.code); + if (made.code || !made.value.has_value()) { + return std::nullopt; + } + return std::move(std::get<0>(*made.value)); +} + +completed sign_async(asio::io_context& context, keypair const& key, + std::span message) { + return complete(context, [&](auto const& executor, auto&& token) { + return crypto::async_sign(executor, key, message, std::forward(token)); + }); +} + +boost::system::error_code verify_async(asio::io_context& context, public_key const& key, + std::span message, + std::span signature) { + return complete_code(context, [&](auto const& executor, auto&& token) { + return crypto::async_verify(executor, key, message, signature, + std::forward(token)); + }); +} + +completed> agree_async(asio::io_context& context, keypair const& key, + public_key const& peer) { + return complete>(context, [&](auto const& executor, auto&& token) { + return crypto::async_agree(executor, key, peer, std::forward(token)); + }); +} + +void async_rfc6979(asio::io_context& context) { + auto const key = made_async(context, data::rfc6979_scalar); + if (!BOOST_TEST(key.has_value())) { + return; + } + auto const own = key->public_key(); + if (!BOOST_TEST(own.has_value())) { + return; + } + BOOST_TEST(own->uncompressed() == data::rfc6979_public); + for (auto const& [text, expected] : + {std::pair{std::string_view("sample"), data::rfc6979_sample}, + std::pair{std::string_view("test"), data::rfc6979_test}}) { + auto const message = bytes_of(text); + auto const signed_async = sign_async(context, *key, message); + BOOST_TEST(!signed_async.code); + if (!BOOST_TEST(signed_async.value.has_value())) { + continue; + } + auto const& signature = std::get<0>(*signed_async.value); + BOOST_TEST(signature == expected); + auto const signed_sync = key->sign_ecdsa(sha256(message)); + BOOST_TEST(signed_sync.has_value() && *signed_sync == signature); + BOOST_TEST(!verify_async(context, *own, message, signature)); + } +} + +json::value load(std::string const& name) { + auto const text = test::read_file(WEBCPP_TEST_WYCHEPROOF "/testvectors_v1/" + name + ".json"); + boost::system::error_code ec; + auto value = json::parse(text, ec); + BOOST_TEST(!ec); + return value; +} + +std::string str(json::value const& v) { + return std::string(std::string_view(v.as_string())); +} + +void async_wycheproof_ecdsa(asio::io_context& context) { + auto const doc = load("ecdsa_secp256r1_sha256_p1363_test"); + int run = 0; + for (auto const& group : doc.at("testGroups").as_array()) { + auto const key = + public_key::make(test::from_hex(str(group.at("publicKey").at("uncompressed")))); + if (!BOOST_TEST(key.has_value())) { + continue; + } + for (auto const& t : group.at("tests").as_array()) { + if (run == wycheproof_cases) { + break; + } + if (str(t.at("result")) != "valid") { + continue; + } + ++run; + auto message = test::from_hex(str(t.at("msg"))); + auto const encoded = test::from_hex(str(t.at("sig"))); + if (!BOOST_TEST_EQ(encoded.size(), p256::signature_size)) { + continue; + } + std::span const signature(encoded.data(), + encoded.size()); + auto const verified_sync = p256::verify_ecdsa(signature, sha256(message), *key); + BOOST_TEST(verified_sync.has_value()); + BOOST_TEST(!verify_async(context, *key, message, encoded)); + // A changed byte of the message: both refuse it. + message.push_back(0); + message.front() ^= 1U; + BOOST_TEST(p256::verify_ecdsa(signature, sha256(message), *key).error() == + crypto::error::invalid_signature); + BOOST_TEST(verify_async(context, *key, message, encoded) == + crypto::error::invalid_signature); + } + } + BOOST_TEST_EQ(run, wycheproof_cases); + std::cout << "ecdsa_secp256r1_sha256_p1363_test: async_verified=" << run << '\n'; +} + +// A case's private key as 32 bytes: Wycheproof writes it as an ASN.1 integer's bytes, which may +// carry a leading 00, or shorter; the leading zero bytes are stripped and the rest left-padded. +// More than 32 significant bytes is no P-256 scalar: nothing is returned. +std::optional> scalar_bytes( + std::vector const& integer) { + auto const first = std::ranges::find_if(integer, [](std::uint8_t b) { return b != 0; }); + auto const significant = static_cast(integer.end() - first); + if (significant > p256::secret_key_size) { + return std::nullopt; + } + std::array padded{}; + std::copy(first, integer.end(), padded.end() - static_cast(significant)); + return padded; +} + +void async_wycheproof_ecdh(asio::io_context& context) { + auto const doc = load("ecdh_secp256r1_ecpoint_test"); + int run = 0; + for (auto const& group : doc.at("testGroups").as_array()) { + for (auto const& t : group.at("tests").as_array()) { + if (run == wycheproof_cases) { + break; + } + if (str(t.at("result")) != "valid") { + continue; + } + ++run; + auto const scalar = scalar_bytes(test::from_hex(str(t.at("private")))); + auto const peer = public_key::make(test::from_hex(str(t.at("public")))); + auto const shared = test::from_hex(str(t.at("shared"))); + if (!BOOST_TEST(scalar.has_value()) || !BOOST_TEST(peer.has_value())) { + continue; + } + auto const key = made_async(context, *scalar); + auto const synchronous = keypair::make(*scalar); + if (!BOOST_TEST(key.has_value()) || !BOOST_TEST(synchronous.has_value())) { + continue; + } + auto const agreed_sync = synchronous->ecdh_x(*peer); + auto const agreed = agree_async(context, *key, *peer); + BOOST_TEST(!agreed.code); + if (!BOOST_TEST(agreed.value.has_value()) || !BOOST_TEST(agreed_sync.has_value())) { + continue; + } + auto const bytes = std::get<0>(*agreed.value).bytes(); + BOOST_TEST(std::ranges::equal(bytes, shared)); + BOOST_TEST(std::ranges::equal(bytes, agreed_sync->bytes())); + } + } + BOOST_TEST_EQ(run, wycheproof_cases); + std::cout << "ecdh_secp256r1_ecpoint_test: async_agreed=" << run << '\n'; +} + +void async_verify_refused(asio::io_context& context) { + auto const key = public_key::make(data::rfc6979_public); + if (!BOOST_TEST(key.has_value())) { + return; + } + auto const message = bytes_of("test"); + auto signature = data::rfc6979_test; + BOOST_TEST(!verify_async(context, *key, message, signature)); + signature[10] ^= 1U; + BOOST_TEST(verify_async(context, *key, message, signature) == crypto::error::invalid_signature); + signature[10] ^= 1U; + BOOST_TEST(verify_async(context, *key, message, std::span(signature).first(63)) == + crypto::error::invalid_signature); + std::fill_n(signature.begin(), p256::coordinate_size, std::uint8_t{0}); + BOOST_TEST(verify_async(context, *key, message, signature) == crypto::error::invalid_signature); +} + +template +void generated(asio::io_context& context) { + auto made = complete(context, [](auto const& executor, auto&& token) { + return crypto::async_generate(executor, std::forward(token)); + }); + BOOST_TEST(!made.code); + if (!BOOST_TEST(made.value.has_value())) { + return; + } + auto& key = std::get<0>(*made.value); + std::array const message{1, 2, 3, 4, 5}; + auto const own = key.public_key(); + if (!BOOST_TEST(own.has_value())) { + return; + } + auto const signed_async = + complete(context, [&](auto const& executor, auto&& token) { + return crypto::async_sign(executor, key, message, std::forward(token)); + }); + BOOST_TEST(!signed_async.code); + if (!BOOST_TEST(signed_async.value.has_value())) { + return; + } + auto const& signature = std::get<0>(*signed_async.value); + BOOST_TEST(p256::verify_ecdsa(signature, sha256(message), *own).has_value()); + auto const verified = complete_code(context, [&](auto const& executor, auto&& token) { + return crypto::async_verify(executor, *own, message, signature, + std::forward(token)); + }); + BOOST_TEST(!verified); +} + +void async_generate(asio::io_context& context) { + generated(context); + generated(context); +} + +void async_make_refused(asio::io_context& context) { + auto const peer = public_key::make(data::rfc6979_public); + if (!BOOST_TEST(peer.has_value())) { + return; + } + std::array const message{1, 2, 3}; + auto const refused = [&](std::span scalar, crypto::error expected) { + auto const made = complete(context, [&](auto const& executor, auto&& token) { + return crypto::async_make(executor, scalar, + std::forward(token)); + }); + BOOST_TEST(made.code == expected); + if (!BOOST_TEST(made.value.has_value())) { + return; + } + auto const& empty = std::get<0>(*made.value); + BOOST_TEST(empty.public_key().error() == crypto::error::invalid_state); + BOOST_TEST(empty.secret_scalar().error() == crypto::error::invalid_state); + BOOST_TEST(empty.sign_ecdsa(sha256(message)).error() == crypto::error::invalid_state); + BOOST_TEST(empty.ecdh_x(*peer).error() == crypto::error::invalid_state); + auto const signed_empty = sign_async(context, empty, message); + BOOST_TEST(signed_empty.code == crypto::error::invalid_state); + if (BOOST_TEST(signed_empty.value.has_value())) { + BOOST_TEST(all_zero(std::get<0>(*signed_empty.value))); + } + auto const agreed_empty = agree_async(context, empty, *peer); + BOOST_TEST(agreed_empty.code == crypto::error::invalid_state); + if (BOOST_TEST(agreed_empty.value.has_value())) { + BOOST_TEST(all_zero(std::get<0>(*agreed_empty.value).bytes())); + } + }; + refused(std::span(data::rfc6979_scalar).first(31), crypto::error::invalid_key_size); + refused(data::order, crypto::error::invalid_secret_key); +} + +void async_destroyed(asio::io_context& context) { + signature_type signature{}; + boost::system::error_code sign_code; + boost::system::error_code agree_code; + std::array shared{}; + std::array expected_shared{}; + { + auto key = std::make_unique(*keypair::make(data::rfc6979_scalar)); + auto message = std::make_unique>(bytes_of("sample")); + auto peer = std::make_unique(*public_key::make(data::rfc6979_public)); + auto const agreed_sync = key->ecdh_x(*peer); + if (!BOOST_TEST(agreed_sync.has_value())) { + return; + } + std::ranges::copy(agreed_sync->bytes(), expected_shared.begin()); + crypto::async_sign(context.get_executor(), *key, *message, + [&](boost::system::error_code code, signature_type done) { + sign_code = code; + signature = done; + }); + crypto::async_agree(context.get_executor(), *key, *peer, + [&](boost::system::error_code code, crypto::secret<32> done) { + agree_code = code; + std::ranges::copy(done.bytes(), shared.begin()); + }); + // Everything the calls read goes out of scope here, before the completions. + } + context.restart(); + context.run(); // lint-run: the test's event loop + BOOST_TEST(!sign_code); + BOOST_TEST(signature == data::rfc6979_sample); + BOOST_TEST(!agree_code); + BOOST_TEST(shared == expected_shared); +} + +void async_coroutine(asio::io_context& context) { + bool done = false; + asio::co_spawn( + context, + [&]() -> asio::awaitable { + auto const executor = co_await asio::this_coro::executor; + auto const message = bytes_of("test"); + auto made_result = co_await crypto::async_make( + executor, data::rfc6979_scalar, asio::as_tuple(asio::use_awaitable)); + auto& [made_code, key] = made_result; + BOOST_TEST(!made_code); + auto [sign_code, signature] = co_await crypto::async_sign( + executor, key, message, asio::as_tuple(asio::use_awaitable)); + BOOST_TEST(!sign_code); + BOOST_TEST(signature == data::rfc6979_test); + auto const own = key.public_key(); + if (!BOOST_TEST(own.has_value())) { + co_return; + } + auto [verify_code] = co_await crypto::async_verify(executor, *own, message, signature, + asio::as_tuple(asio::use_awaitable)); + BOOST_TEST(!verify_code); + auto generate_result = co_await crypto::async_generate( + executor, asio::as_tuple(asio::use_awaitable)); + auto& [generate_code, peer_key] = generate_result; + BOOST_TEST(!generate_code); + auto const peer = peer_key.public_key(); + if (!BOOST_TEST(peer.has_value())) { + co_return; + } + auto agree_result = co_await crypto::async_agree(executor, key, *peer, + asio::as_tuple(asio::use_awaitable)); + auto& [agree_code, shared] = agree_result; + BOOST_TEST(!agree_code); + auto const back = peer_key.ecdh_x(*own); + BOOST_TEST(back.has_value() && std::ranges::equal(shared.bytes(), back->bytes())); + done = true; + }, + [](std::exception_ptr const& failure) { BOOST_TEST(!failure); }); + context.restart(); + context.run(); // lint-run: the test's event loop + BOOST_TEST(done); +} + +} // namespace + +int main() { + asio::io_context context; + async_rfc6979(context); + async_wycheproof_ecdsa(context); + async_wycheproof_ecdh(context); + async_verify_refused(context); + async_generate(context); + async_make_refused(context); + async_destroyed(context); + async_coroutine(context); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/timing_coverage_bearssl_test.cpp b/test/timing_coverage_bearssl_test.cpp index 9b8e5b44..144dbce4 100644 --- a/test/timing_coverage_bearssl_test.cpp +++ b/test/timing_coverage_bearssl_test.cpp @@ -20,10 +20,13 @@ // basic_public_key::make (both); verify_ecdsa, to_der, from_der; decode_spki, decode_pkcs8; not // guarded (no BearSSL call): public_key, secret_scalar, uncompressed, encode_spki, encode_pkcs8, // basic_keypair's move constructor and move assignment, and normalize_ecdsa and check_low_s, -// which test/timing_test.cpp calls without a backend. +// which test/timing_test.cpp calls without a backend; and the asynchronous async_make, +// async_generate, async_sign, async_verify and async_agree, each refused once before BearSSL +// too. #include "support/timing_seam.hpp" +#include #include #include #include @@ -36,6 +39,8 @@ #include "support/p256_data.hpp" #include "support/timing_coverage.hpp" +#include + #include #include @@ -262,6 +267,81 @@ void cover_p256_formats() { }); } +// P-256's asynchronous functions, each with valid input and with input refused before BearSSL (a +// scalar of 31 bytes, a signature of 63 bytes, a moved-from key pair), an io_context run after +// each call so that its completion is delivered. The first guard each enters is its own (the +// synchronous call it makes holds others, which run after). +void cover_async_p256() { + namespace p256 = crypto::curves::p256; + namespace data = webcpp::test::p256; + using keypair = p256::basic_keypair; + using public_key = p256::basic_public_key; + using signature_type = std::array; + webcpp::asio::io_context context; + auto const executor = context.get_executor(); + std::array const message{1, 2, 3}; + int completions = 0; + signature_type kept{}; + webcpp::test::async_completion_counter const counted{.completions = + &completions}; + webcpp::test::async_completion_counter const keeping{ + .completions = &completions, + .tag = &kept, + }; + // Each call's completion is delivered before the next call. + auto const deliver = [&context] { + context.restart(); + context.run(); // lint-run: the test's event loop + }; + webcpp::test::covered("p256::async_make on bearssl", "crypto::async_make", [&] { + crypto::async_make(executor, data::rfc6979_scalar, counted); + deliver(); + }); + webcpp::test::covered("p256::async_make with a short scalar on bearssl", "crypto::async_make", + [&] { + crypto::async_make( + executor, std::span(data::rfc6979_scalar).first(31), counted); + deliver(); + }); + webcpp::test::covered("p256::async_generate on bearssl", "crypto::async_generate", [&] { + crypto::async_generate(executor, counted); + deliver(); + }); + auto made = keypair::make(data::rfc6979_scalar); + auto const key = public_key::make(data::rfc6979_public); + if (!BOOST_TEST(made.has_value()) || !BOOST_TEST(key.has_value())) { + return; + } + webcpp::test::covered("p256::async_sign on bearssl", "crypto::async_sign", [&] { + crypto::async_sign(executor, *made, message, keeping); + deliver(); + }); + webcpp::test::covered("p256::async_verify on bearssl", "crypto::async_verify", [&] { + crypto::async_verify(executor, *key, message, kept, counted); + deliver(); + }); + webcpp::test::covered("p256::async_verify of 63 bytes on bearssl", "crypto::async_verify", [&] { + crypto::async_verify(executor, *key, message, std::span(kept).first(63), counted); + deliver(); + }); + webcpp::test::covered("p256::async_agree on bearssl", "crypto::async_agree", [&] { + crypto::async_agree(executor, *made, *key, counted); + deliver(); + }); + [[maybe_unused]] keypair const taken(std::move(*made)); + webcpp::test::covered("p256::async_sign moved from on bearssl", "crypto::async_sign", [&] { + // NOLINTNEXTLINE(bugprone-use-after-move,clang-analyzer-cplusplus.Move): tested + crypto::async_sign(executor, *made, message, counted); + deliver(); + }); + webcpp::test::covered("p256::async_agree moved from on bearssl", "crypto::async_agree", [&] { + // NOLINTNEXTLINE(bugprone-use-after-move,clang-analyzer-cplusplus.Move): tested + crypto::async_agree(executor, *made, *key, counted); + deliver(); + }); + BOOST_TEST_EQ(completions, 9); +} + } // namespace int main() { @@ -271,5 +351,6 @@ int main() { cover_p256_ecdsa(); cover_p256_ecdh(); cover_p256_formats(); + cover_async_p256(); return webcpp::test::exit_status(boost::report_errors()); } From f89b0d95e6adc73ad16c25c789c97782a4437449 Mon Sep 17 00:00:00 2001 From: R Date: Sun, 22 Nov 2026 06:52:56 -0300 Subject: [PATCH 13/14] crypto: llms.txt gives P-256's asynchronous functions their own briefs and use cases, and the P-256 chapter and the seam name the message the async functions hash --- doc/llms.txt | 6 ++-- doc/p256.adoc | 8 +++++ doc/tables/crypto.json | 5 +-- doc/tables/generate.py | 23 +++++++++++--- doc/tables/generate_test.py | 45 +++++++++++++++++++++++++++ include/webcpp/crypto/async.hpp | 5 +-- test/async_p256_test.cpp | 4 +++ test/timing_coverage_bearssl_test.cpp | 4 +-- 8 files changed, 87 insertions(+), 13 deletions(-) diff --git a/doc/llms.txt b/doc/llms.txt index b2f7f23e..4bf211ee 100644 --- a/doc/llms.txt +++ b/doc/llms.txt @@ -23,12 +23,12 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - async_verify: Verifies an Ed25519 signature, asynchronously: `curves::ed25519::verify` run when the operation is initiated, its result posted to `executor`. - [async_agree](https://webcpporg.github.io/libs/crypto/#crypto-async): X25519's asynchronous agree, completing through a post to the executor the call gives, with any Asio completion token. Header . Backends: libsodium (/third_party//sodium) on native, wasip2, wasip3, emscripten. - async_agree: Agrees an X25519 shared secret, asynchronously: `curves::x25519::agree` run when the operation is initiated, its result posted to `executor`. -- [async_make, async_generate, async_sign, async_verify, async_agree](https://webcpporg.github.io/libs/crypto/#crypto-async): P-256's asynchronous make, generate, ECDSA sign and verify of a message hashed with SHA-256, and ECDH's raw x, each completing through a post to the executor the call gives, with any Asio completion token. Header . Backends: BearSSL (/third_party//bearssl) on native, wasip2, wasip3, emscripten. Use it to: sign and verify with Ed25519 in a coroutine. +- [async_make, async_generate, async_sign, async_verify, async_agree](https://webcpporg.github.io/libs/crypto/#crypto-async): P-256's asynchronous make, generate, ECDSA sign and verify of a message hashed with SHA-256, and ECDH's raw x, each completing through a post to the executor the call gives, with any Asio completion token. Header . Backends: BearSSL (/third_party//bearssl) on native, wasip2, wasip3, emscripten. - async_make: Makes an AES-GCM object, an Ed25519 key pair or a P-256 key pair from its key bytes, asynchronously: `Algorithm::make(key_bytes)` run when the operation is initiated, its result posted to `executor`. - async_generate: Makes an Ed25519 or a P-256 key pair from a fresh seed or scalar, asynchronously: `Keypair::generate()` run when the operation is initiated (the system's generator is drawn from then), its result posted to `executor`. - async_sign: Signs a message with an Ed25519 or a P-256 key pair, asynchronously, when the operation is initiated, its result posted to `executor`: Ed25519's `key_pair.sign(message)`; P-256's ECDSA, `key_pair.sign_ecdsa` of the message's SHA-256 digest, as WebCrypto's ECDSA with SHA-256 signs (RFC 6979's nonce: the same key and message give the same signature). - - async_verify: Verifies an Ed25519 signature, asynchronously: `curves::ed25519::verify` run when the operation is initiated, its result posted to `executor`. - - async_agree: Agrees an X25519 shared secret, asynchronously: `curves::x25519::agree` run when the operation is initiated, its result posted to `executor`. + - async_verify: Verifies a P-256 ECDSA signature of a message, asynchronously: `curves::p256::verify_ecdsa` of the message's SHA-256 digest run when the operation is initiated, its result posted to `executor`, as WebCrypto's ECDSA with SHA-256 verifies. + - async_agree: Agrees a P-256 shared secret, ECDH's raw x coordinate, asynchronously: `key_pair.ecdh_x(peer_public_key)` run when the operation is initiated, its result posted to `executor`, as WebCrypto's `deriveBits` with ECDH on P-256 gives its 256 bits. - [equal](https://webcpporg.github.io/libs/crypto/#crypto-equal): Compares two tags or MACs in constant time. Header . Backends: no backend (/webcpp/crypto//crypto) on native, wasip2, wasip3, emscripten. Use it to: check a webhook's or an API's HMAC signature. - equal: Whether two byte sequences are equal, in a time that does not depend on their contents. - [error](https://webcpporg.github.io/libs/crypto/#crypto-errors): Every failure's value, fixed and never reused, in the category webcpp.crypto. Header . Backends: no backend (/webcpp/crypto//crypto) on native, wasip2, wasip3, emscripten. Use it to: tell a forged message from a malformed one. diff --git a/doc/p256.adoc b/doc/p256.adoc index b16b7b73..7ff8b431 100644 --- a/doc/p256.adoc +++ b/doc/p256.adoc @@ -152,6 +152,11 @@ ordinary ECDSA signature (link:https://csrc.nist.gov/pubs/fips/186-5/final[FIPS `invalid_signature`, also for an r or an s that is 0 or not below the group order n, refused before BearSSL sees it. +In an event loop, `async_sign(executor, key_pair, message, token)` and +`async_verify(executor, public_key, message, signature, token)` do the same +through a completion (<>); they take the *message* and hash it +with SHA-256 themselves, as WebCrypto does. + A signature has two forms. The *raw* form, 64 bytes, r then s at 32 bytes each (link:https://standards.ieee.org/ieee/1363/2049/[IEEE 1363]), is the one `sign_ecdsa` and `verify_ecdsa` take: what WebCrypto signs and verifies @@ -238,6 +243,9 @@ as a `secret<32>`, which wipes itself: include::{examples}/p256_ecdh.cpp[tag=agree,indent=0] ---- +In an event loop, `async_agree(executor, key_pair, peer, token)` gives the +same x through a completion (<>). + The raw x is exactly what a browser's WebCrypto gives: `+deriveBits({name: "ECDH", public: peerKey}, privateKey, 256)+` returns the shared point's x coordinate, 256 bits diff --git a/doc/tables/crypto.json b/doc/tables/crypto.json index fe101993..25935dab 100644 --- a/doc/tables/crypto.json +++ b/doc/tables/crypto.json @@ -292,6 +292,7 @@ "functions": ["async_make", "async_generate", "async_sign", "async_verify", "async_agree"], "namespace": "root", "api": "async_make, async_generate, async_sign, async_verify, async_agree", + "overloads": {"async_verify": "p256::basic_public_key", "async_agree": "p256::basic_keypair"}, "header": "", "what": "P-256's asynchronous make, generate, ECDSA sign and verify of a message hashed with SHA-256, and ECDH's raw x, each completing through a post to the executor the call gives, with any Asio completion token.", "section": "crypto-async", @@ -1217,8 +1218,8 @@ } }, "use_cases": [ - {"need": "Seal or open a record inside an event loop without waiting", "namespace": "webcpp::crypto", "api": "`async_seal`, `async_open`", "backend": "the default of AES-GCM", "jamfile": "/webcpp/crypto//crypto /webcpp/crypto//gcm-default /webcpp/asio//asio", "example": "async_seal", "section": "crypto-async"}, - {"need": "Sign and verify with Ed25519 in a coroutine", "namespace": "webcpp::crypto", "api": "`async_sign`, `async_verify`", "backend": "the default of Ed25519", "jamfile": "/webcpp/crypto//crypto /webcpp/crypto//ed25519-default /webcpp/asio//asio", "example": "async_sign", "section": "crypto-async"}, + {"need": "Seal or open a record inside an event loop without waiting", "namespace": "webcpp::crypto", "api": "`async_seal`, `async_open`", "backend": "the default of AES-GCM", "jamfile": "/webcpp/crypto//crypto /webcpp/crypto//gcm-default /webcpp/asio//asio", "example": "async_seal", "section": "crypto-async", "operations": ["async_gcm"]}, + {"need": "Sign and verify with Ed25519 in a coroutine", "namespace": "webcpp::crypto", "api": "`async_sign`, `async_verify`", "backend": "the default of Ed25519", "jamfile": "/webcpp/crypto//crypto /webcpp/crypto//ed25519-default /webcpp/asio//asio", "example": "async_sign", "section": "crypto-async", "operations": ["async_ed25519"]}, {"need": "Generate a session token, a password-reset link or an API key", "namespace": "webcpp::crypto", "api": "`random_device::fill`", "backend": "the system's generator", "jamfile": "/webcpp/crypto//crypto", "example": "reset_token", "section": "crypto-entropy"}, {"need": "Draw an unbiased number in a range, such as a six-digit code", "namespace": "webcpp::crypto", "api": "`random_device` with `std::uniform_int_distribution`", "backend": "the system's generator", "jamfile": "/webcpp/crypto//crypto", "example": "reset_token", "section": "crypto-entropy"}, {"need": "Check a webhook's or an API's HMAC signature", "namespace": "webcpp::crypto", "api": "`equal`, with Boost.Hash2's `hmac`", "backend": "none", "jamfile": "/webcpp/crypto//crypto", "example": "equal_hmac", "section": "crypto-equal"}, diff --git a/doc/tables/generate.py b/doc/tables/generate.py index 654d0ebb..3af7d3df 100644 --- a/doc/tables/generate.py +++ b/doc/tables/generate.py @@ -26,7 +26,10 @@ constant time; a fact about the world in a column the namespace lists as `cited` holds a source or begins with "none", or the table is refused naming its row. The namespaces and the backends are crypto.json's, in its order; llms.txt's summary is its `llms`, and each operation's entry gives its -backends, its default per target and the use cases that name it. +backends, its default per target and the use cases that name it (a use case's `operations`, when +it has them, limit it to those operations' ids, for a name that several families' operations +share). A function's brief is its Doc Comment's first sentence; an operation's `overloads` name, +per function, a text its declaration holds, for a name another family's overload declares first. The capability table is crypto.json's families: each family's algorithms and, per backend, the targets on which it has them, which the tests of the family's operations must run on (a cell is @@ -1701,7 +1704,12 @@ def use_cases_page(data: Data, library: Path) -> str: namespace under webcpp::crypto that holds it, so that no column is as wide as a namespace's full name.""" rows: List[List[str]] = [] + ids = {operation['id'] for operation in data.get('operations', [])} for entry in data['use_cases']: + unknown = [name for name in entry.get('operations', []) if name not in ids] + if unknown: + raise Fault(f'crypto.json: the use case "{entry["need"]}" names the operations ' + f'{", ".join(unknown)}, which crypto.json does not describe') example = entry['example'] if not example and entry['jamfile'] != 'none': raise Fault(f'crypto.json: the use case "{entry["need"]}" names no example: each ' @@ -1761,8 +1769,11 @@ def declared_brief(library: Path, operation: Data, function: str) -> str: """The first sentence of the Doc Comment of a function an operation names, read from the operation's headers: the description llms.txt gives it. A function written `class::name` is read in that class's body alone, for a name that another class of the header declares first. - A function no header declares is a fault.""" + A function the operation's `overloads` name is read in the first declaration that holds the + text they give it, for a name another family's overload declares first. A function no header + declares is a fault.""" scope, _, name = function.rpartition('::') + overload = operation.get('overloads', {}).get(function) if name == 'operator()': pattern = re.compile(r'\boperator\(\)\(') else: @@ -1779,6 +1790,8 @@ def declared_brief(library: Path, operation: Data, function: str) -> str: free = not declaration.lstrip('\n').startswith(' ') if operation.get('free') and not free and not scope: continue + if overload is not None and overload not in declaration: + continue found = pattern.search(declaration) # The declared name: the first parenthesis of the declaration is its own. if found and '(' not in declaration[:found.start()] and '/*' not in declaration: @@ -1786,8 +1799,9 @@ def declared_brief(library: Path, operation: Data, function: str) -> str: for line in comment.group(1).splitlines()).strip() words = LINE_REFERENCE.sub('', words.replace('@ref ', '')) return re.split(r'(?<=\.)\s', words, maxsplit=1)[0] + held = f' with {overload} in its declaration' if overload is not None else '' raise Fault(f'crypto.json names {function} of {operation["id"]}, which no Doc Comment of ' - f'{operation["header"]} declares') + f'{operation["header"]} declares{held}') def llms_entry(library: Path, operation: Data, function: str) -> str: @@ -1824,10 +1838,11 @@ def llms_default(data: Data, operation: Data) -> str: def llms_uses(data: Data, operation: Data) -> str: """The use cases of the decision table that an operation answers: of its section, or whose `answers` names it where the use case links a teaching chapter instead, naming one of its - names.""" + names; a use case that lists its `operations` answers those alone.""" named = [part.rpartition('::')[2] for part in operation['api'].split(', ')] needs = [entry['need'][:1].lower() + entry['need'][1:] for entry in data['use_cases'] if entry.get('answers', entry['section']) == operation['section'] + and operation.get('id') in entry.get('operations', [operation.get('id')]) and any(re.search(rf'\b{re.escape(name)}\b', entry['api']) for name in named)] return f' Use it to: {"; ".join(needs)}.' if needs else '' diff --git a/doc/tables/generate_test.py b/doc/tables/generate_test.py index 8147b38e..67352fa5 100644 --- a/doc/tables/generate_test.py +++ b/doc/tables/generate_test.py @@ -1144,6 +1144,48 @@ def test_a_use_case_that_links_a_teaching_section_joins_the_operation_it_answers ' Use it to: find who signed a message.') +def test_a_use_case_that_lists_its_operations_joins_those_alone(_: Path) -> None: + data = {'use_cases': [ + {'need': 'Sign with Ed25519', 'api': '`async_sign`', 'section': 's', + 'operations': ['ed']}, + {'need': 'Seal a record', 'api': '`async_seal`', 'section': 's'}]} + assert generate.llms_uses(data, {'id': 'ed', 'api': 'async_sign', 'section': 's'}) == ( + ' Use it to: sign with Ed25519.') + assert generate.llms_uses(data, {'id': 'p', 'api': 'async_sign', 'section': 's'}) == '' + + +def test_a_use_case_listing_an_unknown_operation_is_a_fault(scratch: Path) -> None: + data = {'operations': [{'id': 'ed'}], 'use_cases': [ + {'need': 'Sign with Ed25519', 'namespace': 'webcpp::crypto', 'api': '`async_sign`', + 'backend': 'b', 'jamfile': 'none', 'example': '', 'section': 's', + 'operations': ['nothing']}]} + try: + generate.use_cases_page(data, scratch) + except generate.Fault as fault: + assert 'nothing' in str(fault), fault + else: + raise AssertionError('a use case naming an unknown operation was accepted') + + +def test_an_overload_is_read_in_the_declaration_that_holds_its_text(scratch: Path) -> None: + written(scratch, 'include/webcpp/crypto/over.hpp', ( + 'namespace webcpp::crypto {\n' + '/** Verifies an Ed25519 signature. */\nint verify(span key, int signature);\n' + '/** Verifies a P-256 signature. */\nint verify(p256::basic_public_key const& key);\n}\n')) + plain = {'id': 'ed', 'header': '', 'free': True} + assert generate.declared_brief(scratch, plain, 'verify') == 'Verifies an Ed25519 signature.' + chosen = dict(plain, id='p', overloads={'verify': 'p256::basic_public_key'}) + brief = generate.declared_brief(scratch, chosen, 'verify') + assert brief == 'Verifies a P-256 signature.', brief + missing = dict(plain, id='q', overloads={'verify': 'p384::basic_public_key'}) + try: + generate.declared_brief(scratch, missing, 'verify') + except generate.Fault as fault: + assert 'p384::basic_public_key' in str(fault), fault + else: + raise AssertionError('an overload no declaration holds was given a brief') + + def test_a_measurement_not_built_at_release_is_refused(scratch: Path) -> None: import json written(scratch, 'doc/performance.json', json.dumps(measured(22.5))) @@ -1457,6 +1499,9 @@ def test_a_namespace_table_is_split_into_its_parts(_: Path) -> None: test_every_api_page_lists_its_default_per_target, test_a_use_case_joins_the_operation_it_names, test_a_use_case_that_links_a_teaching_section_joins_the_operation_it_answers, + test_a_use_case_that_lists_its_operations_joins_those_alone, + test_a_use_case_listing_an_unknown_operation_is_a_fault, + test_an_overload_is_read_in_the_declaration_that_holds_its_text, test_a_measurement_not_built_at_release_is_refused, test_a_speed_cell_names_each_operation_and_refuses_an_unknown_backend, test_a_measured_cell_escapes_the_bars_of_its_finding, diff --git a/include/webcpp/crypto/async.hpp b/include/webcpp/crypto/async.hpp index 0d43a545..1330218f 100644 --- a/include/webcpp/crypto/async.hpp +++ b/include/webcpp/crypto/async.hpp @@ -143,10 +143,11 @@ inline constexpr bool asynchronous_backend_v = false; * - `generate(executor, token)`; * - `seal(executor, aead, iv_bytes, additional_data_bytes, data_bytes, token)` and * `open(executor, aead, iv_bytes, additional_data_bytes, data_bytes, tag_bytes, token)`; - * - `sign(executor, key_pair, message, token)`; + * - `sign(executor, key_pair, message, token)`; for P-256 the message itself, which the engine + * hashes with SHA-256, as WebCrypto's ECDSA does; * - `verify(executor, public_key, message, signature, token)` for Ed25519, and * `verify(executor, public_key, message, signature, token)` for P-256, its key P-256's - * `basic_public_key`; + * `basic_public_key` and the message itself, which the engine hashes with SHA-256; * - `agree(executor, secret_key, peer_public_key, token)` for X25519, and * `agree(executor, key_pair, peer_public_key, token)` for P-256, its key pair and its peer's * key P-256's types. diff --git a/test/async_p256_test.cpp b/test/async_p256_test.cpp index e4d9b552..d4150040 100644 --- a/test/async_p256_test.cpp +++ b/test/async_p256_test.cpp @@ -227,6 +227,10 @@ void async_wycheproof_ecdsa(asio::io_context& context) { auto const doc = load("ecdsa_secp256r1_sha256_p1363_test"); int run = 0; for (auto const& group : doc.at("testGroups").as_array()) { + // The groups after the 50th case are not read: their keys are not made. + if (run == wycheproof_cases) { + break; + } auto const key = public_key::make(test::from_hex(str(group.at("publicKey").at("uncompressed")))); if (!BOOST_TEST(key.has_value())) { diff --git a/test/timing_coverage_bearssl_test.cpp b/test/timing_coverage_bearssl_test.cpp index 144dbce4..6161d3ee 100644 --- a/test/timing_coverage_bearssl_test.cpp +++ b/test/timing_coverage_bearssl_test.cpp @@ -21,8 +21,8 @@ // guarded (no BearSSL call): public_key, secret_scalar, uncompressed, encode_spki, encode_pkcs8, // basic_keypair's move constructor and move assignment, and normalize_ecdsa and check_low_s, // which test/timing_test.cpp calls without a backend; and the asynchronous async_make, -// async_generate, async_sign, async_verify and async_agree, each refused once before BearSSL -// too. +// async_generate, async_sign, async_verify and async_agree, all but async_generate (which takes +// no input) also refused once before BearSSL. #include "support/timing_seam.hpp" From 900d4557bc582d7e10d68259179e9a5e2dea7f1d Mon Sep 17 00:00:00 2001 From: R Date: Sun, 22 Nov 2026 07:35:23 -0300 Subject: [PATCH 14/14] crypto: the P-256 asynchronous test's long functions are split into per-case helpers, and its const and trailing-comma lint findings are fixed --- test/async_p256_test.cpp | 271 +++++++++++++++----------- test/timing_coverage_bearssl_test.cpp | 5 +- 2 files changed, 155 insertions(+), 121 deletions(-) diff --git a/test/async_p256_test.cpp b/test/async_p256_test.cpp index d4150040..2a30b113 100644 --- a/test/async_p256_test.cpp +++ b/test/async_p256_test.cpp @@ -194,9 +194,10 @@ void async_rfc6979(asio::io_context& context) { return; } BOOST_TEST(own->uncompressed() == data::rfc6979_public); - for (auto const& [text, expected] : - {std::pair{std::string_view("sample"), data::rfc6979_sample}, - std::pair{std::string_view("test"), data::rfc6979_test}}) { + for (auto const& [text, expected] : { + std::pair{std::string_view("sample"), data::rfc6979_sample}, + std::pair{std::string_view("test"), data::rfc6979_test}, + }) { auto const message = bytes_of(text); auto const signed_async = sign_async(context, *key, message); BOOST_TEST(!signed_async.code); @@ -223,6 +224,46 @@ std::string str(json::value const& v) { return std::string(std::string_view(v.as_string())); } +// One valid case: the synchronous and the asynchronous verification accept it, and both refuse +// the message with a changed byte. +void check_wycheproof_ecdsa_case(asio::io_context& context, public_key const& key, + json::value const& t) { + auto message = test::from_hex(str(t.at("msg"))); + auto const encoded = test::from_hex(str(t.at("sig"))); + if (!BOOST_TEST_EQ(encoded.size(), p256::signature_size)) { + return; + } + std::span const signature(encoded.data(), + encoded.size()); + auto const verified_sync = p256::verify_ecdsa(signature, sha256(message), key); + BOOST_TEST(verified_sync.has_value()); + BOOST_TEST(!verify_async(context, key, message, encoded)); + // A changed byte of the message: both refuse it. + message.push_back(0); + message.front() ^= 1U; + BOOST_TEST(p256::verify_ecdsa(signature, sha256(message), key).error() == + crypto::error::invalid_signature); + BOOST_TEST(verify_async(context, key, message, encoded) == crypto::error::invalid_signature); +} + +void async_wycheproof_ecdsa_group(asio::io_context& context, json::value const& group, int& run) { + auto const key = + public_key::make(test::from_hex(str(group.at("publicKey").at("uncompressed")))); + if (!BOOST_TEST(key.has_value())) { + return; + } + for (auto const& t : group.at("tests").as_array()) { + if (run == wycheproof_cases) { + break; + } + if (str(t.at("result")) != "valid") { + continue; + } + ++run; + check_wycheproof_ecdsa_case(context, *key, t); + } +} + void async_wycheproof_ecdsa(asio::io_context& context) { auto const doc = load("ecdsa_secp256r1_sha256_p1363_test"); int run = 0; @@ -231,37 +272,7 @@ void async_wycheproof_ecdsa(asio::io_context& context) { if (run == wycheproof_cases) { break; } - auto const key = - public_key::make(test::from_hex(str(group.at("publicKey").at("uncompressed")))); - if (!BOOST_TEST(key.has_value())) { - continue; - } - for (auto const& t : group.at("tests").as_array()) { - if (run == wycheproof_cases) { - break; - } - if (str(t.at("result")) != "valid") { - continue; - } - ++run; - auto message = test::from_hex(str(t.at("msg"))); - auto const encoded = test::from_hex(str(t.at("sig"))); - if (!BOOST_TEST_EQ(encoded.size(), p256::signature_size)) { - continue; - } - std::span const signature(encoded.data(), - encoded.size()); - auto const verified_sync = p256::verify_ecdsa(signature, sha256(message), *key); - BOOST_TEST(verified_sync.has_value()); - BOOST_TEST(!verify_async(context, *key, message, encoded)); - // A changed byte of the message: both refuse it. - message.push_back(0); - message.front() ^= 1U; - BOOST_TEST(p256::verify_ecdsa(signature, sha256(message), *key).error() == - crypto::error::invalid_signature); - BOOST_TEST(verify_async(context, *key, message, encoded) == - crypto::error::invalid_signature); - } + async_wycheproof_ecdsa_group(context, group, run); } BOOST_TEST_EQ(run, wycheproof_cases); std::cout << "ecdsa_secp256r1_sha256_p1363_test: async_verified=" << run << '\n'; @@ -282,6 +293,31 @@ std::optional> scalar_bytes( return padded; } +// One valid case: the key made asynchronously agrees with the peer's key as the vector says and +// as the synchronous key does. +void check_wycheproof_ecdh_case(asio::io_context& context, json::value const& t) { + auto const scalar = scalar_bytes(test::from_hex(str(t.at("private")))); + auto const peer = public_key::make(test::from_hex(str(t.at("public")))); + auto const shared = test::from_hex(str(t.at("shared"))); + if (!BOOST_TEST(scalar.has_value()) || !BOOST_TEST(peer.has_value())) { + return; + } + auto const key = made_async(context, *scalar); + auto const synchronous = keypair::make(*scalar); + if (!BOOST_TEST(key.has_value()) || !BOOST_TEST(synchronous.has_value())) { + return; + } + auto const agreed_sync = synchronous->ecdh_x(*peer); + auto const agreed = agree_async(context, *key, *peer); + BOOST_TEST(!agreed.code); + if (!BOOST_TEST(agreed.value.has_value()) || !BOOST_TEST(agreed_sync.has_value())) { + return; + } + auto const bytes = std::get<0>(*agreed.value).bytes(); + BOOST_TEST(std::ranges::equal(bytes, shared)); + BOOST_TEST(std::ranges::equal(bytes, agreed_sync->bytes())); +} + void async_wycheproof_ecdh(asio::io_context& context) { auto const doc = load("ecdh_secp256r1_ecpoint_test"); int run = 0; @@ -294,26 +330,7 @@ void async_wycheproof_ecdh(asio::io_context& context) { continue; } ++run; - auto const scalar = scalar_bytes(test::from_hex(str(t.at("private")))); - auto const peer = public_key::make(test::from_hex(str(t.at("public")))); - auto const shared = test::from_hex(str(t.at("shared"))); - if (!BOOST_TEST(scalar.has_value()) || !BOOST_TEST(peer.has_value())) { - continue; - } - auto const key = made_async(context, *scalar); - auto const synchronous = keypair::make(*scalar); - if (!BOOST_TEST(key.has_value()) || !BOOST_TEST(synchronous.has_value())) { - continue; - } - auto const agreed_sync = synchronous->ecdh_x(*peer); - auto const agreed = agree_async(context, *key, *peer); - BOOST_TEST(!agreed.code); - if (!BOOST_TEST(agreed.value.has_value()) || !BOOST_TEST(agreed_sync.has_value())) { - continue; - } - auto const bytes = std::get<0>(*agreed.value).bytes(); - BOOST_TEST(std::ranges::equal(bytes, shared)); - BOOST_TEST(std::ranges::equal(bytes, agreed_sync->bytes())); + check_wycheproof_ecdh_case(context, t); } } BOOST_TEST_EQ(run, wycheproof_cases); @@ -374,39 +391,48 @@ void async_generate(asio::io_context& context) { generated(context); } +// A key made from a refused scalar is the empty object a move leaves: every member says +// invalid_state, and the asynchronous functions complete with it and a zeroed value. +void check_empty_keypair(asio::io_context& context, keypair const& empty, public_key const& peer, + std::span message) { + BOOST_TEST(empty.public_key().error() == crypto::error::invalid_state); + BOOST_TEST(empty.secret_scalar().error() == crypto::error::invalid_state); + BOOST_TEST(empty.sign_ecdsa(sha256(message)).error() == crypto::error::invalid_state); + BOOST_TEST(empty.ecdh_x(peer).error() == crypto::error::invalid_state); + auto const signed_empty = sign_async(context, empty, message); + BOOST_TEST(signed_empty.code == crypto::error::invalid_state); + if (BOOST_TEST(signed_empty.value.has_value())) { + BOOST_TEST(all_zero(std::get<0>(*signed_empty.value))); + } + auto const agreed_empty = agree_async(context, empty, peer); + BOOST_TEST(agreed_empty.code == crypto::error::invalid_state); + if (BOOST_TEST(agreed_empty.value.has_value())) { + BOOST_TEST(all_zero(std::get<0>(*agreed_empty.value).bytes())); + } +} + +void check_make_refused(asio::io_context& context, public_key const& peer, + std::span message, std::span scalar, + crypto::error expected) { + auto const made = complete(context, [&](auto const& executor, auto&& token) { + return crypto::async_make(executor, scalar, std::forward(token)); + }); + BOOST_TEST(made.code == expected); + if (!BOOST_TEST(made.value.has_value())) { + return; + } + check_empty_keypair(context, std::get<0>(*made.value), peer, message); +} + void async_make_refused(asio::io_context& context) { auto const peer = public_key::make(data::rfc6979_public); if (!BOOST_TEST(peer.has_value())) { return; } std::array const message{1, 2, 3}; - auto const refused = [&](std::span scalar, crypto::error expected) { - auto const made = complete(context, [&](auto const& executor, auto&& token) { - return crypto::async_make(executor, scalar, - std::forward(token)); - }); - BOOST_TEST(made.code == expected); - if (!BOOST_TEST(made.value.has_value())) { - return; - } - auto const& empty = std::get<0>(*made.value); - BOOST_TEST(empty.public_key().error() == crypto::error::invalid_state); - BOOST_TEST(empty.secret_scalar().error() == crypto::error::invalid_state); - BOOST_TEST(empty.sign_ecdsa(sha256(message)).error() == crypto::error::invalid_state); - BOOST_TEST(empty.ecdh_x(*peer).error() == crypto::error::invalid_state); - auto const signed_empty = sign_async(context, empty, message); - BOOST_TEST(signed_empty.code == crypto::error::invalid_state); - if (BOOST_TEST(signed_empty.value.has_value())) { - BOOST_TEST(all_zero(std::get<0>(*signed_empty.value))); - } - auto const agreed_empty = agree_async(context, empty, *peer); - BOOST_TEST(agreed_empty.code == crypto::error::invalid_state); - if (BOOST_TEST(agreed_empty.value.has_value())) { - BOOST_TEST(all_zero(std::get<0>(*agreed_empty.value).bytes())); - } - }; - refused(std::span(data::rfc6979_scalar).first(31), crypto::error::invalid_key_size); - refused(data::order, crypto::error::invalid_secret_key); + check_make_refused(context, *peer, message, std::span(data::rfc6979_scalar).first(31), + crypto::error::invalid_key_size); + check_make_refused(context, *peer, message, data::order, crypto::error::invalid_secret_key); } void async_destroyed(asio::io_context& context) { @@ -418,7 +444,7 @@ void async_destroyed(asio::io_context& context) { { auto key = std::make_unique(*keypair::make(data::rfc6979_scalar)); auto message = std::make_unique>(bytes_of("sample")); - auto peer = std::make_unique(*public_key::make(data::rfc6979_public)); + auto const peer = std::make_unique(*public_key::make(data::rfc6979_public)); auto const agreed_sync = key->ecdh_x(*peer); if (!BOOST_TEST(agreed_sync.has_value())) { return; @@ -444,45 +470,52 @@ void async_destroyed(asio::io_context& context) { BOOST_TEST(shared == expected_shared); } +// The second half of the coroutine: a generated key agrees with the first one's. +asio::awaitable coroutine_agreement(asio::any_io_executor const& executor, + p256::keypair const& key, public_key const& own, + bool& done) { + auto generate_result = co_await crypto::async_generate( + executor, asio::as_tuple(asio::use_awaitable)); + auto& [generate_code, peer_key] = generate_result; + BOOST_TEST(!generate_code); + auto const peer = peer_key.public_key(); + if (!BOOST_TEST(peer.has_value())) { + co_return; + } + auto agree_result = + co_await crypto::async_agree(executor, key, *peer, asio::as_tuple(asio::use_awaitable)); + auto& [agree_code, shared] = agree_result; + BOOST_TEST(!agree_code); + auto const back = peer_key.ecdh_x(own); + BOOST_TEST(back.has_value() && std::ranges::equal(shared.bytes(), back->bytes())); + done = true; +} + +asio::awaitable coroutine_body(bool& done) { + auto const executor = co_await asio::this_coro::executor; + auto const message = bytes_of("test"); + auto made_result = co_await crypto::async_make( + executor, data::rfc6979_scalar, asio::as_tuple(asio::use_awaitable)); + auto& [made_code, key] = made_result; + BOOST_TEST(!made_code); + auto [sign_code, signature] = + co_await crypto::async_sign(executor, key, message, asio::as_tuple(asio::use_awaitable)); + BOOST_TEST(!sign_code); + BOOST_TEST(signature == data::rfc6979_test); + auto const own = key.public_key(); + if (!BOOST_TEST(own.has_value())) { + co_return; + } + auto [verify_code] = co_await crypto::async_verify(executor, *own, message, signature, + asio::as_tuple(asio::use_awaitable)); + BOOST_TEST(!verify_code); + co_await coroutine_agreement(executor, key, *own, done); +} + void async_coroutine(asio::io_context& context) { bool done = false; - asio::co_spawn( - context, - [&]() -> asio::awaitable { - auto const executor = co_await asio::this_coro::executor; - auto const message = bytes_of("test"); - auto made_result = co_await crypto::async_make( - executor, data::rfc6979_scalar, asio::as_tuple(asio::use_awaitable)); - auto& [made_code, key] = made_result; - BOOST_TEST(!made_code); - auto [sign_code, signature] = co_await crypto::async_sign( - executor, key, message, asio::as_tuple(asio::use_awaitable)); - BOOST_TEST(!sign_code); - BOOST_TEST(signature == data::rfc6979_test); - auto const own = key.public_key(); - if (!BOOST_TEST(own.has_value())) { - co_return; - } - auto [verify_code] = co_await crypto::async_verify(executor, *own, message, signature, - asio::as_tuple(asio::use_awaitable)); - BOOST_TEST(!verify_code); - auto generate_result = co_await crypto::async_generate( - executor, asio::as_tuple(asio::use_awaitable)); - auto& [generate_code, peer_key] = generate_result; - BOOST_TEST(!generate_code); - auto const peer = peer_key.public_key(); - if (!BOOST_TEST(peer.has_value())) { - co_return; - } - auto agree_result = co_await crypto::async_agree(executor, key, *peer, - asio::as_tuple(asio::use_awaitable)); - auto& [agree_code, shared] = agree_result; - BOOST_TEST(!agree_code); - auto const back = peer_key.ecdh_x(*own); - BOOST_TEST(back.has_value() && std::ranges::equal(shared.bytes(), back->bytes())); - done = true; - }, - [](std::exception_ptr const& failure) { BOOST_TEST(!failure); }); + asio::co_spawn(context, coroutine_body(done), + [](std::exception_ptr const& failure) { BOOST_TEST(!failure); }); context.restart(); context.run(); // lint-run: the test's event loop BOOST_TEST(done); diff --git a/test/timing_coverage_bearssl_test.cpp b/test/timing_coverage_bearssl_test.cpp index 6161d3ee..c19ceaed 100644 --- a/test/timing_coverage_bearssl_test.cpp +++ b/test/timing_coverage_bearssl_test.cpp @@ -282,8 +282,9 @@ void cover_async_p256() { std::array const message{1, 2, 3}; int completions = 0; signature_type kept{}; - webcpp::test::async_completion_counter const counted{.completions = - &completions}; + webcpp::test::async_completion_counter const counted{ + .completions = &completions, + }; webcpp::test::async_completion_counter const keeping{ .completions = &completions, .tag = &kept,