diff --git a/README.md b/README.md index 24acaa5..a33763e 100644 --- a/README.md +++ b/README.md @@ -61,6 +61,7 @@ tag is placed. | crypto | [formats](libraries/crypto/openspec/changes/formats) | crypto: one encode and one decode for every key and signature format, the format as a value | wrapper | implementing | | 2026-11-22 | [code](https://github.com/webcpporg/crypto) | | crypto | [hpke](libraries/crypto/openspec/changes/hpke) | crypto: HPKE (RFC 9180) composed from crypto's own primitives, readable names, the mode from the arguments | wrapper | implementing | | 2026-11-23 | [code](https://github.com/webcpporg/crypto) | | crypto | [one-verb](libraries/crypto/openspec/changes/one-verb) | crypto: codecs' verbs are crypto's: crypto::encode and crypto::decode removed, the check declared to codecs, PEM on a fixed label and decoded in place | wrapper | implementing | | 2026-12-02 | [code](https://github.com/webcpporg/crypto) | +| crypto | [primitives](libraries/crypto/openspec/changes/primitives) | crypto: RFC 8439's raw ChaCha20 and Poly1305 as building blocks: the stream cipher on libsodium, BearSSL and OpenSSL, the single-use key authenticator on libsodium and OpenSSL | wrapper | implementing | | 2026-11-23 | [code](https://github.com/webcpporg/crypto) | | crypto | [rfc9001-tests](libraries/crypto/openspec/changes/rfc9001-tests) | crypto: RFC 9001 Appendix A's QUIC packet protection vectors as interop tests, on every AES-GCM backend, no QUIC API | wrapper | implementing | | 2026-12-01 | [code](https://github.com/webcpporg/crypto) | | crypto | [unified-sign](libraries/crypto/openspec/changes/unified-sign) | crypto: one sign and verify on every curve, the scheme always named, the key pair contract and four forms of each operation | wrapper | implementing | | 2026-11-22 | [code](https://github.com/webcpporg/crypto) | | crypto | [uniform-types](libraries/crypto/openspec/changes/uniform-types) | crypto: typed signatures, typed X25519 keys, and concepts for key pairs, AEADs and boxes | wrapper | implementing | | 2026-11-22 | [code](https://github.com/webcpporg/crypto) | diff --git a/libraries/crypto/openspec/changes/primitives/.openspec.yaml b/libraries/crypto/openspec/changes/primitives/.openspec.yaml new file mode 100644 index 0000000..3329dc5 --- /dev/null +++ b/libraries/crypto/openspec/changes/primitives/.openspec.yaml @@ -0,0 +1,11 @@ +schema: spec-driven +created: 2026-11-30 +webcpp: + library: crypto + title: "crypto: RFC 8439's raw ChaCha20 and Poly1305 as building blocks: the stream cipher on libsodium, BearSSL and OpenSSL, the single-use key authenticator on libsodium and OpenSSL" + kind: wrapper + port_of: null + status: implementing + release: null + implementation: https://github.com/webcpporg/crypto + decided: 2026-11-23 diff --git a/libraries/crypto/openspec/changes/primitives/design.md b/libraries/crypto/openspec/changes/primitives/design.md new file mode 100644 index 0000000..5428c99 --- /dev/null +++ b/libraries/crypto/openspec/changes/primitives/design.md @@ -0,0 +1,1054 @@ +## Open questions for the owner + +None: the owner answered the one question of the first draft (where the stream cipher's concept +and its free forms live) on 2026-11-30, owner decision 5, and added RFC 8439's raw Poly1305 and +named its purpose namespace on 2026-12-01, owner decision 6, and the same day freed the stream +cipher's concept from ChaCha20's shape, owner decision 7. + +## Context + +This change builds on what crypto's `main` will hold when it starts, all merged before it: + +- **crypto/uniform-types** (on `main`): the AEAD contract `secret_key_encryption::aead::cipher` + and its free forms, the boxes' `authenticated_box`, the factories named by their input + (`from_key`, `crypto::from_key`), the names of owner decision 14 of 2026-11-23 + (`ciphers::aead` renamed `ciphers::basic_chacha20_poly1305`, `iv` renamed + `nonce`, `associated_data`, `secret_key_encryption::aead`). +- **crypto's asynchronous family, part A** (on `main`): ``, the four forms + of every cheap operation (unified-sign's D9: member and free, synchronous and asynchronous), + each asynchronous member declared in its class and defined in `async.hpp`, completing by a post + to the caller's executor on a synchronous backend (`detail::complete_by_post`); the browser's + backend of part B not built yet, `detail::asynchronous_backend_v` false for every shipped + backend, and every construction WebCrypto lacks refused on a backend for which it is true + (`detail::refuse_aead_on_asynchronous_backend`, foundation D6). +- **crypto/data-independent-timing and webcpp::secure** (on `main`): `secure::timing_guard` as the + first statement of every public function that calls a backend, each backend's + `test/timing_coverage__test.cpp`, `secure::erase_secret`, `secure::secret`, + `secure::declassify`. +- **crypto/formats** (implementing now): `crypto::formats`, `crypto::signing_schemes`, + `crypto::verification_policies`, the typed `secp256k1::xonly_public_key`, and crypto's + dependency on webcpp::codecs (its R32). This change uses none of its interfaces but codecs' + base64 in one test, and starts from its merged head. +- **codecs' Q1 and crypto/hpke** (queued before this change): hpke adds + `error::message_limit_reached = 21`; neither touches ChaCha20 (see "The queue"). + +ChaCha20 as it is on crypto's `main`: inside `ciphers::basic_chacha20_poly1305` alone +(``, the aliases in `ciphers/chacha20_poly1305.hpp`), the family +`chacha20_poly1305` on libsodium (`crypto_aead_chacha20poly1305_ietf_*_detached`, the default on +every target), BearSSL (`br_poly1305_ctmul_run` or `ctmulq`, given `br_chacha20_ct_run` or its SSE2 +code, `detail::bearssl_chacha20()`) and OpenSSL (`EVP_CIPHER` "ChaCha20-Poly1305", native, wasip2 +and wasip3), refused on ctaes and secp256k1 by the generated `WEBCPP_CRYPTO_DETAIL_REFUSE_*` +macros. Each backend's engine is `detail::aead_state` and `detail::aead_engine` (`init`, `seal`, `open`, `move`, `reset`), declared in `detail/engines.hpp`. The three +backends' raw ChaCha20 differ where its 32-bit block counter ends: libsodium's +`crypto_stream_chacha20_ietf_xor_ic` calls `sodium_misuse()`, which aborts the program, when the +initial counter is above 2^32 minus the message's blocks (`stream_chacha20.c`); BearSSL's +`br_chacha20_ct_run` wraps the counter silently to 0 (`chacha20_ct.c`); OpenSSL's provider carries +it into the nonce's first word (`cipher_chacha20_hw.c`). + +Poly1305 as it is on crypto's `main`: inside the AEADs and boxes alone, never reachable by itself. +The three backends' raw Poly1305 differ in what they offer: libsodium has the one-time +authenticator itself, `crypto_onetimeauth_poly1305(out, in, inlen, key)` with the 32-byte key +r || s (`onetimeauth_poly1305.c`); OpenSSL has it as the `EVP_MAC` "POLY1305" (a provider MAC on +native, wasip2 and wasip3, the key given to `EVP_MAC_init`, a 16-byte output); BearSSL has +Poly1305 only inside its AEAD, `br_poly1305_ctmul_run`, which derives the one-time key from +ChaCha20's block 0 itself and so cannot authenticate under a caller's key. webcpp::hash's +`hash::mac` (``) computes HMAC, KMAC, SipHash and BLAKE2's keyed tags, whose +keys are reusable; a program compares a tag with `secure::constant_time_equal`. + +## Intent + +A protocol that fixes its own construction reads as the protocol does: + +```cpp +namespace ciphers = webcpp::crypto::ciphers; +namespace unauthenticated_encryption = webcpp::crypto::unauthenticated_encryption; + +// NIP-44 version 2's encryption, keys from HKDF, ChaCha20 from block 0 (in a program, not in crypto). +auto cipher = ciphers::chacha20<>::from_key(chacha_key.bytes()); // a secure::secret<32>'s bytes, or 32 bytes +auto const sealed = cipher->apply_keystream(chacha_nonce, padded, 0); // padded is ciphertext after +auto const same = unauthenticated_encryption::apply_keystream(*cipher, chacha_nonce, padded, 0); // decrypts it again +``` + +Four properties motivate it: a protocol's bytes (the keystream from the counter it names, with no +tag), one contract on every backend (the same bytes, the same refusals, no abort and no silent +wrap where the counter ends), crypto's conventions (a type per algorithm, its backend a template +parameter, `result<>` errors, the key wiped, the timing guard, the four forms), and no misuse +dressed as safety: the guide says that ChaCha20 authenticates nothing and that a program wants +`chacha20_poly1305` unless its protocol fixes another construction. + +A protocol that authenticates with Poly1305 under a key it derives for one message reads the same +way (owner decision 6): + +```cpp +namespace authenticators = webcpp::crypto::authenticators; +namespace single_use_key_authentication = webcpp::crypto::single_use_key_authentication; + +// A one-time key r || s, derived for this message alone (e.g. ChaCha20's block 0, as +// chacha20-poly1305@openssh.com derives it); never used for a second message. +auto const tag = authenticators::poly1305<>::authenticate(one_time_key, ciphertext); // result> +auto const same = single_use_key_authentication::authenticate>(one_time_key, ciphertext); +auto const checked = single_use_key_authentication::verify>( + one_time_key, ciphertext, received_tag); // authentication_failed on a mismatch +``` + +## Goals / Non-Goals + +**Goals:** RFC 8439 section 2.4's ChaCha20 with a caller's initial block counter, in place; one +type over libsodium, BearSSL and OpenSSL, libsodium the default on every target; a concept every +stream cipher satisfies and its free form; the counter's end refused before any backend runs, with +an error of its own; the four forms, the asynchronous ones on a native backend, every form refused +at compile time on a backend that completes by itself; the timing guard, the constant-time lane, +dudect, no heap; RFC 8439's vectors, the backends' agreement and NIP-44 version 2's end-to-end +vectors. RFC 8439 section 2.5's Poly1305 (owner decision 6): one type over libsodium (the +default) and OpenSSL, refused at compile time on BearSSL, ctaes, secp256k1 and the browser; a purpose +namespace whose name warns that the key is used once, its concept and its free forms, the four +forms; the tag compared in constant time; the same guard, constant-time and heap rules; RFC 8439's +section 2.5.2 and Appendix A.3 vectors and the backends' agreement; a test that composes RFC 8439 +section 2.8's AEAD from the two raw pieces and finds `chacha20_poly1305`'s bytes, across every +backend combination (D17). + +**Non-goals:** NIP-44 itself (its padding, its HMAC, its payload, its key derivation stay in a +program or a later Nostr library; the tests compose it only to prove the cipher); the original +ChaCha20 (8-byte nonce, 64-bit counter), XChaCha20 and HChaCha20, Salsa20 and XSalsa20 (each joins +as a family when a consumer needs it, R1); a keystream that continues across calls at a byte +offset, and a separate output span (R4); AES-CTR or another stream mode of the +block cipher (AES-CTR is the motivating future consumer of the concept's shape, owner decision 7, +queued as a later crypto change); a WebCrypto implementation (WebCrypto has no ChaCha20 and no Poly1305). For +Poly1305 (owner decision 6): GMAC, Poly1305-AES, UMAC and VMAC, GHASH and POLYVAL; FSChaCha20 and +BIP 324's packet cipher (they belong to a future webcpp::bitcoin); HOTP and TOTP, the one-time +passwords; an incremental Poly1305 (init, update, final) and a keyed Poly1305 object (R21). + +**Anti-goals:** a default initial counter the reader cannot see at the call (R2); a counter that +wraps, carries or aborts; anything that presents the raw cipher as authenticated encryption; a +Poly1305 key that an object keeps and a second message could reuse (R21); a tag compared with +`==`. + +## Approaches + +**A. Only an AEAD option** (`chacha20_poly1305` with a flag that skips the tag). The AEAD derives +its Poly1305 key from block 0 and encrypts from block 1, so its keystream is not NIP-44's from +block 0 under the same key, and a flag that drops authentication on an AEAD is the misuse this +library avoids. Rejected. + +**B. A free function only, `chacha20_xor(key, nonce, counter, data)`.** It reads well for one call +but holds no key across calls (BearSSL and libsodium take the key per call, OpenSSL keys a context +once), has no backend parameter, and breaks the shape of every other cipher (a type, `from_key`, a +keyed object, its members). Rejected. + +**C. A type per backend function, as libsodium spells it (`chacha20_ietf_xor_ic`).** Not spelled +out, and a name per counter width. Rejected. + +**D (chosen).** A type `ciphers::basic_chacha20` shaped as +`basic_chacha20_poly1305` (owner, 2026-11-23): `from_key`, `apply_keystream(nonce, data, +initial_counter)`, a concept `stream_cipher` and its free form, the four forms, three backends. + +For Poly1305 (owner decision 6): **E. A tag of `hash::macs`, beside HMAC**, rejected: `hash::mac`'s +keys are reusable, and a one-time key among them would read as one more MAC. **F (chosen).** An +algorithm type `authenticators::poly1305` with static members, in a purpose namespace +whose name says the key is used once, `single_use_key_authentication`. + +## Owner decisions (2026-11-23 to 2026-12-01, binding) + +1. **A small change "primitives" after formats (2026-11-23)**: `ciphers::basic_chacha20` and + `ciphers::chacha20`, RFC 8439's raw stream cipher; the factory `from_key`; + `apply_keystream(nonce12, data, initial_counter)`; a concept `stream_cipher`, not an AEAD; a + counter overflow error; the backends libsodium, OpenSSL and BearSSL; native only where the + browser's backend is concerned; RFC 8439's and NIP-44's end-to-end vectors, NIP-44 itself + staying out of crypto. +2. **The x-only key leaves this change (2026-11-24)**: the typed `secp256k1::xonly_public_key` + moves into crypto's `formats` change (its task 2.6); this change keeps the raw ChaCha20 alone. +3. **The final names of 2026-11-23** (owner decision 14 and the renames of uniform-types): + `ciphers::basic_chacha20_poly1305`, `secret_key_encryption::aead`, `nonce`, + `associated_data`, factories named by their input; this design follows them (`from_key`, + `nonce_bytes`, no `iv`). +4. **The queue (2026-11-30)**: codecs, formats, codecs' Q1, hpke, primitives, backend-concepts, + part B, the owner's pause. +5. **A purpose namespace of its own, `crypto::unauthenticated_encryption` (2026-11-30, answering + the first draft's Q1; the owner's words: "Vamos de unauthenticated_encryption").** Neither + `secret_key_encryption` nor `ciphers`: a new namespace, sibling of `secret_key_encryption` and + `public_key_encryption`, holds the concept `unauthenticated_encryption::stream_cipher` and the + free forms `unauthenticated_encryption::apply_keystream(cipher, ...)` and + `unauthenticated_encryption::async_apply_keystream(executor, cipher, ...)`, in + `` (the asynchronous one in + `async.hpp`). The type stays `ciphers::basic_chacha20` and `ciphers::chacha20`. + The reasons: uniform-types' owner decision 13 names a namespace by what its contract is for; + `secret_key_encryption` keeps its promise that what it holds encrypts and authenticates; + `ciphers` stays the algorithms alone; the namespace's name itself warns the reader. The name + `stream_encryption` is deliberately left free for a future authenticated chunked construction + (libsodium's secretstream, the STREAM construction). The namespace has a page of its own in the + guide, which says when to use it (a protocol that brings its own authentication, as NIP-44 with + its HMAC) and points to `secret_key_encryption` as the normal path. The AES block cipher stays in + `ciphers`, untouched. +6. **RFC 8439's raw Poly1305 joins this change, in a purpose namespace of its own, + `crypto::single_use_key_authentication` (2026-12-01; the owner's words: "Prefiro + single_use_key_authentication").** Poly1305, the one-time authenticator of RFC 8439 section 2.5 + (a 32-byte one-time key r || s, a 16-byte tag), lives in crypto, not in `hash::mac`, because its + key must never be reused while HMAC's and KMAC's keys are reusable; the purpose namespace's name + carries that warning. The owner chose `single_use_key_authentication` over + `one_time_authentication`, which a reader would confuse with the one-time passwords HOTP and + TOTP. The namespace holds the concept `single_use_key_authenticator` and the free forms + `authenticate(key, message) -> result` and `verify(key, message, tag) -> result<>` + (the tag compared in constant time through `secure::constant_time_equal`, a mismatch an error), + and the asynchronous forms `async_authenticate` and `async_verify` in `async.hpp`, after crypto's + four forms as closely as the shape allows: there is no keyed object, the key enters every call, + deliberately, and there is no `from_key`. The algorithm type is + `crypto::authenticators::poly1305`, `key_size` 32, `tag_size` 16. + The backends: libsodium's `crypto_onetimeauth_poly1305` (the default) and OpenSSL's `EVP_MAC` + "POLY1305"; BearSSL refused at compile time (it has Poly1305 only inside its AEAD, + `br_poly1305_ctmul_run`, which derives the key itself), ctaes and secp256k1 refused as ChaCha20 + is, the browser's backend refused at compile time (WebCrypto has no Poly1305). ChaCha20's + conventions hold: the timing guard first, the key wiped where crypto holds a copy, no heap, + `noexcept`, the constant-time lane and dudect, the timing coverage per backend, RFC 8439's + section 2.5.2 and Appendix A.3 vectors, the backends' agreement. The guide has a page for the + namespace: the key is used once; for a reusable key, `hash::mac` (HMAC); for one-time passwords + (HOTP, TOTP), not this. Non-goals: GMAC, Poly1305-AES, UMAC and VMAC, GHASH and POLYVAL, + FSChaCha20 (a future webcpp::bitcoin's), HOTP and TOTP; there will be no webcpp::otp, and the + page says only that HOTP and TOTP are not what this namespace does, pointing to no library. The + same day the owner added a composition test (the owner's words: "Então vamos colocar, tanto + chacha cru, quanto o teste de composição"): RFC 8439 section 2.8's AEAD built in a test from the + raw ChaCha20 and Poly1305 this change adds, its ciphertext and tag equal byte for byte to + `ciphers::chacha20_poly1305`'s (D17); a test only, the AEAD keeps its backends' combined + functions (R27). The owner then made it the full cross-backend matrix (the owner's words: "Pode + virar sim a matriz"): the raw ChaCha20 on libsodium, BearSSL and OpenSSL, times Poly1305 on + libsodium and OpenSSL, times ChaCha20-Poly1305 on libsodium, BearSSL and OpenSSL, 18 + combinations in one type-parameterised test, a failure naming its combination; BearSSL joins + through its raw ChaCha20 and its AEAD. The budget grows by about 6 hours for Poly1305 and under + one for the composition test, to about 24 in all. +7. **The stream cipher's concept reads the algorithm's own shape (2026-12-01; the owner's words: + "Pode ser, ajusta já o concept").** The concept `unauthenticated_encryption::stream_cipher` and + its free forms `apply_keystream` and `async_apply_keystream` are not fixed to ChaCha20's shape + (a 12-byte nonce, a 64-byte block, a 32-bit block counter): they read the algorithm's own + `Cipher::nonce_size`, `Cipher::block_size` and `Cipher::counter_type`, the names + `basic_chacha20` already exposes and that follow crypto's convention for an AEAD's + `key_size`, `nonce_size` and `tag_size`. The counter's end is computed from the algorithm's + counter width and block size by one helper of the concept's header, + `detail::counter_overflows(data_size, initial_counter)`, which every stream cipher's + `apply_keystream` calls, so that the refusal stays `counter_overflow`, before any backend runs + (D2, D3, R28). The motivating future consumer is AES-CTR (`ciphers::aes128_ctr` and + `ciphers::aes256_ctr` over `detail::basic_aes_ctr`: a 16-byte counter block that + protocols split differently between nonce and counter, a 16-byte block), queued as a later crypto + change with ML-KEM-768 and P-384/P-521, not implemented here; the original ChaCha20 (an 8-byte + nonce, a 64-bit counter) and XChaCha20 (a 24-byte nonce) would fit the same way. ChaCha20 keeps + exactly its API and behaviour (nonce 12, block 64, `std::uint32_t` counter). A test-only stand-in + stream cipher of another nonce size, block size and counter type proves at compile time that it + satisfies the concept, and that the free forms and the counter's refusal work for it + (`stream_cipher_shape_test`, D9). The budget grows by under one hour, to about 25 in all. + +The standing rules of every library apply (the owner's, recorded in the workspace and in the +guidelines): a library builds without exceptions and may throw where they are available (no +blanket no-throw rule; ChaCha20 allocates nothing and its functions are `noexcept`); public names +are spelled out, an algorithm's proper name staying as it is (`chacha20`); no two-word naming +rule; MSVC verification is 14.3 and 14.5 x64 debug, plus arm64 on 14.5 for the DIT and timing +tests only; a fix round verifies scoped (the affected tests on one lane and the lint; a special +lane only when its subject changed), every lane runs on a task's first implementation and on the +final head; sizes and speed are measured on release builds only; every new secret operation holds +`secure::timing_guard`; every defect a lane shows is fixed, nothing goes to known failures. + +## Decisions + +### D1. The family and the types + +```cpp +// +namespace webcpp::crypto::families { +struct chacha20 { // forward-declared by the generated table + static constexpr std::size_t key_size = 32; + static constexpr std::size_t nonce_size = 12; // RFC 8439 section 2.3 + static constexpr std::size_t block_size = 64; + using counter_type = std::uint32_t; // RFC 8439's 32-bit block counter + static constexpr std::uint64_t max_message_size = std::uint64_t{1} << 38U; // 2^32 blocks from counter 0 +}; +} +namespace webcpp::crypto::ciphers { +template +class basic_chacha20 { +public: + using backend_type = Backend; + using family_type = Family; // the capability table's family + using name_type = Family; + using counter_type = typename Family::counter_type; + static constexpr std::size_t key_size = Family::key_size; + static constexpr std::size_t nonce_size = Family::nonce_size; + static constexpr std::size_t block_size = Family::block_size; + static constexpr std::uint64_t max_message_size = Family::max_message_size; + + [[nodiscard]] static boost::system::result from_key(std::span key_bytes) noexcept; + template + static auto async_from_key(Executor const&, std::span key_bytes, CompletionToken&&); + + [[nodiscard]] boost::system::result apply_keystream(std::span nonce_bytes, + std::span data_bytes, + counter_type initial_counter) noexcept; + template + auto async_apply_keystream(Executor const&, std::span nonce_bytes, + std::span data_bytes, counter_type initial_counter, CompletionToken&&); + + basic_chacha20(basic_chacha20&&) noexcept; // the source wiped and empty + basic_chacha20& operator=(basic_chacha20&&) noexcept; + basic_chacha20(basic_chacha20 const&) = delete; + basic_chacha20& operator=(basic_chacha20 const&) = delete; + ~basic_chacha20(); // wipes the key +private: + friend struct detail::async_access; + basic_chacha20() noexcept = default; + detail::stream_state state_{}; + bool keyed_ = false; +}; +} +// +namespace webcpp::crypto::ciphers { +template > +using chacha20 = basic_chacha20; +} +``` + +`basic_chacha20` refuses a `Family` that is no stream family first, in one `static_assert` +("ciphers::basic_chacha20 takes a stream family: families::chacha20"), with placeholder sizes +after it (`detail::stream_sizes`), as `basic_chacha20_poly1305` does. +`ciphers/stream_cipher.hpp` holds the family's definition, `detail::stream_family`, +`detail::stream_sizes`, the primary `detail::stream_engine` (the generated refusal and fail-closed +stubs) and the class, and includes `unauthenticated_encryption/stream_cipher.hpp` (the concept +and its free form, D3), as `ciphers/aead.hpp` includes `secret_key_encryption/aead.hpp`; it +includes no backend. +`ciphers/chacha20.hpp` holds the alias, includes `stream_cipher.hpp` and, when the program links +the default, the default's backend header (`WEBCPP_CRYPTO_DETAIL_DEFAULT_CHACHA20_SODIUM`), and +checks the concept on `detail::concept_check_backend`, as `chacha20_poly1305.hpp` does. A key +given as a `secure::secret<32>` (an HKDF's or an agreement's output) reaches the span by its +`bytes()`: a secret converts implicitly only to a fixed-extent span, and HPKE gives its keys the +same way. + +### D2. `apply_keystream`: the contract + +`apply_keystream(nonce_bytes, data_bytes, initial_counter)` XORs into `data_bytes`, in place, the +keystream of RFC 8439 section 2.4 under the object's key and `nonce_bytes`, its first block the +block of counter `initial_counter`. Encryption and decryption are this one call. Its order: + +1. `secure::timing_guard` first; on a backend that completes by itself, the refusal (D6). +2. The guards, none of which reads a byte of the spans, in this order: `invalid_state` (moved + from), `invalid_nonce_size` (not `nonce_size` bytes), `counter_overflow` when the data needs + more blocks than the counter has left, decided by `detail::counter_overflows( + data_bytes.size(), initial_counter)` (D3, owner decision 7): with `blocks = ceil(size / + block_size)` computed in 64 bits and `w` the counter's width in bits, refused exactly when + `blocks > 2^w - initial_counter`, which for ChaCha20 (64-byte blocks, a 32-bit counter) is + `blocks > 2^32 - initial_counter` (R6). A refusal leaves `data_bytes` untouched. +3. Empty data: success, no backend call (R7). +4. The nonce copied into an array of `nonce_size` bytes (12 for ChaCha20) of the function's own, + so that it may lie inside `data_bytes` (R5); then the engine's `apply`. +5. A backend's failure zeroes `data_bytes` (`secure::erase_secret`) and returns its error + (`backend_failure`), as an AEAD's failed seal does: neither the plaintext nor bytes that look + encrypted are left (R8). + +`counter_overflow` is the only length error: data longer than `max_message_size` from counter 0 +is a counter overflow too, and `message_too_long` is never returned (R6). `data_bytes` of +`2^32 - initial_counter` whole blocks, the last block of the counter, is accepted on every +backend. The keystream of a call from counter c over n blocks followed by a call from c + n +continues it, so a program that processes whole blocks continues a stream by the counter (R4). + +### D3. The concept and its free forms: `crypto::unauthenticated_encryption` (owner decision 5) + +```cpp +// : needs no backend, includes no cipher +namespace webcpp::crypto::detail { +// The counter's end, from the algorithm's block size and counter width (owner decision 7): true +// exactly when data_size bytes need more BlockSize-byte blocks than Counter has left from +// initial_counter, the first block included. Computed in 64 bits, with no sum that can wrap. +template + requires(BlockSize > 0 && std::numeric_limits::digits <= 64) +[[nodiscard]] constexpr bool counter_overflows(std::uint64_t data_size, Counter initial_counter) noexcept { + std::uint64_t const blocks = data_size / BlockSize + (data_size % BlockSize != 0 ? 1U : 0U); + std::uint64_t const blocks_after_first = std::uint64_t{std::numeric_limits::max()} - initial_counter; + return blocks != 0 && blocks - 1 > blocks_after_first; +} +} +namespace webcpp::crypto::unauthenticated_encryption { +template +concept stream_cipher = + requires(Cipher& keyed_cipher, std::span& key_bytes, + std::span const& nonce_bytes, std::span& data_bytes, + typename Cipher::counter_type initial_counter) { + { Cipher::key_size } -> std::convertible_to; + { Cipher::nonce_size } -> std::convertible_to; + { Cipher::block_size } -> std::convertible_to; + typename Cipher::counter_type; + requires std::unsigned_integral; + requires std::numeric_limits::digits <= 64; + requires(Cipher::block_size > 0); + { Cipher::from_key(key_bytes) } -> std::same_as>; + { keyed_cipher.apply_keystream(nonce_bytes, data_bytes, initial_counter) } + -> std::same_as>; + }; + +template +[[nodiscard]] boost::system::result apply_keystream( + Cipher& keyed_cipher, std::span nonce_bytes, std::span data_bytes, + typename Cipher::counter_type initial_counter) noexcept(noexcept(...)); // holds the guard, calls the member +} +``` + +The concept reads the algorithm's own shape (owner decision 7): `nonce_size`, `block_size` and +`counter_type` are the algorithm's, never ChaCha20's 12, 64 and `std::uint32_t`, and the free forms +take `typename Cipher::counter_type` and a nonce span of any length, which the member checks against +its own `nonce_size`. The free forms name no backend and no member of the algorithm but +`apply_keystream` (and `async_apply_keystream`, D6), so a stream cipher of another shape, as +AES-CTR will be, works through them unchanged. The counter's end is the one helper +`detail::counter_overflows`, in this header (it needs no backend), which every stream cipher's +`apply_keystream` calls after `invalid_state` and `invalid_nonce_size`; the guard order stays the +member's, since only the member can see a moved-from object. A counter is a standard unsigned +integer of at most 64 bits (R28). `stream_cipher_shape_test` (D9) pins all of it with a test-only +stand-in. + +No AEAD, box or block cipher satisfies `stream_cipher`, and `ciphers::chacha20` satisfies +neither `secret_key_encryption::aead::cipher` nor `secret_key_encryption::authenticated_box`; a +test pins all four. `crypto::from_key>(key)` already serves it +(`factories.hpp`, unchanged). `` declares the namespace +`crypto::unauthenticated_encryption` beside the others, so that a name used without its header is +a missing member of the namespace. The generator's namespace list (`crypto.json`'s `namespaces`) +gains `unauthenticated_encryption`, from which the guide's namespace tables +(`doc/generated/namespace-unauthenticated_encryption.adoc` and the table "The namespaces by +purpose") are written. The include boundaries (crypto's `meta/include-boundaries.json`, if it +lists the purpose namespaces' headers) give `unauthenticated_encryption/` the same rule as +`secret_key_encryption/`: no backend and no cipher header. The name `stream_encryption` stays free +for a future authenticated construction over chunks (owner decision 5). + +### D4. The engines + +`detail/engines.hpp` declares two more traits, `template struct +stream_state;` and `stream_engine;`, and crypto's `AGENTS.md` names them among the traits a +backend's header supplies (ten, from eight). An engine has `init(state&, key_bytes) -> +result`, `apply(state&, std::span nonce_bytes, +typename Family::counter_type initial_counter, std::span data_bytes) -> +result` (for ChaCha20 a 12-byte span and a `std::uint32_t`), `move(target, source)` and +`reset(state&)`, every one `noexcept`, `apply` called with checked sizes and a non-empty span: + +| Backend | State | `init` | `apply` | Fails | +|---|---|---|---|---| +| libsodium | `std::array` key | `sodium_ready()`, copy | `crypto_stream_chacha20_ietf_xor_ic(data, data, size, nonce, counter, key)`, in place (libsodium's contract allows `c == m`) | never past the guards; libsodium's own `sodium_misuse` is unreachable (R6) | +| BearSSL | `std::array` key | copy | `detail::bearssl_chacha20()(key, nonce, counter, data, size)`, its SSE2 code where present, `br_chacha20_ct_run` under the seam `WEBCPP_CRYPTO_DETAIL_BEARSSL_PORTABLE` | never | +| OpenSSL | one `EVP_CIPHER_CTX*`, keyed once for "ChaCha20" fetched by name | `openssl_context(..., "ChaCha20", key, ...)`, as ChaCha20-Poly1305's | a 16-byte IV, the counter little-endian then the nonce (OpenSSL's `ChaCha20` IV), set by `EVP_CipherInit_ex(context, nullptr, nullptr, nullptr, iv, 1)`, as GCM's engine sets its nonce, then `EVP_CipherUpdate` in pieces of 2^30 bytes, whole 64-byte blocks, the last one shorter (its length is an `int`, R18) | `backend_failure`, the error queue left as GCM's engine leaves it | + +libsodium's and BearSSL's read their backend's canary first, as the AEAD engines do; OpenSSL has no +canary, and its engine reads none; `move` copies and wipes (libsodium, +BearSSL) or moves the pointer (OpenSSL); `reset` wipes the key or frees the context +(`EVP_CIPHER_CTX_free` cleanses the key) and then wipes the state with `secure::erase_secret`. The +state of a backend whose header does not specialise it is empty, and its engine is the family's +generated refusal. + +### D5. The capability table, the default, the refusals + +`doc/tables/crypto.json` gains the family `chacha20` (group `ciphers`, since 0.2, measured +"keystream of 16 KiB", header ``, the name `chacha20` of type +`ciphers::chacha20<{backend}>`), its backends with ChaCha20-Poly1305's targets and lanes +(libsodium and BearSSL on every target, OpenSSL on native, wasip2 and wasip3; the constant-time +lane's cells as D8 says), its operation entry in `ciphers` (`from_key`, +`basic_chacha20::async_from_key`, `apply_keystream`, `basic_chacha20::async_apply_keystream`, the +free `apply_keystream` and `async_apply_keystream`, with each backend's tests), its default +(libsodium on every target, R9) and its message tests in `fixes`. The generator then writes, never +by hand: the family's forward declaration and `WEBCPP_CRYPTO_DETAIL_REFUSE_CHACHA20(Backend)` in +`detail/capabilities.hpp` (ctaes and secp256k1 "have no ChaCha20", a header not included, the +default not linked, an unknown backend, each naming the backends and targets that have it), +`default_backend_t` and `WEBCPP_CRYPTO_DETAIL_DEFAULT_CHACHA20_SODIUM` in +`detail/defaults.hpp`, the alias `/webcpp/crypto//chacha20-default` in `build.jam`, +`supports_v` and its cells in `test/capabilities_test.cpp`, and the guide's +generated tables. The superproject's crypto Jamfile fixtures gain `chacha20_default` (the alias +links libsodium on every target). + +### D6. The asynchronous forms and the browser + +The class declares `async_from_key` and `async_apply_keystream`; `` +defines them (a post of the synchronous call through `detail::complete_by_post`, completing with +`void(boost::system::error_code, basic_chacha20)` and `void(boost::system::error_code)`), and adds +the free `unauthenticated_encryption::async_apply_keystream(executor, cipher, nonce_bytes, data_bytes, +initial_counter, token)`, which calls the member; `crypto::async_from_key` takes a +`stream_cipher` besides an AEAD and a secret box, its refusal text naming all three. The object +and the spans are the caller's until the completion; a guard's refusal leaves the data untouched, +a backend's failure zeroes it, as the synchronous call does. + +WebCrypto has no ChaCha20. Every member of `basic_chacha20`, synchronous or asynchronous, on a +backend whose `detail::asynchronous_backend_v` is true, calls first, after its guard, +`detail::refuse_stream_cipher_on_asynchronous_backend()` in `detail/asynchronous.hpp`; the +free forms, which name no backend (owner decision 7), meet the same refusal through the member they +call, so every form, member or free, stops the build with that one `static_assert`, which says: "webcpp::crypto: WebCrypto has no ChaCha20: no form of the raw +stream cipher, synchronous or asynchronous, runs on the browser's backend; name a native backend +for it." (R10). Message tests pin it with a stand-in backend, as `open_asynchronous_backend` does. +On such a backend the engine's generated refusal is not expanded (`detail::stream_refusal` is empty +there, and so are the AEADs', the secret boxes' and the boxes' refusals): a kept `from_key` result +destroys an object, whose destructor names the engine after the member's refusal, which speaks for +that backend alone (`from_key_chacha20_asynchronous_backend` pins it). +On Emscripten the default (libsodium compiled to wasm) runs every form, as ChaCha20-Poly1305's +does. + +### D7. The error value + +`crypto::error::counter_overflow = 22`, message "the data needs more blocks than the stream +cipher's counter has left after the initial counter", in the category `webcpp.crypto`; its line +in `error_test.cpp` and in the guide's errors page. 22 follows hpke's +`message_limit_reached = 21` in the queue; the values are fixed and never reused (R12). + +### D8. The timing guard and constant time + +Every function of D1, D3 and D6 holds `secure::timing_guard` first; `test/timing_coverage_sodium_test.cpp`, +`timing_coverage_bearssl_test.cpp` and `timing_coverage_openssl_test.cpp` each cover +`chacha20`'s `from_key`, `apply_keystream`, the free `crypto::from_key` and +`unauthenticated_encryption::apply_keystream`, and the two asynchronous forms (a new +`webcpp::test::cover_stream_cipher` in `test/support/timing_coverage.hpp`, beside `cover_aead`); +arm64 14.5 runs them. The constant-time lane (Linux) runs the keystream on BearSSL and on +libsodium under memcheck and MemorySanitizer (`test/constant_time/paths.hpp`, the key and the data +marked secret, the result read), and OpenSSL's under memcheck alone (`ctgrind_test.cpp`, as +ChaCha20-Poly1305's seal); dudect measures BearSSL's keystream natively and on wasip2 +(`dudect_test.cpp`, a case `chacha20_keystream`, two classes of key, the all-zero key against +random keys, the data and nonce fixed). The `lane` cells of the family in `crypto.json` are +ChaCha20-Poly1305's: libsodium memcheck and msan, BearSSL memcheck, msan and dudect (native, +wasip2), OpenSSL memcheck. + +### D9. The tests and the vectors + +- **RFC 8439's vectors**, in `test/support/stream_cipher_checks.hpp`, run by one test per backend + (`chacha20_sodium`, `chacha20_bearssl` with its portable twin `chacha20_bearssl_portable`, + `chacha20_openssl`): section 2.3.2's block (the keystream of 64 zero bytes at counter 1), section + 2.4.2's encryption (counter 1), Appendix A.1's five keystream blocks and A.2's three encryptions + (counters 0, 1 and 42), each decrypted back; the guards in their order; the boundary (counter + 2^32 - 1 with 64 bytes accepted and equal across backends, with 65 bytes `counter_overflow` and + the data untouched; counter 2^32 - 2 with 128 bytes accepted); the nonce inside the data; empty + data; a moved-from object; the key as a `secure::secret<32>`. +- **The backends' agreement**, `agreement_chacha20` (and its Emscripten and portable twins, as + `agreement_chacha`): libsodium, BearSSL and OpenSSL on the same random keys, nonces, counters + (0, 1, random, 2^32 - 1 minus the blocks) and lengths (0 to 1 KiB, block edges, 64 KiB) give the + same bytes, and two calls continuing by the counter equal one call. +- **NIP-44 version 2's end-to-end vectors** (R13): paulmillr/nip44's `nip44.vectors.json`, the + vectors NIP-44's text names with its SHA-256, as a test-data submodule of the superproject + `third_party/libs/nip44`, read through `WEBCPP_TEST_NIP44`; the test's own NIP-44 + (`test/support/nip44.hpp`, test only) composes the conversation key (secp256k1's `agree` on + the peer's x with even y, `hash::hkdf_extract` with the salt "nip44-v2"), the message keys + (`hash::hkdf_expand`, 76 bytes: the ChaCha20 key, its nonce, the HMAC key), the padding, + ChaCha20 from counter 0, HMAC-SHA256 over the nonce and the ciphertext, and codecs' base64; the + sections `valid.get_conversation_key`, `valid.get_message_keys`, `valid.encrypt_decrypt` (each + payload encrypted and decrypted) and `valid.encrypt_decrypt_long_msg` (the plaintext's and the + payload's SHA-256), on each of the three backends. +- **The concepts and the forms**: `stream_cipher_concepts_test` (D3's four facts, the four forms + give the same bytes), `stream_cipher_shape_test` (owner decision 7: a test-only stand-in, + `webcpp::test::stand_in_stream_cipher`, with a 16-byte key, an 8-byte nonce, a 16-byte block and + a `std::uint8_t` counter, its `apply_keystream` calling `detail::counter_overflows` as ChaCha20's + does; at compile time it satisfies `stream_cipher`, both free forms are callable with its own + nonce and counter types, and `static_assert`s pin `detail::counter_overflows` at its bound + (16 bytes at counter 255 accepted, 17 refused; 4096 bytes from 0 accepted, 4097 refused), at + ChaCha20's (64 bytes at 2^32 - 1 accepted, 65 refused, 128 at 2^32 - 2 accepted) and at a 64-bit + counter's (65 bytes at 2^64 - 1 refused, the largest `std::uint64_t` size from 0 accepted with + 64-byte blocks); at run time the free forms give the member's bytes, refuse ChaCha20's 12-byte + nonce with `invalid_nonce_size` and 17 bytes at counter 255 with `counter_overflow`, the data + untouched, and `crypto::from_key` makes one; it links no backend), `async_stream_cipher_test` (the asynchronous forms with a callback, + `use_awaitable` where the build has coroutines, `deferred`; an error completion's empty object + refusing with `invalid_state`). +- **No heap**: `allocation_sodium`, `allocation_bearssl` and `allocation_openssl` gain the + keystream (OpenSSL's `from_key` allocates through OpenSSL's memory functions, as + ChaCha20-Poly1305's does; `apply_keystream` allocates nothing on any backend). +- **Message tests**, each with its `crypto.json` `fixes` entry and its `test/msvc/` twin: + `chacha20_not_a_family`, `chacha20_unknown_backend`, `chacha20_on_ctaes`, + `chacha20_default_not_linked`, `chacha20_header_not_included`, + `apply_keystream_asynchronous_backend`, `async_apply_keystream_asynchronous_backend`, + `async_from_key_chacha20_asynchronous_backend`, `apply_keystream_not_a_stream_cipher` (the free + form given an AEAD), `from_key_chacha20_asynchronous_backend` (a kept `from_key` result, D6), + `async_from_key_aead_without_member` and `async_from_key_stream_cipher_without_empty` (the free + `async_from_key`'s own refusals), and the changed text of `async_from_key`'s refusal; the final + round's `from_key_chacha20_poly1305_asynchronous_backend`, `from_key_secretbox_asynchronous_backend` + and `from_keys_box_asynchronous_backend` pin the AEADs', the secret boxes' and the boxes' silent + engine refusals alike. + +### D10. The guide, the example, sizes and speed + +A section "ChaCha20, the raw stream cipher" in `doc/chacha.adoc` after ChaCha20-Poly1305's: what +it is and is not (no authentication; use `chacha20_poly1305` unless a protocol fixes its own +construction, as NIP-44 does), the call, the counter and its overflow, the nonce rule, the backends +and the default, the four forms, the browser; a pitfall list (a nonce reused under one key reveals +the XOR of two plaintexts; a bit flipped in the ciphertext flips the same bit of the plaintext; a +protocol's MAC must cover the nonce and the ciphertext). A page of its own, +`doc/unauthenticated_encryption.adoc` ("Unauthenticated encryption: +`webcpp::crypto::unauthenticated_encryption`", included after `secret_key_encryption.adoc`), +says what the namespace is for: a protocol that brings its own authentication (NIP-44, with its +HMAC over the nonce and the ciphertext), never a program's own messages, for which +`secret_key_encryption` is the normal path; it holds the concept, the free forms, a generic +function over the concept and the generated namespace table. `doc/secret_key_encryption.adoc`'s +table of the namespaces by purpose gains the row, `doc/ciphers.adoc` names ChaCha20 among the +algorithms and points to the page, `doc/errors.adoc` the new value, `doc/async.adoc` the forms, +`doc/p2p.adoc` a paragraph on NIP-44 composed from webcpp's pieces. The example +`example/chacha20_keystream.cpp` with its `.expected` runs RFC 8439 section 2.4.2. `crypto.json` +gains a rule ("ChaCha20 authenticates nothing") and a use case. The sizes programs +`test/sizes/chacha20_{sodium,bearssl,openssl}.cpp` and the bench cells (`bench/operations.hpp`'s +`keystream`, `throughput.cpp`'s three cells) are added; their numbers come from release builds +only (R16). + +### D11. Poly1305: the family and the type (owner decision 6) + +```cpp +// +namespace webcpp::crypto::families { +struct poly1305 { // forward-declared by the generated table + static constexpr std::size_t key_size = 32; // r || s, RFC 8439 section 2.5 + static constexpr std::size_t tag_size = 16; +}; +} +namespace webcpp::crypto::authenticators { +template > +class poly1305 { +public: + using backend_type = Backend; + using family_type = families::poly1305; // the capability table's family + using name_type = families::poly1305; // the algorithm supports_v reads + using result_type = boost::hash2::digest<16>; // the AEADs' and boxes' tag type + static constexpr std::size_t key_size = families::poly1305::key_size; + static constexpr std::size_t tag_size = families::poly1305::tag_size; + + [[nodiscard]] static boost::system::result authenticate( + std::span key_bytes, std::span message_bytes) noexcept; + [[nodiscard]] static boost::system::result verify( + std::span key_bytes, std::span message_bytes, + std::span tag_bytes) noexcept; + template + static auto async_authenticate(Executor const&, std::span key_bytes, + std::span message_bytes, CompletionToken&&); + template + static auto async_verify(Executor const&, std::span key_bytes, + std::span message_bytes, + std::span tag_bytes, CompletionToken&&); + + poly1305() = delete; // an algorithm, never an object (R21) +}; +} +``` + +`authenticators` is a new namespace of algorithms, the sibling of `ciphers`, declared in +``; Poly1305 is no cipher, so it does not join `ciphers` (R20). +`authenticators/poly1305.hpp` holds the family's definition, `detail::authenticator_refusal`, the +primary `detail::authenticator_engine` (the generated refusal and a fail-closed stub) and the +class, includes `single_use_key_authentication/authenticator.hpp` (the concept and its free forms, +D13), as `ciphers/stream_cipher.hpp` includes `unauthenticated_encryption/stream_cipher.hpp`, and, +when the program links the default, the default's backend header +(`WEBCPP_CRYPTO_DETAIL_DEFAULT_POLY1305_SODIUM`), and checks the concept on +`detail::concept_check_backend`. One header holds what ChaCha20 splits in two, because Poly1305 has +one family and no `basic_` template (R22). A key given as a `secure::secret<32>` reaches the span +by its `bytes()` (D1). + +### D12. `authenticate` and `verify`: the contract + +`authenticate(key_bytes, message_bytes)` gives RFC 8439 section 2.5's tag of `message_bytes` under +the one-time key `key_bytes` (r || s, r clamped by the algorithm, not by the caller). Its order: + +1. `secure::timing_guard` first; on a backend that completes by itself, the refusal (D15). +2. `invalid_key_size` for a key of another size than 32, reading no byte. No other guard: every + message length is accepted, the empty message too (its tag is s). +3. The engine's `authenticate` into a zeroed `result_type`; on a backend's failure the tag is + zeroed again and the error returned. + +`verify(key_bytes, message_bytes, tag_bytes)`: + +1. The guard; the refusal (D15). +2. `invalid_key_size`, then `invalid_tag_size` for a tag of another size than 16, reading no byte. +3. The tag computed as `authenticate` computes it, into a local `result_type`; a backend's failure + returns its error, never `authentication_failed`. +4. `secure::constant_time_equal(computed_tag, tag_bytes)`, the verdict declassified with + `secure::declassify` where crypto first branches on it, the computed tag wiped with + `secure::erase_secret`, then `authentication_failed` on a mismatch, success on a match (as + BearSSL's AEAD open compares, `backends/bearssl.hpp`). + +The errors are crypto's existing values (R23): `invalid_key_size` (1), `invalid_tag_size` (3), +whose text already names "`open` or `verify`", and `authentication_failed` (6), what every AEAD's +and box's `open` returns for a tag that does not match; and the backends' (`backend_failure`, and on +OpenSSL `memory_functions_not_installed` and `errc::not_enough_memory`). No error value is added. +Nothing is written into the caller's spans; the key, the message and the tag may overlap. + +The key: crypto takes it as a span and copies it nowhere. libsodium reads it from the caller's +bytes and wipes its own state (`crypto_onetimeauth_poly1305_final`); OpenSSL copies it into its +MAC context, which `EVP_MAC_CTX_free` cleanses, in the same call. The one secret copy crypto holds +is `verify`'s computed tag, wiped before it returns. The caller's key is the caller's to wipe (a +`secure::secret<32>` does it). + +### D13. The concept and its free forms: `crypto::single_use_key_authentication` (owner decision 6) + +```cpp +// : needs no backend, includes no algorithm +namespace webcpp::crypto::single_use_key_authentication { +template +concept single_use_key_authenticator = + requires(std::span const& key_bytes, std::span const& message_bytes, + std::span const& tag_bytes) { + { Authenticator::key_size } -> std::convertible_to; + { Authenticator::tag_size } -> std::convertible_to; + typename Authenticator::result_type; + { Authenticator::authenticate(key_bytes, message_bytes) } + -> std::same_as>; + { Authenticator::verify(key_bytes, message_bytes, tag_bytes) } -> std::same_as>; + }; + +template +[[nodiscard]] boost::system::result authenticate( + std::span key_bytes, std::span message_bytes) noexcept(noexcept(...)); +template +[[nodiscard]] boost::system::result verify( + std::span key_bytes, std::span message_bytes, + std::span tag_bytes) noexcept(noexcept(...)); +// Catch-alls, requires(!single_use_key_authenticator), one static_assert each: +// "webcpp::crypto: single_use_key_authentication::authenticate takes a single-use key +// authenticator (authenticators::poly1305); a reusable key's MAC is webcpp::hash::mac (HMAC)." +} +``` + +The four forms (unified-sign's D9) without a keyed object (R21): the "member" forms are the +algorithm type's static members, `poly1305::authenticate`, `verify`, `async_authenticate` and +`async_verify`; the free forms are `single_use_key_authentication::authenticate`, `verify`, +`async_authenticate` and `async_verify`, the type an explicit template argument, each holding +its guard and calling the static member. crypto's existing pairs have the same shape where an +operation has no object: `K::async_generate(executor, token)` and `C::async_from_key(executor, +key_bytes, token)` are static members, and their free forms `crypto::async_generate` and +`crypto::async_from_key` name the type and call them. There is no `from_key`, no +`crypto::from_key` and no `async_from_key`: `crypto::from_key>` +stops the build with `factories.hpp`'s existing refusal, unchanged. + +No AEAD, box, stream cipher or webcpp::hash MAC satisfies `single_use_key_authenticator`, and +`authenticators::poly1305` satisfies neither `unauthenticated_encryption::stream_cipher` nor +`secret_key_encryption::aead::cipher`; a test pins them. `` declares the +namespaces `single_use_key_authentication` and `authenticators`; `crypto.json`'s `namespaces` gains +`single_use_key_authentication`, from which its generated table and the row of "The namespaces by +purpose" are written; the include boundaries give `single_use_key_authentication/` the rule of +`secret_key_encryption/` (no backend, no algorithm header). + +### D14. Poly1305's engines, the table, the default, the refusals + +`detail/engines.hpp` declares `template struct authenticator_engine;`, +and `AGENTS.md` names it among a backend's traits (eleven, from ten). It has no state trait: an +engine is one static function, `authenticate(std::span key_bytes, +std::span message_bytes, std::span tag_bytes) -> +result`, `noexcept`, called with checked sizes. + +| Backend | `authenticate` | Fails | +|---|---|---| +| libsodium | `read_canary`, `sodium_ready()`, `crypto_onetimeauth_poly1305(tag, message, size, key)`; an empty message passed as a pointer to a byte of the engine's own with length 0 (R24) | never (libsodium returns 0) | +| OpenSSL | `openssl_memory_guard()` (no canary: OpenSSL has none, and its engine reads none), `ERR_set_mark()`, `EVP_MAC_fetch(nullptr, "POLY1305", nullptr)`, `EVP_MAC_CTX_new`, `EVP_MAC_init(context, key, 32, nullptr)`, `EVP_MAC_update(context, message, size)` (a `size_t`, no pieces), `EVP_MAC_final(context, tag, &written, 16)` with `written == 16`, `EVP_MAC_CTX_free` (which cleanses the key) and `EVP_MAC_free`, `ERR_pop_to_mark()` | `memory_functions_not_installed`, `errc::not_enough_memory` (a null context), `backend_failure` (a null fetch or a failed call) | + +`doc/tables/crypto.json` gains the family `poly1305` (group `authenticators`, since 0.2, measured +"tag of 16 KiB", header ``, the name `poly1305` of +type `authenticators::poly1305<{backend}>`), its backends (libsodium on native, wasip2, wasip3 and +Emscripten; OpenSSL on native, wasip2 and wasip3; the lane cells of D16), its operation entries (the +static members and the free forms, in `single_use_key_authentication`), its default (libsodium on +every target, R25) and its message tests in `fixes`. The generator writes the forward declaration, +`WEBCPP_CRYPTO_DETAIL_REFUSE_POLY1305(Backend)` (BearSSL, ctaes and secp256k1 "have no Poly1305", a +header not included, the default not linked, an unknown backend, each naming libsodium, OpenSSL and +their targets), `default_backend_t`, `WEBCPP_CRYPTO_DETAIL_DEFAULT_POLY1305_SODIUM`, +the alias `/webcpp/crypto//poly1305-default`, `supports_v` and its cells, and +the generated tables. BearSSL's reason (its Poly1305 is inside its AEAD alone and derives its key +itself) is in the family's backend note where the generator's table carries one, and on the guide's +page in any case. The superproject's crypto fixtures gain `poly1305_default`. + +### D15. Poly1305's asynchronous forms and the browser + +`` defines the two static members through `detail::complete_by_post`, +completing with `void(boost::system::error_code, result_type)` (on an error the zeroed tag, as +`async_seal`'s) and `void(boost::system::error_code)`, and adds the free +`single_use_key_authentication::async_authenticate(executor, key_bytes, message_bytes, token)` +and `async_verify(executor, key_bytes, message_bytes, tag_bytes, token)`, with catch-alls as +D13's; its header comment lists them. The spans are the caller's until the completion. + +WebCrypto has no Poly1305. Every form, synchronous or asynchronous, static member or free, on a +backend whose `detail::asynchronous_backend_v` is true, calls first, after its guard, +`detail::refuse_single_use_key_authenticator_on_asynchronous_backend()`, whose one +`static_assert` says: "webcpp::crypto: WebCrypto has no Poly1305: no form of the single-use key +authenticator, synchronous or asynchronous, runs on the browser's backend; name a native backend for +it." Message tests pin it with a stand-in backend, as D6's do. On Emscripten the default (libsodium +compiled to wasm) runs every form. + +### D16. Poly1305's guard, constant time, tests and page + +- **The guard**: every function of D11, D13 and D15 holds `secure::timing_guard` first; + `timing_coverage_sodium_test.cpp` and `timing_coverage_openssl_test.cpp` cover each through a new + `webcpp::test::cover_single_use_key_authenticator` (a matching and a mismatching `verify` + included); arm64 14.5 runs them. +- **Constant time**: the constant-time lane runs `authenticate` and `verify` on libsodium under + memcheck and MemorySanitizer (`paths.hpp`, the key, the message and the tag marked secret, the + tag checked with `carries_mark(tag)`, `verify`'s verdict declassified by crypto itself, + D12) and on OpenSSL under memcheck alone (`ctgrind_test.cpp`); dudect (`dudect_sodium_test.cpp`) + measures `poly1305_authenticate` (the all-zero key against random keys, the message fixed) and + `poly1305_verify` (the right tag with its last byte flipped against the right tag with its first + byte flipped, both failing, the key and the message fixed, which measures crypto's comparison, + the probe of one that exits early) natively and on wasip2. A matching tag against a mismatching + one would measure the public verdict's return path, success against `authentication_failed` + (|t| 32.71 natively), not the comparison: as the AEAD open case of `dudect_test.cpp`, both + classes fail. +- **Vectors**, `test/support/authenticator_checks.hpp`, run by `poly1305_sodium` and + `poly1305_openssl`: RFC 8439 section 2.5.2 and Appendix A.3's eleven vectors, each through + `authenticate`, `verify` and the free forms; the guards in their order; a tag with one bit flipped + in each byte `authentication_failed`; a message with one bit flipped `authentication_failed`; the + key as a `secure::secret<32>`; the empty message (its tag is s). +- **Agreement**, `agreement_poly1305` (and its Emscripten twin against the support's portable + reference, written from RFC 8439 section 2.5's pseudocode): libsodium and OpenSSL on 2000 random + keys and lengths (0 to 1 KiB, 15, 16, 17, 64 KiB) give the same tag, equal to the reference's. +- **The concepts**: `authenticator_concepts_test` (D13's facts, the four forms give the same tag + and the same errors, a generic function over the concept); `async_authenticator_test`. +- **No heap**: `authenticate` and `verify` allocate nothing on libsodium; on OpenSSL nothing + through `operator new`, the MAC context through OpenSSL's memory functions alone (R26). +- **Message tests**, each with its `fixes` entry and `test/msvc/` twin: `poly1305_on_bearssl`, + `poly1305_on_ctaes`, `poly1305_unknown_backend`, `poly1305_default_not_linked`, + `poly1305_header_not_included`, `authenticate_not_a_single_use_key_authenticator` (a hash MAC's tag + or an AEAD given to the free form), `verify_not_a_single_use_key_authenticator`, + `async_authenticate_not_a_single_use_key_authenticator`, + `async_verify_not_a_single_use_key_authenticator`, `from_key_poly1305`, + `authenticate_asynchronous_backend`, `verify_poly1305_asynchronous_backend` (Ed25519 already had + `verify_asynchronous_backend`), `async_authenticate_asynchronous_backend`, + `async_verify_asynchronous_backend`. +- **The page**: `doc/single_use_key_authentication.adoc` ("Single-use key authentication: + `webcpp::crypto::single_use_key_authentication`", included after + `unauthenticated_encryption.adoc`) opens with the rule: the key is used once, for one message, and + a second message under it lets an attacker forge tags; for a reusable key, `hash::mac` (HMAC); + one-time passwords (HOTP, TOTP) are not what this namespace does, and the page points to no + library for them (there will be no webcpp::otp, owner decision 6). Then the call, `verify` and its constant-time + comparison, the backends and BearSSL's absence, the four forms, the browser, the generated + namespace table, a generic function over the concept. `secret_key_encryption.adoc`'s table of the + namespaces by purpose gains the row; `chacha.adoc` points to it beside the raw ChaCha20; + `crypto.json` gains a rule ("a Poly1305 key authenticates one message") and a use case; the + example `poly1305_one_time_tag` runs section 2.5.2; the sizes programs + `test/sizes/poly1305_{sodium,openssl}.cpp` and the bench cells (`one_time_tag`, a tag of 16 KiB) are added, + their numbers from release builds only (R16). + +### D17. RFC 8439's AEAD composed from the raw pieces, as a cross-backend matrix (owner decision 6) + +`test/support/composition_checks.hpp`'s `check_rfc8439_composition()`, run by one type-parameterised test, +`composition_rfc8439`, over every combination, builds RFC 8439 section 2.8's AEAD from this +change's pieces: + +- `poly_key`: the first 32 bytes of `ciphers::chacha20`'s keystream at counter 0 + (section 2.6); +- the ciphertext: the plaintext through `apply_keystream` from counter 1; +- the tag: `authenticators::poly1305::authenticate(poly_key, aad || pad16 || + ciphertext || pad16 || le64(aad_len) || le64(ct_len))`; + +and asserts that the ciphertext and the tag equal, byte for byte, +`ciphers::chacha20_poly1305`'s `seal` of the same key, nonce, aad and plaintext. The +matrix: the raw ChaCha20 on libsodium, BearSSL and OpenSSL, times Poly1305 on libsodium and +OpenSSL, times ChaCha20-Poly1305 on libsodium, BearSSL and OpenSSL, 18 combinations natively, +wasip2 and wasip3; on Emscripten, without OpenSSL, the 4 combinations of libsodium and BearSSL. Each +combination runs the same cases: section 2.8.2's vector (also checked against the RFC's bytes), then +the same random keys and nonces over every message length of 0, 1, 15, 16, 17, 63, 64, 65, 255 and +1024 bytes with every aad length of 0, 1, 12, 16 and 17. A failure names its combination (the three +backends, the case, the lengths) in the test's message. BearSSL joins through its raw ChaCha20 and +its AEAD; it has no raw Poly1305. The matrix proves that the two raw pieces are the ones inside +every backend's AEAD (the counter, the key derivation, the padding), a fact no vector of either +piece shows alone. It partly overlaps the backends' agreement tests (`agreement_chacha20`, +`agreement_poly1305`, `agreement_chacha`), which already show the backends equal piece by piece, +but it localises a failure better: a broken cell names the one backend of the one piece or AEAD +that differs, where an agreement failure says only that the backends disagree. + +## Rulings + +Each says what was ruled, why, and the cost if the ruling is wrong. + +- **R1. `basic_chacha20` takes the family, with `families::chacha20` its only one + today** - why: it mirrors `basic_chacha20_poly1305`, the owner's named model, + and leaves the original ChaCha20 (8-byte nonce, 64-bit counter) and XChaCha20 (24-byte nonce) + room to join as families with their own `counter_type`, which the concept reads - cost if + wrong: an alias `basic_chacha20` is one line; callers use `chacha20` either way. +- **R2. `initial_counter` is a mandatory parameter, with no default** - why: the owner's signature + names it; RFC 8439 says the counter is usually 0 or 1, and the two protocols that use it differ + (NIP-44 starts at 0, the AEAD's encryption at 1), so a default would hide the one choice that + makes the bytes right - cost if wrong: a default argument added later breaks no caller. +- **R3. The counter is `std::uint32_t`, the family's `counter_type`** - why: RFC 8439 section 2.3 + fixes 32 bits; a wider type would accept values no backend can start from - cost if wrong: + none for RFC 8439's family. +- **R4. In place only; no separate output span, no keystream that continues across calls at a + byte offset** - why: the owner's signature; every cipher of crypto works in place; whole blocks + continue by the counter (D2), and NIP-44 and the AEAD encrypt each message in one call - cost if + wrong: a stateful form is a later addition with no change to this one. +- **R5. The nonce is copied before any write, so that it may lie in `data`** - why: one contract on + every backend, whatever each reads first (BearSSL and OpenSSL read it first today, libsodium + too, but none documents it); `nonce_size` bytes, 12 for ChaCha20 - cost if wrong: none. +- **R6. crypto refuses the counter's end itself, before any backend, with `counter_overflow`, at + exactly libsodium's bound (`blocks > 2^32 - initial_counter`, `detail::counter_overflows` at + ChaCha20's 64-byte block and 32-bit counter), and never `message_too_long`** - + why: the three backends disagree past it (libsodium aborts the program, BearSSL wraps to block + 0, which repeats keystream, OpenSSL carries into the nonce, which is another nonce's keystream); + a value error before the call makes the three agree and keeps libsodium's abort unreachable; one + error for "not enough keystream" is clearer than two - cost if wrong: renaming the value. +- **R7. Empty data succeeds after the guards and calls no backend** - why: an empty span's + `data()` may be null, which no backend should be given; the result is the same everywhere - cost + if wrong: none. +- **R8. A backend's failure zeroes the data** - why: ChaCha20-Poly1305's seal does the same, for + the same reason (a partial XOR leaves neither the input nor a usable output); only OpenSSL can + fail - cost if wrong: none. +- **R9. libsodium is the default on every target** - why: it is ChaCha20-Poly1305's default + ("one library for the ChaCha20 constructions on every target"), so a program that uses both + links one library; libsodium's ChaCha20 is constant time in C on every target - cost if wrong: + one line of `crypto.json`, rerun. +- **R10. The raw cipher's refusal on a backend that completes by itself is its own + (`refuse_stream_cipher_on_asynchronous_backend`), not the AEAD's** - why: the AEAD's text names + "ChaCha20-Poly1305, XChaCha20-Poly1305, secret box or crypto_box" and "only AES-GCM seals and + opens", which would mislead a reader of a keystream error, and changing it would change every + message test that pins it - cost if wrong: one more text in part B's list of refusals. +- **R11. The four forms, the asynchronous ones included, as ChaCha20-Poly1305's** - why: + unified-sign's D9 gives every cheap operation that calls a backend its four forms, and the + dispatch of 2026-11-30 asks the raw cipher to match the AEAD's wiring; the AES block cipher, + the other building block, has no asynchronous form today, an inconsistency this change does not + touch (listed in "Risks") - cost if wrong: removing two declarations and their definitions. +- **R12. `counter_overflow` is 22, whatever merges first** - why: hpke's design already names + `message_limit_reached = 21`, and the queue puts hpke first; if this change merged first, 21 + stays hpke's and no merged text moves - cost if wrong: a gap at 21 until hpke merges. +- **R13. NIP-44's vectors are a test-data submodule, and NIP-44 is composed only in + `test/support/nip44.hpp`; the `invalid` sections are not run** - why: the owner keeps NIP-44 out + of crypto; the vectors are the ones NIP-44's text pins by SHA-256, kept as wycheproof's are (a + pinned submodule after its licence check, never compiled); the invalid sections test NIP-44's + own parsing and MAC checks, the protocol's code, not the cipher - cost if wrong: running them is + a loop in the test. +- **R14. No fuzz target** - why: ChaCha20 parses nothing; the lane's rule is a target per decoder + - cost if wrong: one target. +- **R15. The concept and the free forms are in `crypto::unauthenticated_encryption`, their header + `unauthenticated_encryption/stream_cipher.hpp`, which `ciphers/stream_cipher.hpp` includes** - + why: owner decision 5; the split mirrors the AEAD's (`ciphers/aead.hpp` the class, + `secret_key_encryption/aead.hpp` the contract) - cost if wrong: none, the owner chose it. +- **R16. The bench cells and the sizes programs are added; their numbers are written only from + release builds, the sizes by the delivery's sizes lane, the throughput by the owner's release + measurement pass** - why: the owner's rule; the generator writes "not measured yet" until then - + cost if wrong: none. +- **R17. The spec adds requirements and modifies none** - why: nothing of an existing requirement + changes (ChaCha20-Poly1305, the AEAD contract, the error values already defined) - cost if + wrong: none. +- **R18. OpenSSL's `apply` feeds `EVP_CipherUpdate` pieces of 2^30 bytes, whole 64-byte blocks, + the last one shorter (`detail::openssl_chacha20_piece`, given to `openssl_update`, whose default + stays GCM's and ChaCha20-Poly1305's `INT_MAX / 16 * 16`)** - why: its length is an `int`; the + context keeps the keystream's position between pieces, and the guards have already kept the whole + call within the counter; whole blocks make each piece start a block, and the release agreement + test's 2^30 + 64 bytes cross exactly one piece's end - cost if wrong: none. +- **R19. `from_key` takes a span, which a `secure::secret<32>` gives by its `bytes()`** - why: + the AEADs' factories do the same; a second overload would be a second path to test; a secret + converts implicitly only to a fixed-extent span, not to the dynamic span `from_key` takes (Task + 3's ruling) - cost if wrong: none. +- **R20. The algorithm namespace `crypto::authenticators`, the header + ``, the purpose header + ``** - why: owner decision 6 names + `crypto::authenticators::poly1305`; the layout is the ciphers' (`ciphers/.hpp` the type, + `/.hpp` the concept and the free forms, the second included by the first), and + the purpose header is named by its concept's noun, as `secret_key_encryption/aead.hpp` and + `unauthenticated_encryption/stream_cipher.hpp` are - cost if wrong: a header renamed before + release. +- **R21. No keyed object: the key enters every call, and there is no `from_key`** - why: owner + decision 6; an object that held a Poly1305 key would invite the second message the key must never + see, while one call per key makes the single use visible at each call; the four forms map to + static members and free forms, as `async_generate` and `async_from_key` already do (D13); the + same reason keeps out an incremental init, update and final, which would need a state holding the + key - cost if wrong: a keyed or incremental form is an addition that changes no call of these. +- **R22. `poly1305` is a class template of its own, with no `basic_poly1305`** - why: R1's reason for ChaCha20's family parameter (the original ChaCha20, XChaCha20) + has no Poly1305 counterpart in scope: Poly1305-AES is a non-goal, and a second authenticator would + be another type satisfying the concept - cost if wrong: an alias over a `basic_` template later, + with no change for callers of `poly1305`. +- **R23. No new error value: `invalid_key_size`, `invalid_tag_size` and `authentication_failed`** + - why: `authentication_failed` is what every AEAD's and box's `open` returns when a tag does not + match, and `invalid_tag_size` already documents a tag given to `verify`; a reader handles a failed + Poly1305 tag as a failed open; a backend's failure keeps its own error, so that a broken backend + never reads as a forgery - cost if wrong: a value added later (23 or above). +- **R24. An empty message is accepted, and its engine never passes a null pointer** - why: RFC 8439 + defines the tag of every message, the empty one's being s; an empty span's `data()` may be null, + which no backend should be given - cost if wrong: none. +- **R25. libsodium is Poly1305's default on every target** - why: ChaCha20's and ChaCha20-Poly1305's + default (R9), so that a program composing ChaCha20 and Poly1305 links one library; libsodium's + Poly1305 is constant time in C on every target, Emscripten included, where OpenSSL is not built - + cost if wrong: one line of `crypto.json`, rerun. +- **R26. On OpenSSL each call allocates its MAC context through OpenSSL's memory functions** - why: + there is no keyed object to hold a context (R21), and `EVP_MAC` has no stack form; it is the + allocation OpenSSL's `from_key` already makes for every cipher, never through `operator new`, and + `WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE`'s guard applies - cost if wrong: a cached fetched `EVP_MAC` + per thread, a later optimisation measured on release builds. +- **R27. Of record: `ciphers::chacha20_poly1305` keeps calling each backend's combined function; + its composition from the raw pieces is a test, never its implementation** - why: owner decision 6; + the backends' AEADs are fused single passes over the data and audited as one construction, and + BearSSL, the AEAD's third backend, cannot compose alone (no raw Poly1305); the matrix (D17) pins + that the two paths agree on every backend combination without making the AEAD depend on the pieces - cost if wrong: none, the AEAD is + unchanged. +- **R28. The stream cipher's shape is the algorithm's: `nonce_size`, `block_size` and + `counter_type`, a standard unsigned integer of at most 64 bits, and the counter's end computed + from them by `detail::counter_overflows`** - why: owner decision 7; AES-CTR (a later crypto + change, with ML-KEM-768 and P-384/P-521), the original ChaCha20 (an 8-byte nonce, a 64-bit + counter) and XChaCha20 (a 24-byte nonce) must join without a change to the concept or the free + forms; the names are the ones `basic_chacha20` already exposes and that crypto's AEADs use + (`key_size`, `nonce_size`, `tag_size`); one helper keeps every algorithm's refusal the same + error at the same kind of bound; 64 bits keeps the arithmetic in `std::uint64_t`, where a span's + size already lives - cost if wrong: an AES-CTR whose protocol increments the whole 16-byte block + as a 128-bit counter (SP 800-38A's generic increment) needs a wider counter, which that change + adds to the concept as a widening that breaks no algorithm already satisfying it. + +## A NIP-44 message, in a program + +```cpp +namespace ciphers = webcpp::crypto::ciphers; +namespace hash = webcpp::hash; + +// keys: 76 bytes of HKDF-Expand(conversation_key, nonce): the ChaCha20 key, its nonce, the HMAC key. +auto cipher = ciphers::chacha20<>::from_key(std::span(keys).first<32>()); +std::span padded = ...; // u16 length, message, zeros +if (auto const done = cipher->apply_keystream(std::span(keys).subspan<32, 12>(), padded, 0); !done) { + return done.error(); // counter_overflow never, for 65 KiB +} +// then HMAC-SHA256(hmac_key, nonce || ciphertext) and base64(0x02 || nonce || ciphertext || mac). +``` + +## Allocation analysis + +| Operation | Heap | Stack | +|---|---|---| +| `from_key` on libsodium, BearSSL | none | the object (32 bytes of key) | +| `from_key` on OpenSSL | OpenSSL's context, through OpenSSL's memory functions | the object (a pointer) | +| `apply_keystream`, every backend | none | the 12-byte nonce copy; OpenSSL's 16-byte IV | +| the asynchronous forms | the completion's own (Asio's handler allocation, recycled) | as above | +| Poly1305's `authenticate`, `verify` on libsodium | none | the tag; `verify`'s computed tag; libsodium's state | +| Poly1305's `authenticate`, `verify` on OpenSSL | the MAC context, through OpenSSL's memory functions, freed in the call (R26) | the tag; `verify`'s computed tag | + +## The queue + +- **hpke needs nothing from primitives, and primitives nothing from hpke.** hpke composes + `ciphers::chacha20_poly1305` (the AEAD) through `secret_key_encryption::aead::cipher`, never the + raw keystream; primitives uses none of hpke's names. They share files only (`error.hpp`, where + hpke takes 21 and primitives 22; `async.hpp`; `crypto.json` and its generated files; the timing + coverage tests; `paths.hpp`), which a serial order keeps free of conflicts. The order hpke then + primitives stays; primitives could run first or beside hpke with no change to either design + (R12), at the cost of merging those shared files. +- **backend-concepts after primitives** (as queued): its catalogue (its D4) gains one capability, + `detail::backend::stream_cipher` (`init`, `apply`, `move`, `reset`) for + `stream_engine` on libsodium, BearSSL and OpenSSL, with its + `crypto.json` capability cell, and a second, `detail::backend::authenticator` + (`authenticate`) for `authenticator_engine` on libsodium and OpenSSL; + nothing else of it changes. Running backend-concepts first would make this change write those + concepts itself; the queue's order costs backend-concepts two more rows and is kept. +- **part B** (the browser backend) lists ChaCha20 and Poly1305 among the constructions WebCrypto + lacks; their refusals are this change's (D6, D15), and part B's wording of "sync refuses on the + browser" covers them. +- **hpke** shares one more file with this change, `config.hpp` (the two new namespaces), which the + serial order keeps free of conflicts. +- **AES-CTR after primitives** (owner decision 7): a later crypto change, queued with ML-KEM-768 + and P-384/P-521, adds `ciphers::aes128_ctr` and `ciphers::aes256_ctr` over + `detail::basic_aes_ctr` as stream ciphers of their own shape (a 16-byte block, the + 16-byte counter block split between nonce and counter as its protocols fix); it satisfies this + change's concept and uses its free forms and `detail::counter_overflows` unchanged (R28). + +## Risks / Trade-offs + +- **A raw stream cipher invites misuse.** It authenticates nothing; the guide's section opens with + that, the rule in `crypto.json` says it, its namespace's name and page say it (owner decision 5), + and the AEAD stays the documented default. +- **The counter's end is a new refusal** a program meets only past 256 GiB from counter 0, or near + 2^32 with a high initial counter; the tests reach it with 65 bytes at counter 2^32 - 1. +- **libsodium aborts past its bound**: crypto's guard is at the same bound, and the boundary test + runs on libsodium, so a mistake in the guard shows as an abort in that test, not in a program. +- **The NIP-44 vectors come from a third party**: pinned, licence checked, SHA-256 compared with + the value NIP-44's text states; never compiled. +- **The AES block cipher has no asynchronous form** while ChaCha20 gets one (R11): a gap of the + block cipher's, recorded for the owner, not changed here. +- **A Poly1305 key reused forges tags.** crypto cannot see a second use of a key it never holds; + the namespace's name (owner decision 6), the absence of a keyed object (R21), the page's opening + rule and `crypto.json`'s rule say it, and the page points a reusable key to `hash::mac`. +- **BearSSL has no Poly1305 a program can key**, so a program on BearSSL alone composes Poly1305 + from libsodium or OpenSSL; the refusal names both. + +## Migration Plan + +No caller changes. After crypto's `formats`, codecs' Q1 and `hpke` merge: the superproject's +test-data submodule, then crypto's types, backends, forms, tests and pages on branch +`crypto/primitives` of webcpporg/crypto and of the superproject, and this change's branch of +webcpporg/proposals; every lane locally on each task's first implementation and on the final head; +merged by the stream under the owner's standing instruction; one CI run at the end. Then +backend-concepts, whose catalogue gains the stream cipher's and the authenticator's capabilities. diff --git a/libraries/crypto/openspec/changes/primitives/proposal.md b/libraries/crypto/openspec/changes/primitives/proposal.md new file mode 100644 index 0000000..b17bb07 --- /dev/null +++ b/libraries/crypto/openspec/changes/primitives/proposal.md @@ -0,0 +1,117 @@ +## Why + +webcpp::crypto has ChaCha20 only inside its AEADs: `ciphers::chacha20_poly1305` seals and opens +with Poly1305 around the keystream, and a program cannot reach the keystream itself. Protocols +that fix their own construction need the raw RFC 8439 stream cipher. The first is Nostr's NIP-44 +(version 2), the encryption of Nostr's direct messages, which webcpp's Nostr work needs: it +derives a ChaCha20 key and a 12-byte nonce with HKDF, encrypts the padded message with ChaCha20 +from block counter 0, and authenticates the nonce and the ciphertext with HMAC-SHA256; the AEAD +cannot produce those bytes. Every piece of NIP-44 but the stream cipher is already in webcpp +(secp256k1's ECDH in crypto, HKDF and HMAC in webcpp::hash, base64 in webcpp::codecs). + +On 2026-11-23 the owner approved a small change, "primitives", for ChaCha20 and the typed x-only +key; on 2026-11-24 the x-only key moved into crypto's `formats` change, and this change keeps the +raw ChaCha20 alone. NIP-44 itself stays out of crypto: its vectors only prove the cipher where a +real protocol uses it. + +On 2026-12-01 the owner added RFC 8439's raw Poly1305 (owner decision 6), the other half of the +AEAD's construction: a protocol that derives a one-time key per message (the ChaCha20 keystream's +first block, as RFC 8439 section 2.6 does) and authenticates with Poly1305 needs the authenticator +under its own key, which no AEAD exposes. It lives in crypto, not beside HMAC in `hash::mac`, +because its key must never be reused, and in a purpose namespace whose name says so. The owner also +asked for a test that composes RFC 8439's AEAD from the two raw pieces and finds +`chacha20_poly1305`'s bytes. + +## What Changes + +- **`ciphers::basic_chacha20` and `ciphers::chacha20`**, RFC 8439 + section 2.4's ChaCha20 (a 32-byte key, a 12-byte nonce, a 32-bit block counter), in + `` and ``, the + family `families::chacha20`: `from_key(key)`, and + `apply_keystream(nonce, data, initial_counter)`, which XORs the keystream from block + `initial_counter` into `data` in place (encryption and decryption are the same call); move-only, + the key wiped; every function holding webcpp::secure's `timing_guard`. +- **A purpose namespace, `crypto::unauthenticated_encryption`** (owner, 2026-11-30), sibling of + `secret_key_encryption`, in ``: the + concept `unauthenticated_encryption::stream_cipher` (not an AEAD: it authenticates nothing) and + the free form `unauthenticated_encryption::apply_keystream(cipher, nonce, data, + initial_counter)`; `crypto::from_key` serves it as it serves the AEADs. The concept reads + the algorithm's own `nonce_size`, `block_size` and `counter_type`, not ChaCha20's (owner, + 2026-12-01), so that AES-CTR, a later crypto change, joins it unchanged. Its name warns, its + page says when to use it (a protocol that brings its own authentication) and points to + `secret_key_encryption` as the normal path; `ciphers` keeps the algorithms alone. +- **A counter overflow error**: `error::counter_overflow`, a new value of `crypto::error`, returned + before any backend runs when `data` needs more blocks than the counter has left after + `initial_counter` (computed from the algorithm's block size and counter width; RFC 8439's 32-bit + counter, 256 GiB from counter 0), so that no backend wraps, + carries into the nonce or aborts the program. +- **Three backends**: libsodium (`crypto_stream_chacha20_ietf_xor_ic`, the default on every + target, as ChaCha20-Poly1305's), BearSSL (`br_chacha20_ct_run` or its SSE2 code) and OpenSSL + (`EVP_CIPHER` "ChaCha20", native, wasip2, wasip3); the capability table, its generated refusals + (ctaes and secp256k1 have no ChaCha20), `supports_v`, `default_backend_t` and the alias + `/webcpp/crypto//chacha20-default`. +- **The four forms**, as ChaCha20-Poly1305's: the member and the free synchronous forms, and + `async_from_key` and `async_apply_keystream`, member and free, in ``, + on a native backend; WebCrypto has no ChaCha20, so every form stops the build on a backend that + completes by itself (the browser backend of part B), with a refusal of its own. +- **Tests**: RFC 8439's vectors (sections 2.3.2, 2.4.2, A.1, A.2), the three backends' agreement on + random keys, nonces, counters and lengths up to the last block of the counter, the counter's + boundary on every backend, NIP-44 version 2's end-to-end vectors (paulmillr/nip44's + `nip44.vectors.json`, a new test-data submodule) composed in the tests from crypto's ChaCha20, + secp256k1 and webcpp::hash's HKDF and HMAC; the timing coverage, the constant-time lane's + paths and dudect; message tests for every refusal; no heap. + +- **`authenticators::poly1305`**, RFC 8439 section 2.5's one-time authenticator (a + 32-byte key r || s, a 16-byte tag), in ``: the static + `authenticate(key, message)`, giving the tag, and `verify(key, message, tag)`, comparing in + constant time through `secure::constant_time_equal` and returning `authentication_failed` on a + mismatch; no keyed object and no `from_key`: the key enters every call. No new error value. +- **A purpose namespace, `crypto::single_use_key_authentication`** (owner, 2026-12-01), in + ``: the concept + `single_use_key_authenticator` and the free forms `authenticate` and `verify`, and + `async_authenticate` and `async_verify` (static members and free forms) in `async.hpp`. Its page + says the key is used once, points a reusable key to `hash::mac` (HMAC), and says one-time + passwords (HOTP, TOTP) are not what it does. +- **Two backends for Poly1305**: libsodium (`crypto_onetimeauth_poly1305`, the default on every + target) and OpenSSL (`EVP_MAC` "POLY1305", native, wasip2, wasip3); BearSSL (Poly1305 only inside + its AEAD), ctaes, secp256k1 and the browser's backend refused at compile time. +- **Poly1305's tests**: RFC 8439's section 2.5.2 and Appendix A.3 vectors, the two backends' + agreement, forged tags, the timing coverage, the constant-time lane and dudect, no heap; and the + composition matrix: RFC 8439 section 2.8's AEAD built from the raw ChaCha20 and Poly1305, equal byte + for byte to `chacha20_poly1305`, across the 18 combinations of the three pieces' backends, the + AEAD itself unchanged. + +Not changed: ChaCha20-Poly1305 and its forms, every existing name, every existing error value. + +## Capabilities + +### New Capabilities + +None. + +### Modified Capabilities + +- `crypto`: RFC 8439's raw ChaCha20 stream cipher, its concept, its counter overflow error and + its three backends; RFC 8439's raw Poly1305, its purpose namespace, its concept and its two + backends. + +## Impact + +- **Kind:** a wrapper (`"port-of": null`), as the genesis. +- **Breaking:** no; new names and one new error value (22, after hpke's 21). Order: after crypto's + `formats` (on which the NIP-44 test reads its base64 through webcpp::codecs), codecs' Q1 and + crypto's `hpke`; before crypto's `backend-concepts`, whose catalogue gains the stream cipher's + and the authenticator's capabilities, and part B, whose browser backend refuses ChaCha20 and + Poly1305 through this change's refusals. + It needs nothing from `hpke` and `hpke` nothing from it (design, "The queue"). +- **Implementation:** webcpporg/crypto (`ciphers/stream_cipher.hpp`, `ciphers/chacha20.hpp`, + `unauthenticated_encryption/stream_cipher.hpp`, `authenticators/poly1305.hpp`, + `single_use_key_authentication/authenticator.hpp`, `config.hpp`, + `detail/engines.hpp`, `detail/asynchronous.hpp`, `async.hpp`, `error.hpp`, the three backends' + headers, tests, message tests and their MSVC twins, the constant-time lane's paths and dudect, + the sizes programs, the benches, an example, `doc/`, `doc/tables/crypto.json` and its generated + files), the superproject (the NIP-44 vectors as a test-data submodule, its `third_party/Jamfile` + entry, CODING-GUIDELINES.md's third-party row, the crypto fixtures, the pointer). +- **Status:** the owner approved the scope on 2026-11-23 and narrowed it on 2026-11-24 + (`decided`), answered its namespace question on 2026-11-30, and added Poly1305 and the composition test on + 2026-12-01 (about 24 hours in all); `proposed` until the owner reviews this design; `reference/plan.md` holds the plan. diff --git a/libraries/crypto/openspec/changes/primitives/reference/STATUS.md b/libraries/crypto/openspec/changes/primitives/reference/STATUS.md new file mode 100644 index 0000000..bcf20de --- /dev/null +++ b/libraries/crypto/openspec/changes/primitives/reference/STATUS.md @@ -0,0 +1,159 @@ +# webcpp::crypto primitives: where the implementation stands + +2026-12-05: delivered. crypto's branch `crypto/primitives` merged as webcpporg/crypto#30 +(`0467566`, head `2453484`), the superproject's as webcpporg/webcpp#69 (`bd1a788`, head `e4c9a8f`, +the gitlink at `0467566`); the one CI on the superproject's `main` at `bd1a788` (run 47526278354) +passed every job. Tasks 1 to 13 of `plan.md` are done, each reviewed clean, and the final +whole-branch review and its fix round approved. `tasks.md` ticks every item. 7.4's two notes, for +backend-concepts and for part B, are in the HANDBACK. + +The implementation started from the merged mains below. hpke merged first, so +`error::counter_overflow` takes 22 as the design says (R12). Every file and helper the plan names +existed on these heads; the plan needed no change of substance. + +## The heads + +| Repository | Branch | Head | +| --- | --- | --- | +| webcpporg/crypto (`libs/crypto`) | `crypto/primitives` | `2453484`, merged as `0467566` (crypto#30) | +| webcpporg/webcpp | `crypto/primitives` | `e4c9a8f` (the gitlink at `0467566`), merged as `bd1a788` (webcpp#69) | +| webcpporg/proposals | `crypto/primitives` | this commit | + +## The bases + +| Repository | Base | +| --- | --- | +| webcpporg/webcpp | `cb0bf50` (webcpp#65's merge) | +| webcpporg/crypto | `36d1279` (crypto#27's merge) | +| webcpporg/hash | `d7ea49c` | +| webcpporg/codecs | `85061b2` | +| webcpporg/secure | `a88fc50` | +| webcpporg/config | `9fb4210` | +| BearSSL pin | `f8a2f3d` (our fork, bits2int and check_scalar patches) | + +At Task 13's start each branch merged its `origin/main` (never rebased): crypto's three +constant-time and c_suites commits at `7576ecc`, the superproject at `5f4ae7c` (the `libs/crypto` +gitlink's conflict resolved to `7576ecc`); the proposals' `main` had not moved. + +## The final lanes + +On crypto `2453484` / superproject `58d4931` (the merged trees; `0467566` has `2453484`'s tree), +all local, all green; the native lanes, tools and macOS lint ran on `c638dbf`, after which only +comments (`9d66d47`) and `main`'s dudect change (the merge) moved. + +| Lane | Result | +| --- | --- | +| clang / gcc-15 / wasip2 / wasip3 / Emscripten (crypto test+example) | 776 / 550 / 723 / 705 / 455 passed, 0 failed | +| report.py over the five XMLs | every test and example passed in 5 lanes | +| agreement at release (2^30 + 64 bytes included), c-suites x4, b2 doc, generate.py --check, generate_test, crypto_jamfiles(_format), third_party, doc_test, matrix_test | pass | +| MSVC 14.3 x64 debug | 470 passed, 0 new failures | +| MSVC 14.5 x64 debug (third-party rebuilt: the VM's full disk had left cache objects corrupt) | 786 passed, 0 new failures | +| MSVC 14.5 arm64 timing_coverage_{sodium,bearssl,openssl,ctaes,secp256k1} | 5 passed, DIT checks ran | +| Constant-time, Linux (memcheck, MemorySanitizer, dudect) | judge exit 0, planted leaks found | +| Mac dudect, release (Apple M5 Max) | chacha20_keystream 2.02, poly1305_authenticate 0.84, poly1305_verify 2.43, every case <= 2.43; planted 194.24 | +| macOS full lint, Linux full lint | clean | +| CI on `main` at `bd1a788` | every job passed | + +## Rulings made while building + +- **The plan is executed inline by one worker, not by a subagent per task:** the stream runs as a + worker that may not dispatch subagents; each task still gets its own review pass and the final + head every lane. Cost: less independence in the per-task review. +- **From Task 8 on, the tasks and every review ran in subagents (coordinator's ruling, + 2026-12-05):** the controller kept the dispatch, the ledger and the lanes, which gave the reviews + back their independence. +- **The NIP-44 vectors' licence (Task 1):** paulmillr/nip44 at `671a1f0` has no licence at its + root. Its `nip44.vectors.json` is byte-identical to `javascript/test/nip44.vectors.json`, whose + directory is under the Unlicense, so the vectors are taken as Unlicense. The checkout also holds + GPL subtrees (`fsharp`, `haskell`); they are never compiled or redistributed: only the JSON is + read, as test data. +- **A `secure::secret<32>` reaches `from_key` by `bytes()` (Task 3, Task 8):** a secret converts + implicitly only to a fixed-extent span, and `from_key` takes a dynamic one (R19); HPKE gives its + keys the same way. D1, D11 and R19 now say so. +- **`chacha20_header_not_included` goes through `ciphers/stream_cipher.hpp` with libsodium linked + (Task 3):** `chacha20.hpp` includes the default's header itself, so only the class's own header + leaves a backend's header out. +- **Operation lists follow the generator (Tasks 3, 8):** the free stream cipher's operation lists + `apply_keystream` alone, and Poly1305's lists `authenticate` and `verify` unscoped: the generator + reads functions from Doc Comments, and its `class_body("poly1305")` finds the family struct first. +- **The free asynchronous forms pick the member by a requires-expression (fix round, Tasks 9, 10):** + the free `async_from_key`, `async_apply_keystream`, `async_authenticate` and `async_verify` call + the member when it exists, else run `complete_by_post` over the synchronous form; an AEAD or a + secret box without the member, and a stream cipher without a `noexcept` empty constructor + (`makes_empty_v`), stop with a `static_assert` of their own, each pinned by a message test. Why: a + third-party type with only the synchronous members still works, and nothing fails deep. +- **The AEAD branch of `async_from_key` needs `aead::cipher || is_secretbox_v` (fix round):** a + stream cipher on an asynchronous backend goes to its own member or the fallback, not the AEAD + refusal. `async_from_key_not_a_cipher` refuses a crypto_box, the case its text names. +- **`agree_large` holds one buffer of 2^30 + 64 bytes, applied in place (fix round):** about 1 GiB + at peak instead of 3; the backends' keystreams restore the message exactly when they are equal. +- **NIP-44's HMAC state is not wiped (fix round):** Boost.Hash2's `hmac` has no wipe; the + HKDF-extract digest and the conversation keys are, and the vectors' keys are public. +- **`authenticators::poly1305` has `name_type = families::poly1305` (Task 8):** `supports_v` and the + capabilities test read it, as ChaCha20's; D11 now lists it. +- **`poly1305_header_not_included` joined in Task 9, not Task 8:** with libsodium the only backend, + `poly1305.hpp` includes its header whenever libsodium is linked, so the refusal was unreachable + until OpenSSL's header gave it a case. +- **The synchronous free forms meet the asynchronous-backend refusal through the member (Task 8):** + the concept names no backend type, so the free form cannot refuse by itself; the message is the + same one. +- **The constant-time cases check their output with `carries_mark` (Task 7):** the plan said + `mark_public`; the code checks that the keystream XORed in (and Poly1305's tag) carries the + secret's mark, as the existing cases do. The plan and D16 follow. +- **`test/support/capabilities.hpp`'s `made()` makes an algorithm that is no object (Task 8):** it + authenticates the empty message, so Poly1305 joins the capabilities test as the types do. +- **`poly1305_openssl_memory_resource` (Task 9):** a second Jamfile target of + `poly1305_openssl_test.cpp`, native only, that defines `openssl_memory_resource()` and never + installs the adapter, so `memory_functions_not_installed` is tested. +- **OpenSSL has no canary (Task 9):** Poly1305's and ChaCha20's OpenSSL engines read none; D4 and + D14 said each engine reads its canary. An empty message goes to OpenSSL as a pointer to a static + byte. +- **R26's cost measured (Task 9):** an OpenSSL Poly1305 call makes about 54 allocations through + OpenSSL's functions, none through `operator new`. +- **Message test names (Tasks 9, 11, final round):** Ed25519 already had + `verify_asynchronous_backend`, so Poly1305's is `verify_poly1305_asynchronous_backend`. MSVC twins + take shorter names where the object path would pass Windows' 260 characters + (`async_authenticate_not_an_authenticator`, `async_verify_not_an_authenticator`, + `async_from_key_stream_cipher_no_empty`, `from_key_chacha20_poly1305_async_backend`) or to match those siblings + (`verify_not_an_authenticator`). +- **`check_rfc8439_composition` takes the cases `run_composition_matrix` draws once (Task 9):** + every backend combination runs the same cases; the plan gave it no argument. +- **`test/support/agreement.hpp`'s locals named `near` are renamed (Task 9):** `` + defines `near` as a macro, which broke the composition test on MSVC only. +- **Poly1305's dudect case compares two failing tags (Task 10):** the right tag with its last byte + flipped against it with its first byte flipped, not D16's match against mismatch. Why: on Apple + M5 Max, release, match against mismatch read |t| 32.71 and 13.97, and the experiments put the + difference on the public verdict's return path (success against `authentication_failed`, about + 0.4 ns), not on the comparison (two failing classes 0.87, A/A 2.18 and 2.24); the AEAD open case + already compares two failing classes. D16 and the plan follow. +- **dudect_sodium's Poly1305 cell judges on wasip2 (Task 10):** dudect_sodium judges its cases + there (only `x25519_agree` is printed unjudged), as Ed25519's and X25519's cells do; + `poly1305_count` is 2,000,000, the count of calls of tens of nanoseconds. +- **The generator reads a free function's brief from its namespace (Task 11):** crypto.json may name + `namespace::name`, and a plain name two namespaces declare is a Fault. Why: llms.txt gave + Ed25519's `async_verify` Poly1305's brief; the Fault also moved `async_gcm`'s `async_seal` and + `async_open` to `secret_key_encryption::aead::`. +- **The guide's text rules (Task 11):** briefs are one sentence (MrDocs' reference check); a + possessive on code ("`code`'s") is rephrased, which the rendered check refuses; the changelog's + libsodium line names the raw pieces within its 30-word cap and no line is added (10 lines). +- **The guide's additions (Task 11):** the `chacha20_keystream` example prints RFC 8439 section + 2.4.2's ciphertext and plaintext in hex, then `counter_overflow` from counter 2^32 - 1 with the + data untouched; "The namespaces by purpose" gains `unauthenticated_encryption`, `authenticators` + and `single_use_key_authentication`; test sources the guide quotes gain include tags. +- **`doc/tables/sizes.json` rewritten whole (Task 11):** all seven release tables were re-measured, + so every row is dated 2026-12-05; throughput stays "not measured yet" for the owner's release + pass (R16). +- **CODING-GUIDELINES (Task 12):** chapter 17 gains "The primitives change (built, not merged)"; + chapter 19 cites no ChaCha20 or Poly1305 size, so none moved. The formats change and hash's + Base58Check, merged on 2026-12-02, still read "built, not merged" there; they are now merged. +- **The engines' refusal is silent on a backend that completes by itself (final review):** a kept + `from_key` (or `from_keys`) result destroys an object, whose destructor names the engine; the + generated refusal then added "has no backend of that name" after the member's own refusal. + ChaCha20's, the AEADs', the secret boxes' and the boxes' refusal structs are now empty there, each + pinned by a message test (`from_key_chacha20_asynchronous_backend` and its three siblings). GCM's + engine keeps its refusal: WebCrypto has AES-GCM, so part B's browser backend specialises its + engine, and only a stand-in reaches the primary. +- **OpenSSL's ChaCha20 runs in pieces of 2^30 bytes (final review):** `openssl_update` takes the + piece size, its default GCM's and ChaCha20-Poly1305's `INT_MAX / 16 * 16`; ChaCha20 gives + `std::size_t{1} << 30`, whole 64-byte blocks (R18), so the release agreement test's 2^30 + 64 + bytes cross one piece's end. Before, its one piece was larger than the test. diff --git a/libraries/crypto/openspec/changes/primitives/reference/plan.md b/libraries/crypto/openspec/changes/primitives/reference/plan.md new file mode 100644 index 0000000..6990da7 --- /dev/null +++ b/libraries/crypto/openspec/changes/primitives/reference/plan.md @@ -0,0 +1,1290 @@ +# crypto primitives (raw ChaCha20 and Poly1305) Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** RFC 8439's raw ChaCha20 in webcpp::crypto: `ciphers::basic_chacha20` +and `ciphers::chacha20` with `from_key` and `apply_keystream(nonce, data, +initial_counter)`, the concept `unauthenticated_encryption::stream_cipher` and its free forms, the error +`counter_overflow`, libsodium (the default), BearSSL and OpenSSL, the four forms, the timing +guard, the constant-time lane and dudect, proven by RFC 8439's vectors, the backends' agreement +and NIP-44 version 2's end-to-end vectors; and RFC 8439's raw Poly1305 (owner decision 6): +`authenticators::poly1305` with the static `authenticate(key, message)` and +`verify(key, message, tag)`, the concept `single_use_key_authentication::single_use_key_authenticator` +and its free forms, libsodium (the default) and OpenSSL, BearSSL refused, the four forms, proven by +RFC 8439's section 2.5.2 and Appendix A.3 vectors, the two backends' agreement and a test that +composes RFC 8439 section 2.8's AEAD from the raw ChaCha20 and Poly1305 and finds +`chacha20_poly1305`'s bytes. + +**Budget:** about 25 hours in all: about 17 for ChaCha20 (Tasks 1 to 7 and its share of 11 to 13), +about 6 for Poly1305 (Tasks 8 to 10 and its share of 11 to 13), under 1 for the composition test +(Task 9), owner decision 6, and under 1 for the concept that reads the algorithm's shape and its +stand-in test (Tasks 3 and 5), owner decision 7. + +**Architecture:** one superproject task first (the NIP-44 vectors as test data), then crypto in +three groups. Group 1 adds the error value, then the type, its contract and its concept on +libsodium with the generated table, then BearSSL and OpenSSL and their agreement. Group 2 adds +the asynchronous forms and the browser's refusal, NIP-44's vectors and the constant-time lane. +Group 3 is Poly1305: its type, its purpose namespace and its concept on libsodium with the +generated table, then OpenSSL, the agreement, the asynchronous forms and the browser's refusal, +then the constant-time lane. Group 4 is the guide, the measurements' programs, the superproject +and the delivery. Every engine +follows ChaCha20-Poly1305's (`detail/engines.hpp`'s traits, a backend's header specialising +them), every public function its guard and its coverage line. + +**Tech Stack:** C++20 header-only, b2 5.5.3, Boost 1.92 (System's `result`, Core's +LightweightTest, Hash2, JSON in tests, Asio through webcpp::asio), webcpp::secure, webcpp::hash +(HKDF, HMAC, SHA-256), webcpp::codecs (base64, in one test), libsodium, BearSSL, OpenSSL 3.5.9, +libsecp256k1 (the superproject's pins), clang (Apple), gcc 15, wasi-sdk 34 (wasip2, wasip3), +Emscripten 6.0.11, MSVC 14.3 and 14.5 (the owner's Windows 11 ARM64 VM), Valgrind, clang 18's +MemorySanitizer (Linux container), dudect. + +**Spec:** this change, `libraries/crypto/openspec/changes/primitives/` of webcpporg/proposals at +the commit that adds this plan: `proposal.md`, `design.md` (owner decisions 1 to 7, D1 to D17, R1 +to R28, all binding), `specs/crypto/spec.md` (binding), `tasks.md`. Read the design +before any task, and ChaCha20-Poly1305's code it mirrors: `include/webcpp/crypto/ciphers/aead.hpp`, +`ciphers/chacha20_poly1305.hpp`, `secret_key_encryption/aead.hpp`, the three backends' `aead_*` +specialisations, `async.hpp`'s ChaCha20-Poly1305 forms, `detail/asynchronous.hpp`, +`test/support/aead_checks.hpp`, `test/support/timing_coverage.hpp`'s `cover_aead`; for Poly1305 +also BearSSL's tag comparison in `backends/bearssl.hpp` (`constant_time_equal`, `declassify`, the +wipe), `async.hpp`'s `async_generate` and `async_from_key` (a static member and its free form) and +webcpp::hash's ``, the reusable-key MAC the page points to. + +## Open for the owner + +Nothing. The first draft's Q1 (the namespace of the concept and the free forms) is answered by +owner decision 5 (design, 2026-11-30): `crypto::unauthenticated_encryption`, the concept and the +synchronous free form in ``, the +asynchronous free form in `async.hpp`; the type stays in `ciphers`. Owner decision 6 +(2026-12-01) adds Poly1305 and names its purpose namespace `crypto::single_use_key_authentication`; +the same day the owner added the composition test (D17, R27) and freed the stream cipher's concept +from ChaCha20's shape (owner decision 7, R28: the concept reads the algorithm's own `nonce_size`, +`block_size` and `counter_type`, the counter's end computed by `detail::counter_overflows`, AES-CTR +the motivating later consumer); the design rules the rest (R20 to R27). + +**Paths:** `$W` is the owner's workspace directory, the folder that holds `heavy.sh`, +`msvc-lane/`, `linux-lint/` and this stream's folder `primitives/` (a plan in the proposals +repository names no machine path). `$S` is `$W/primitives/webcpp`, the superproject worktree on +branch `crypto/primitives`; its `libs/crypto` is on branch `crypto/primitives` of +webcpporg/crypto; `libs/hash`, `libs/codecs`, `libs/secure` and `libs/config` stay at their merged +`main` and are never touched. Every command runs from `$S`. Never create another worktree or tree. + +**Commands:** `B2` means +`env -u CPATH -u CPLUS_INCLUDE_PATH -u C_INCLUDE_PATH b2 --user-config=.local/user-config.jam`. +The lanes: +- native: `B2 toolset=clang `; `B2 toolset=gcc-15 ` +- wasip2: `B2 toolset=clang-wasip2 testing.launcher=tools/boost/asio-wasip2/run.sh ` +- wasip3: `B2 toolset=clang-wasip3 testing.launcher=tools/boost/asio-wasip3/run.sh ` +- Emscripten: `B2 toolset=emscripten ` +- "the five local lanes" means all of the above over the task's targets (incremental while + iterating; `-a` only in the delivery). +- MSVC, the essential set (owner's rule): `$W/heavy.sh primitives $W/msvc-lane/run-lane.sh <14.3|14.5> --tree $W/primitives/lane-tree [--arch arm64] -- `, + read with `$W/msvc-lane/summarize.sh <14.3|14.5> ` (`new failures:` empty): x64 debug + on 14.3 and 14.5 over the task's targets; arm64 on 14.5 only for the DIT and timing tests + (`libs/crypto/test//timing libs/crypto/test//timing_sodium libs/crypto/test//timing_coverage_sodium libs/crypto/test//timing_coverage_bearssl libs/crypto/test//timing_coverage_secp256k1 libs/crypto/test//timing_coverage_openssl libs/crypto/test/constant_time//dudect`); + no release. Commit, then `$W/primitives/refresh-tree.sh`, before a run: the lane tree is built + from committed heads. +- The constant-time lane on Linux: `$W/heavy.sh primitives $W/primitives/ct-run/linux.sh crypto constant-time`; + dudect natively on this Mac: `B2 toolset=clang variant=release libs/crypto/test/constant_time//dudect` + then its run as the Jamfile's `dudect` target says. +- The generator: `python3 libs/crypto/doc/tables/generate.py` (and `--check`); the superproject's + fixtures: `python3 tools/test/crypto_jamfiles_test.py`; the third party's: `python3 tools/test/third_party_test.py`. +- A whole library from scratch, the full lints and the MSVC lane are heavy: only through + `$W/heavy.sh primitives `. + +**Which lanes a task runs (owner's rule):** a task's first implementation runs the five local +lanes over its targets, MSVC 14.3 and 14.5 x64 debug over its targets when its "Lanes" line names +MSVC, arm64 14.5's timing set when it adds or changes a guarded function, and the constant-time +lane or dudect when its "Lanes" line names them. A fix round (review findings, a failing lane) +runs only the affected tests on one lane (native clang debug) and the lint, plus a special lane +(MSVC, constant-time, dudect) only when the fix changed that lane's subject. Every lane runs +again on the final head (Task 13). + +**The lint step of every task:** commit, then +`$W/primitives/lint.sh $W/primitives/lint-task.log ` +(the macOS half, clang-format's check and clang-tidy from `.local/wasi-sdk/bin/` over the files' +translation units of the compilation database, then the Linux lint, `$W/linux-lint/run.sh --files` +on the lane tree, through heavy.sh); fix every finding of one run in the task's own commit +(`crypto: ... lint fix`), run once more; a task reaches review lint-clean. Format C++ first with +`.local/wasi-sdk/bin/clang-format -i `. Deleted files are not passed. + +## Preflight (the controller, before Task 1) + +- [ ] crypto's `formats`, codecs' Q1 and crypto's `hpke` are merged: `git -C $W/webcpp fetch origin` + shows the superproject's `origin/main` with `libs/crypto` at a `main` that holds + `include/webcpp/crypto/formats.hpp` and `error::message_limit_reached = 21`. If hpke is not + merged, the stream still takes 22 (design R12) and says so in `reference/STATUS.md`. +- [ ] `$S`: `git -C $W/webcpp worktree add $W/primitives/webcpp -b crypto/primitives origin/main`; + `git -C $S submodule update --init libs/config libs/secure libs/codecs libs/hash libs/crypto libs/asio` + and the third-party submodules crypto's tests name (`third_party/libs/wycheproof`, `bips`, + `secp256k1`, `bearssl`, `libsodium`, `openssl`, `xkcp`, Boost); `ln -sfn $W/webcpp/.local $S/.local`; + `git -C $S/libs/crypto switch -c crypto/primitives`. +- [ ] Record in a new `reference/STATUS.md` of this change the base SHAs: superproject, crypto, + hash, codecs, secure, config. +- [ ] The stream's tools (not committed), copied from `$W/formats/` with `formats` -> `primitives`: + `refresh-tree.sh` (its loop over `crypto` alone), `lint.sh`, `ct-run/linux.sh` and `inside.sh` + (container `ct-primitives`, volume `ct-primitives-work`). Check `lint.sh` on Task 1's files + before dispatching Task 2. + +## Global Constraints + +- English in files; never the em dash character, use "-"; commit messages with no trailer at all; + never hand-edit CHANGELOG.md or generated files (`doc/generated/*`, `doc/llms.txt`, + `detail/capabilities.hpp`, `detail/defaults.hpp`, the defaults' aliases in `build.jam`, + `test/capabilities_test.cpp`: change `doc/tables/crypto.json` or the generator and run it); + "Copyright (c) 2026 WebCpp.org" BSL-1.0 headers; heavy work only through heavy.sh; flaky tests + and lint warnings are defects to fix; measurements only from release builds; never contact + upstream projects; merge origin/main into branches, never rebase; no GitHub CI run until the + final one. +- Commit subjects in each repository's style: `crypto: ...`; superproject + `libs/crypto: the gitlink at ()`, `tools: ...`, `third_party: ...`, + `guidelines: ...`. Never `git add -A` or `git add libs` in the superproject. +- Names, verbatim from the design: `families::chacha20`, `ciphers::basic_chacha20`, + `ciphers::chacha20`, `from_key`, `apply_keystream`, `async_from_key`, + `async_apply_keystream`, `counter_type`, `block_size`, `max_message_size`, the concept + `unauthenticated_encryption::stream_cipher` and the free `unauthenticated_encryption::apply_keystream`, `unauthenticated_encryption::async_apply_keystream` + (owner decision 5; the namespace holds no algorithm), `error::counter_overflow = 22`, `detail::stream_state`, `detail::stream_engine`, + `detail::stream_family`, `detail::stream_sizes`, `detail::refuse_stream_cipher_on_asynchronous_backend`, + `detail::counter_overflows` (owner decision 7; the concept's shape members `nonce_size`, + `block_size`, `counter_type`, never ChaCha20's 12, 64 and `std::uint32_t` in the concept, the free + forms or the helper), the test-only `webcpp::test::stand_in_stream_cipher`, + the alias `/webcpp/crypto//chacha20-default`; parameters `key_bytes`, `nonce_bytes`, + `data_bytes`, `initial_counter`; every public name spelled out; no two-word naming rule. +- Poly1305's names, verbatim from the design (owner decision 6, D11 to D16): `families::poly1305`, + `authenticators::poly1305` (no `basic_poly1305`, no constructor), `key_size`, `tag_size`, + `result_type` (`boost::hash2::digest<16>`), the static `authenticate`, `verify`, + `async_authenticate`, `async_verify`; the namespace `single_use_key_authentication` with the + concept `single_use_key_authenticator` and the free `authenticate`, `verify`, + `async_authenticate`, `async_verify`; `detail::authenticator_engine`, + `detail::authenticator_refusal`, `detail::refuse_single_use_key_authenticator_on_asynchronous_backend`; + the alias `/webcpp/crypto//poly1305-default`; parameters `key_bytes`, `message_bytes`, + `tag_bytes`. No `from_key` and no keyed object (R21); no new error value (R23). +- `ciphers::chacha20_poly1305` keeps calling each backend's combined function: the composition of + Task 9 is a test (`test/support/composition_checks.hpp`), never a code path of `include/` (R27). +- Nothing existing changes name or behaviour: ChaCha20-Poly1305, the AEAD contract, the boxes, the + error values 1 to 21. The only existing text that changes is `crypto::async_from_key`'s refusal + (it now names a stream cipher too) and its message test; `crypto::from_key`'s refusal, which + Poly1305 meets, is unchanged. +- Exceptions (the owner's standing rule): every library builds without exceptions and may throw + where they are available; the cipher's functions are `noexcept` (no allocator is involved); + every test runs with exceptions on and off (`crypto-run`). +- The guard: every new function holds `secure::timing_guard` first (`secure::timing_guard const + timing_scope;`) and joins its backend's timing coverage test; every wipe is + `secure::erase_secret`. +- `nodiscard-results` (crypto's `meta/lint.json`): every function of `include/` that returns + `boost::system::result` is `[[nodiscard]]`. +- Every new message test has its `crypto.json` entry (`fixes`) and, where MSVC builds it, its + `test/msvc/` twin, in the same commit; every new test its `crypto.json` operation's `tests`; + the generator names what is missing. +- NIP-44 stays out of `include/`: its composition lives in `test/support/nip44.hpp` alone. +- A Poly1305 tag is compared only with `secure::constant_time_equal`, never `==`, `memcmp` or a + backend's own verify; the computed tag is wiped and the verdict declassified where crypto first + branches on it (D12). +- The owner's VM: never shut it down, suspend or reconfigure it; `$W/msvc-lane/known-failures.txt` + is never edited. + +## Review Focus + +1. **The counter's end on libsodium.** 65 bytes at initial counter 2^32 - 1, 64 bytes at + 2^32 - 1, and 192 bytes (3 blocks) at 2^32 - 3. Expected: the first `counter_overflow` with the + data untouched and no abort (libsodium's `sodium_misuse` has the same bound), the others + accepted and equal across backends. Task 3 pins it on libsodium, + Task 4 on BearSSL and OpenSSL and their agreement. +2. **The nonce and the data overlapping.** The nonce a span over the data's first 12 bytes, and + over bytes 20 to 31. Expected: the keystream of the original nonce on every backend (R5). Task 3 + and Task 4 pin it. +3. **A moved-from object, and an error completion's object.** `apply_keystream` on the source of a + move, on the empty object `async_from_key` completes with after `invalid_key_size`. Expected: + `invalid_state`, data untouched. Tasks 3 and 5. +4. **OpenSSL's IV and its pieces.** A call from counter 2^32 - 2 over 128 bytes, a call of more + than 2^30 bytes on a 64-bit native build (2^30 + 64, two pieces, in the release agreement run + only, R18), a second call after the first on the same object with another counter. Expected: the + bytes of libsodium. Task 4. +5. **The browser's refusal is the one error.** `apply_keystream`, the free form, `async_from_key` + and `async_apply_keystream` on the stand-in backend. Expected: the build stops with the + stream cipher's refusal alone (`alone` in each message test). Task 5. +6. **Poly1305's `verify` on a mismatch and on a backend's failure.** A tag with its last bit + flipped, a tag of 15 and 17 bytes, a key of 31 bytes with a tag of 15, and OpenSSL with + `WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE` and the adapter not installed. Expected: + `authentication_failed`, `invalid_tag_size`, `invalid_key_size`, `memory_functions_not_installed` + (never `authentication_failed`); the computed tag wiped in every path. Tasks 8 and 9. +7. **Poly1305's empty message and the key's single copy.** The empty message with a null `data()` + on both backends gives s; no `std::array` of the key in crypto's code (grep the engine and the + class). Tasks 8 and 9. +8. **Poly1305 on BearSSL and on the browser.** `poly1305::authenticate` and + every form on the stand-in backend. Expected: the generated refusal naming libsodium and OpenSSL, + and the browser's refusal, each alone. Tasks 8 and 9. +9. **The composition matrix against the AEAD.** Section 2.8.2's vector and a random case with aad + of 17 bytes and a message of 65 bytes in every one of the 18 combinations (BearSSL's raw ChaCha20 + with OpenSSL's Poly1305 against libsodium's AEAD among them), and a deliberately broken cell in a + scratch run. Expected: the composed ciphertext and tag equal `chacha20_poly1305`'s seal byte + for byte; the broken cell's message names its three backends; `aead.hpp` and the backends' AEAD engines + unchanged by the branch (`git diff` names none of their lines). Task 9. + +## The files + +| File | Holds | Task | +| --- | --- | --- | +| `include/webcpp/crypto/error.hpp` | `counter_overflow = 22` and its message | 2 | +| `include/webcpp/crypto/ciphers/stream_cipher.hpp` | `families::chacha20`'s definition, `detail::stream_family`, `detail::stream_sizes`, the primary `detail::stream_state` and `stream_engine` with the generated refusal, `basic_chacha20`; it includes the concept's header | 3 | +| `include/webcpp/crypto/unauthenticated_encryption/stream_cipher.hpp` | the concept `unauthenticated_encryption::stream_cipher` (the algorithm's own shape, owner decision 7), `detail::counter_overflows`, the free `apply_keystream` and its catch-all; no backend, no cipher | 3 | +| `include/webcpp/crypto/config.hpp` | the namespace `unauthenticated_encryption` declared | 3 | +| `include/webcpp/crypto/ciphers/chacha20.hpp` | the alias `chacha20`, the default backend's include, the concept checks | 3 | +| `include/webcpp/crypto/detail/engines.hpp` | the declarations of `stream_state` and `stream_engine` | 3 | +| `include/webcpp/crypto/backends/{sodium,bearssl,openssl}.hpp` | each backend's `stream_state` and `stream_engine` | 3, 4 | +| `include/webcpp/crypto/detail/asynchronous.hpp` | `refuse_stream_cipher_on_asynchronous_backend` | 5 | +| `include/webcpp/crypto/async.hpp` | the members' definitions, the free `unauthenticated_encryption::async_apply_keystream`, `crypto::async_from_key`'s branch | 5 | +| `test/support/stream_cipher_checks.hpp` | RFC 8439's vectors and the contract's checks every backend's test runs | 3 | +| `test/stream_cipher_shape_test.cpp` | the test-only `stand_in_stream_cipher` (8-byte nonce, 16-byte block, `std::uint8_t` counter) through the concept, the free forms and `detail::counter_overflows` (owner decision 7) | 3, 5 | +| `test/support/nip44.hpp` | the tests' NIP-44 composition | 6 | +| `include/webcpp/crypto/authenticators/poly1305.hpp` | `families::poly1305`'s definition, `detail::authenticator_refusal`, the primary `detail::authenticator_engine` with the generated refusal, `authenticators::poly1305`; it includes the concept's header and the default's backend | 8 | +| `include/webcpp/crypto/single_use_key_authentication/authenticator.hpp` | the concept `single_use_key_authenticator`, the free `authenticate` and `verify` and their catch-alls; no backend, no algorithm | 8 | +| `include/webcpp/crypto/config.hpp` | the namespaces `authenticators` and `single_use_key_authentication` declared | 8 | +| `include/webcpp/crypto/detail/engines.hpp` | the declaration of `authenticator_engine` | 8 | +| `include/webcpp/crypto/backends/{sodium,openssl}.hpp` | each backend's `authenticator_engine` | 8, 9 | +| `include/webcpp/crypto/detail/asynchronous.hpp`, `include/webcpp/crypto/async.hpp` | Poly1305's refusal, its static members' definitions, the free asynchronous forms | 9 | +| `test/support/authenticator_checks.hpp` | RFC 8439's Poly1305 vectors, the portable reference, the contract's checks | 8 | + +--- + +### Task 1: The NIP-44 vectors as test data (superproject) + +Model tier: standard. Covers tasks.md 1.1; design D9, R13. + +**Files (superproject):** +- Modify: `.gitmodules`, `third_party/Jamfile` (a `nip44` alias after `bips`', the same shape as + `wycheproof`'s), `CODING-GUIDELINES.md` (the third-party table's row), `tools/test/third_party_test.py` + (the pin's test, as `test_wycheproof_is_pinned`). +- Create: the submodule `third_party/libs/nip44`. + +- [ ] **Step 1: Check the licence and the file before adding anything.** Clone + `https://github.com/paulmillr/nip44` into a fresh scratch directory (data, never built); read its + licence file at the commit of its default branch's head and record the commit, its date and the + licence; compute `shasum -a 256 nip44.vectors.json` and compare it with the SHA-256 that NIP-44's + text (`44.md` of nostr-protocol/nips, read on github.com) states for the vectors. Stop and report + to the controller if the licence is not one CODING-GUIDELINES' chapter 5 accepts for test data + or if the hashes differ; the controller asks the owner. +- [ ] **Step 2: Write the failing test.** `third_party_test.py` gains `test_nip44_is_pinned`: the + gitlink of `third_party/libs/nip44` is the recorded commit, and `.gitmodules` names it with + `shallow = true`. +- [ ] **Step 3: Run, expect failure.** `python3 tools/test/third_party_test.py`: the gitlink is + missing. +- [ ] **Step 4: Add it.** `git submodule add --depth 1 https://github.com/paulmillr/nip44 third_party/libs/nip44`, + checked out at the recorded commit; `.gitmodules` `shallow = true`. `third_party/Jamfile`: + +```jam +# paulmillr/nip44 (), the vectors NIP-44 version 2's text pins by +# SHA-256: test data, never compiled. A test that names nip44 reads +# nip44.vectors.json from the directory WEBCPP_TEST_NIP44 names, with forward +# slashes, the directory given to wasmtime on WASI (webcpp.data), and runs +# again when the file changes. +path-constant NIP44 : libs/nip44 ; +.nip44 = [ regex.replace $(NIP44) "\\\\" "/" ] ; + +rule nip44-checked-out ( properties * ) +{ + if ! [ path.exists [ path.native $(NIP44)/nip44.vectors.json ] ] + { + errors.user-error "third_party/libs/nip44 is not checked out: it holds no" + "nip44.vectors.json. Check it out with `git submodule update" + "--init third_party/libs/nip44`." ; + } +} + +alias nip44 : : @nip44-checked-out : : + "\"WEBCPP_TEST_NIP44=\\\"$(.nip44)\\\"\"" + [ webcpp.data $(NIP44) ] + $(NIP44)/nip44.vectors.json ; +explicit nip44 ; +``` + + The guidelines' row: "`nip44` | paulmillr/nip44 at `` (), shallow, test data: + crypto's tests read `nip44.vectors.json`, NIP-44 version 2's vectors, whose SHA-256 NIP-44's + text states, under the directory its define `WEBCPP_TEST_NIP44` gives, on every target (wasmtime + is given it, `webcpp.data`) | ". +- [ ] **Step 5: Run.** `python3 tools/test/third_party_test.py`; `python3 tools/test/doc_test.py` + if it checks the guidelines' table. Expected: pass. +- [ ] **Step 6: Commit, lint.** `third_party: NIP-44 version 2's vectors (paulmillr/nip44 at ), test data for crypto's ChaCha20`. Lint step over the Jamfile, the guidelines and the test. + +**Lanes:** the tools' tests only (no C++). + +--- + +### Task 2: The error value `counter_overflow` + +Model tier: fast. Covers tasks.md 1.2; design D7, R12. + +**Files (libs/crypto):** modify `include/webcpp/crypto/error.hpp`, `test/error_test.cpp`, +`doc/errors.adoc`. + +**Interfaces:** +- Produces: + +```cpp +enum class error : int { + // ... 1 to 21 unchanged + /** + * A stream cipher's data that needs more blocks than its counter has left after the initial + * counter: RFC 8439's ChaCha20 has a 32-bit block counter, 256 GiB of keystream from counter 0. + */ + counter_overflow = 22, +}; +// message_of: "the data needs more blocks than the stream cipher's counter has left after the initial counter" +``` + +- [ ] **Step 1: Write the failing test.** `error_test.cpp`: `error::counter_overflow` is 22, its + message the text above, its category `webcpp.crypto`, and `make_error_code` round-trips it, as + the test does for the others. +- [ ] **Step 2: Run, expect failure.** `B2 toolset=clang libs/crypto/test//error`: no member + `counter_overflow`. +- [ ] **Step 3: Implement** the value, its message, the errors page's row. +- [ ] **Step 4: Run.** The five local lanes over `libs/crypto/test//error`. Expected: pass. +- [ ] **Step 5: Commit, lint.** `crypto: error::counter_overflow (22), a stream cipher's counter exhausted`. Lint step. + +**Lanes:** the five local lanes over the error test. + +--- + +### Task 3: ChaCha20, its contract and its concept, on libsodium + +Model tier: most capable (a new public type, its contract, the generated table). Covers tasks.md +2.1; design D1 to D5, D9, R1 to R9, R15, R17, R19, R28 (owner decision 7). + +**Files:** +- Create (libs/crypto): `include/webcpp/crypto/ciphers/stream_cipher.hpp`, + `include/webcpp/crypto/unauthenticated_encryption/stream_cipher.hpp`, + `include/webcpp/crypto/ciphers/chacha20.hpp`, `test/support/stream_cipher_checks.hpp`, + `test/chacha20_sodium_test.cpp`, `test/stream_cipher_concepts_test.cpp`, + `test/stream_cipher_shape_test.cpp`, the message tests + `test/messages/{chacha20_not_a_family,chacha20_unknown_backend,chacha20_on_ctaes,chacha20_default_not_linked,chacha20_header_not_included,apply_keystream_not_a_stream_cipher}/` + and their `test/msvc/` twins. +- Modify (libs/crypto): `include/webcpp/crypto/detail/engines.hpp`, + `include/webcpp/crypto/config.hpp` (declares `namespace webcpp::crypto::unauthenticated_encryption {}`, + documented as the home of encryption that authenticates nothing, for protocols that bring their + own authentication), `meta/include-boundaries.json` (if it lists the purpose namespaces' + directories: `unauthenticated_encryption/` with `secret_key_encryption/`'s rule, no backend and + no cipher header), + `include/webcpp/crypto/backends/sodium.hpp`, `include/webcpp/crypto.hpp` (the convenience header + includes `ciphers/chacha20.hpp` where it includes `chacha20_poly1305.hpp`), `test/Jamfile`, + `test/messages/Jamfile`, `test/msvc/Jamfile`, `test/Jamfile`'s header list (the headers that + compile alone), `test/support/timing_coverage.hpp` (`cover_stream_cipher`, + `cover_stream_cipher_free_forms`), `test/timing_coverage_sodium_test.cpp`, + `test/allocation_sodium_test.cpp`, `doc/tables/crypto.json`, `AGENTS.md` (ten traits); then the + generator's outputs. +- Create (superproject): `tools/test/fixtures/crypto_jamfiles/chacha20_default/` (its `Jamfile` + and `app.cpp`, as `chacha20_poly1305_default`'s). + +**Interfaces:** +- Consumes: Task 2's `counter_overflow`. +- Produces (design D1, D3; the bodies follow `basic_chacha20_poly1305`'s line by line): + +```cpp +// +namespace webcpp::crypto::families { +struct chacha20 { + static constexpr std::size_t key_size = 32; + static constexpr std::size_t nonce_size = 12; + static constexpr std::size_t block_size = 64; + using counter_type = std::uint32_t; + static constexpr std::uint64_t max_message_size = std::uint64_t{1} << 38U; +}; +} +namespace webcpp::crypto::detail { +template inline constexpr bool stream_family = false; +template <> inline constexpr bool stream_family = true; +template > struct stream_sizes : Family {}; +template struct stream_sizes { /* placeholders, counter_type std::uint32_t */ }; +template struct stream_state {}; +template struct stream_refusal {}; +template struct stream_refusal { + WEBCPP_CRYPTO_DETAIL_REFUSE_CHACHA20(Backend); +}; +template +struct stream_engine : stream_refusal { + // init, apply -> error::backend_failure (fail closed); move, reset empty: never called. +}; +} +namespace webcpp::crypto::ciphers { +template class basic_chacha20; // design D1's members +} +// , which ciphers/stream_cipher.hpp includes +// (as ciphers/aead.hpp includes secret_key_encryption/aead.hpp); config, secure and System only. +// Nothing in it names ChaCha20's 12, 64 or std::uint32_t (owner decision 7): +namespace webcpp::crypto::detail { +// design D3's body: blocks = ceil(data_size / BlockSize) in 64 bits, true exactly when +// blocks != 0 && blocks - 1 > max(Counter) - initial_counter (no sum that can wrap). +template + requires(BlockSize > 0 && std::numeric_limits::digits <= 64) +[[nodiscard]] constexpr bool counter_overflows(std::uint64_t data_size, Counter initial_counter) noexcept; +} +namespace webcpp::crypto::unauthenticated_encryption { +// design D3: key_size, nonce_size, block_size (> 0), counter_type (std::unsigned_integral, at most +// 64 bits), from_key, apply_keystream; the algorithm's own shape, never ChaCha20's. +template concept stream_cipher = /* design D3 */; +template +[[nodiscard]] boost::system::result apply_keystream(Cipher& keyed_cipher, + std::span nonce_bytes, std::span data_bytes, + typename Cipher::counter_type initial_counter) noexcept(noexcept( + keyed_cipher.apply_keystream(nonce_bytes, data_bytes, initial_counter))); +// The catch-all, so that an AEAD or a block cipher given to it says what it is: its body is one +// static_assert(detail::dependent_false, "webcpp::crypto: unauthenticated_encryption::apply_keystream takes a stream +// cipher (ciphers::chacha20); an AEAD seals and opens through secret_key_encryption::aead."); +template + requires(!stream_cipher) +void apply_keystream(Cipher& keyed_cipher, Arguments&&... arguments) noexcept; +} +// +namespace webcpp::crypto::ciphers { +template > +using chacha20 = basic_chacha20; +static_assert(stream_cipher>); +static_assert(!secret_key_encryption::aead::cipher>); +} +// : template struct stream_state; +// template struct stream_engine; +// (apply takes std::span and typename Family::counter_type) +// : +template <> struct stream_state { std::array key{}; }; +template <> struct stream_engine { + [[nodiscard]] static boost::system::result init(state&, std::span key_bytes) noexcept; + [[nodiscard]] static boost::system::result apply(state&, std::span nonce_bytes, + std::uint32_t initial_counter, std::span data_bytes) noexcept; // crypto_stream_chacha20_ietf_xor_ic, in place + static void move(state& target, state& source) noexcept; + static void reset(state&) noexcept; +}; +``` + + `apply_keystream`'s body (design D2): the guard; (Task 5 inserts here the refusal on a backend + that completes by itself, with its tests); `invalid_state`; `invalid_nonce_size`; the overflow + check + +```cpp +if (detail::counter_overflows(data_bytes.size(), initial_counter)) { + return error::counter_overflow; // for ChaCha20: blocks > 2^32 - initial_counter, as before +} +``` + + (the helper divides before it rounds up, so no size a span holds wraps it); then empty data + returns success; then the nonce copied into a `std::array`; then `engine::apply`; on its failure `secure::erase_secret(data_bytes)`. + +- [ ] **Step 1: Write the failing tests.** + - `stream_cipher_checks.hpp`, `template void check_stream_cipher()`, run by + `chacha20_sodium_test.cpp` on `ciphers::chacha20` (and by Task 4's on the + others), with RFC 8439's bytes typed in hex in the header: section 2.3.2's key, nonce and + counter 1 over 64 zero bytes give the section's serialized block; section 2.4.2's plaintext + (114 bytes) at counter 1 gives its ciphertext and back; Appendix A.1's test vectors 1 to 5 + (keystream of 64 zero bytes at each vector's counter); Appendix A.2's vectors 1 to 3 (counters + 0, 1 and 42). The guards: a 31- and a 33-byte key `invalid_key_size`; nonces of 0, 8, 11, 13 + and 24 bytes `invalid_nonce_size` with the data untouched; a moved-from object + `invalid_state`; `invalid_state` before `invalid_nonce_size` (both wrong). The counter: + 64 bytes at 2^32 - 1 accepted and equal to the RFC block function's output computed by the + test's own portable reference (a 30-line ChaCha20 block in the support header, written from + RFC 8439 section 2.3's pseudocode, used for the boundary cells the RFC has no vector for), 65 + bytes at 2^32 - 1 `counter_overflow` with the data untouched, 128 bytes at 2^32 - 2 accepted; + 0 bytes at 2^32 - 1 accepted. The stream continued: 128 bytes from counter 7 equal 64 from 7 + then 64 from 8. The nonce inside the data (Review Focus 2). Empty data with a null `data()`. + The key as a `secure::secret<32>` lvalue, given by `bytes()`. Moving: the target works, the + source refuses, a self-move assignment keeps the key. + - `stream_cipher_concepts_test.cpp`: `unauthenticated_encryption::stream_cipher>`; + `!secret_key_encryption::aead::cipher>`; + `!secret_key_encryption::authenticated_box>`; + `!unauthenticated_encryption::stream_cipher>`, `>>`, + `>`, `>`; `crypto::from_key>(key)` + and the member give objects whose `apply_keystream` and `unauthenticated_encryption::apply_keystream` give the same + bytes; a generic function over `stream_cipher` (the guide's tagged snippet, `tag=generic`). + - `stream_cipher_shape_test.cpp` (owner decision 7; no backend linked): the test-only + `webcpp::test::stand_in_stream_cipher`, as the other stand-ins of crypto's tests are, with + `key_size` 16, `nonce_size` 8, `block_size` 16, `counter_type` `std::uint8_t`, `from_key`, and an + `apply_keystream` that refuses `invalid_nonce_size`, then calls + `detail::counter_overflows` for `counter_overflow`, then XORs a keystream of its own + (each byte a function of the key, the nonce, the block's counter and the byte's place). + Compile time: `static_assert(unauthenticated_encryption::stream_cipher)`; + a `requires` expression that `unauthenticated_encryption::apply_keystream(cipher, nonce, data, + std::uint8_t{})` is well formed and gives `result`; `static_assert`s of + `detail::counter_overflows`: `<16>` with `std::uint8_t` 16 bytes at 255 false, 17 at 255 true, + 4096 from 0 false, 4097 from 0 true; `<64>` with `std::uint32_t` 64 bytes at 2^32 - 1 false, 65 + true, 128 at 2^32 - 2 false, 0 at 2^32 - 1 false; `<64>` with `std::uint64_t` 65 bytes at + 2^64 - 1 true, 2^64 - 1 bytes from 0 false. Run time: the free form and the member give the same + bytes; 16 bytes at counter 255 accepted; 17 bytes at 255 `counter_overflow` and a 12-byte nonce + `invalid_nonce_size`, each with the data untouched; `crypto::from_key` + makes one. Register `crypto-run stream_cipher_shape : stream_cipher_shape_test.cpp ;` and list it + in the operation's `tests`. + - Message tests (each `webcpp.compile-diagnostic ... : native wasip2 wasip3 : alone`, clang's + `-verify` text on one line): `chacha20_not_a_family` (`basic_chacha20`: + "webcpp::crypto: ciphers::basic_chacha20 takes a stream family: families::chacha20."); + `chacha20_unknown_backend`, `chacha20_on_ctaes`, `chacha20_default_not_linked`, + `chacha20_header_not_included` (the generated texts, copied from `capabilities.hpp` after + Step 3's generator run, as the ChaCha20-Poly1305 twins are); `apply_keystream_not_a_stream_cipher`. + Each with its `test/msvc//` twin (`Jamfile`, `app.cpp`) as `chacha_on_ctaes`'s. + - `timing_coverage_sodium_test.cpp`: `webcpp::test::cover_stream_cipher>("chacha20", "sodium")`, + which calls `from_key`, `apply_keystream`, `crypto::from_key` and `unauthenticated_encryption::apply_keystream` + and checks each entered its guard (`cover_aead`'s pattern; Task 5 adds the asynchronous + two to it). + - `allocation_sodium_test.cpp`: `from_key` and `apply_keystream` of 1 KiB allocate nothing. + - The superproject fixture `chacha20_default`: an `app.cpp` that applies RFC 8439 section 2.4.2 + with `ciphers::chacha20<>` and a Jamfile with `/webcpp/crypto//crypto /webcpp/crypto//chacha20-default`. + Register the tests in `test/Jamfile` (`crypto-run chacha20_sodium : chacha20_sodium_test.cpp : /third_party//sodium ;`, + `crypto-run stream_cipher_concepts : stream_cipher_concepts_test.cpp : /third_party//sodium ;`) + and in `crypto.json` (the operation's `tests`, the `fixes`, the `fixtures`). +- [ ] **Step 2: Run, expect failure.** `B2 toolset=clang libs/crypto/test//chacha20_sodium`: + `ciphers/chacha20.hpp` not found. +- [ ] **Step 3: Implement.** `crypto.json` first: the family `chacha20` (design D5; `default`: + `{"targets": ["native", "wasip2", "wasip3", "emscripten"], "backend": "sodium", "tests": + ["chacha20_sodium", "default_backend_none_linked"], "why": "ChaCha20-Poly1305's default, so that + a program that uses both links one library; libsodium's own C code, constant time, the same on + every target ({libsodium-stream})"}` with the source `libsodium-stream` added; `backends`: + `sodium` alone in this task, `bearssl` and `openssl` in Task 4), the operation entry in + `ciphers`, the namespace `unauthenticated_encryption` in `namespaces` (owner decision 5; its + free forms' operation entry there), the fixture; run the generator, which writes the forward declaration, the refusal + macro, the default, the alias and the capabilities test. `default_backend_none_linked`'s test + gains `chacha20`'s cell if the generator asks. Then the headers and the engine; the engine: + +```cpp +[[nodiscard]] static boost::system::result apply( + state& engine_state, std::span nonce_bytes, std::uint32_t initial_counter, + std::span data_bytes) noexcept { + read_canary(WEBCPP_CRYPTO_DETAIL_SODIUM_CANARY); + // In place: libsodium's xor functions take the output equal to the input. Its own bound on the + // counter (sodium_misuse) is the one basic_chacha20 checked, so it is never reached. + if (crypto_stream_chacha20_ietf_xor_ic(data_bytes.data(), data_bytes.data(), data_bytes.size(), + nonce_bytes.data(), initial_counter, engine_state.key.data()) != 0) { + return error::backend_failure; + } + return {}; +} +``` + + with `#include ` beside the AEAD's includes. `AGENTS.md`'s + traits line names `stream_state` and `stream_engine`. Rerun the generator. +- [ ] **Step 4: Run.** The five local lanes over `libs/crypto/test//chacha20_sodium + libs/crypto/test//stream_cipher_concepts libs/crypto/test//stream_cipher_shape + libs/crypto/test//timing_coverage_sodium + libs/crypto/test//allocation_sodium libs/crypto/test//capabilities libs/crypto/test/messages`; + `python3 libs/crypto/doc/tables/generate.py --check`; `python3 libs/crypto/doc/tables/generate_test.py`; + `python3 tools/test/crypto_jamfiles_test.py`. MSVC 14.3 and 14.5 x64 debug over the new tests + and `libs/crypto/test/msvc`; arm64 14.5's timing set. Expected: pass. +- [ ] **Step 5: Commit, lint.** crypto: `crypto: ciphers::chacha20, RFC 8439's raw stream cipher, its contract, the concept stream_cipher and its free form, on libsodium`; superproject: `tools: the crypto fixture chacha20_default`. Lint step. + +**Lanes:** the five local lanes, MSVC 14.3 and 14.5 x64 debug, arm64 timing set. + +--- + +### Task 4: BearSSL and OpenSSL, and the backends' agreement + +Model tier: standard. Covers tasks.md 2.2; design D4, D9, R18. + +**Files:** +- Modify (libs/crypto): `include/webcpp/crypto/backends/bearssl.hpp`, + `include/webcpp/crypto/backends/openssl.hpp`, `test/Jamfile`, `test/timing_coverage_bearssl_test.cpp`, + `test/timing_coverage_openssl_test.cpp`, `test/allocation_bearssl_test.cpp`, + `test/allocation_openssl_test.cpp`, `doc/tables/crypto.json` (the two backends, their tests, the + `lane` cells as D8 says, OpenSSL's `lane_note` as ChaCha20-Poly1305's); the generator's outputs. +- Create (libs/crypto): `test/chacha20_bearssl_test.cpp`, `test/chacha20_bearssl_portable_test.cpp` + (the seam `WEBCPP_CRYPTO_DETAIL_BEARSSL_PORTABLE`, as `agreement_chacha_portable`'s Jamfile line + sets it), `test/chacha20_openssl_test.cpp`, `test/agreement_chacha20_test.cpp`, + `test/agreement_chacha20_portable_test.cpp`. + +**Interfaces:** +- Consumes: Task 3's class, engine traits and `check_stream_cipher`. +- Produces: + +```cpp +// backends/bearssl.hpp +template <> struct stream_state { std::array key{}; }; +template <> struct stream_engine { + // init: read_canary, copy; apply: read_canary, + // bearssl_chacha20()(engine_state.key.data(), nonce_bytes.data(), initial_counter, data_bytes.data(), data_bytes.size()); + // (its returned counter is discarded); move: copy and wipe; reset: wipe. +}; +// backends/openssl.hpp +template <> struct stream_state { EVP_CIPHER_CTX* context = nullptr; }; +template <> struct stream_engine { + // init: openssl_context(made_context, "ChaCha20", key_bytes, ...) as ChaCha20-Poly1305's, with no IV. + // apply: std::array iv: bytes 0-3 initial_counter little-endian, 4-15 the nonce; + // EVP_CipherInit_ex(context, nullptr, nullptr, nullptr, iv.data(), 1) == 1 (as GCM's engine), else backend_failure; + // then EVP_CipherUpdate(context, out, &written, in, piece) over pieces of 2^30 bytes (whole blocks, the last shorter), + // each written == piece, else backend_failure; no EVP_CipherFinal (a stream cipher has no final block). + // move: the pointer; reset: EVP_CIPHER_CTX_free, then wipe the state. +}; +``` + + Read `openssl_context`'s parameters in `backends/openssl.hpp` (it is GCM's and + ChaCha20-Poly1305's helper) and pass what a cipher without a tag needs; if it insists on an + AEAD's IV length, the engine calls `EVP_CIPHER_fetch(nullptr, "ChaCha20", nullptr)`, + `EVP_CIPHER_CTX_new` and `EVP_CipherInit_ex(context, cipher, nullptr, key, nullptr, 1)` itself, + with the memory functions' check `openssl_context` does, and frees the fetched cipher. + +- [ ] **Step 1: Write the failing tests.** `chacha20_bearssl_test.cpp`, its portable twin and + `chacha20_openssl_test.cpp` call `check_stream_cipher>()`. + `agreement_chacha20_test.cpp` (`test/support/agreement.hpp`'s generator, as `agreement_chacha`): + 2000 random cases per run of key, nonce, initial counter (0, 1, a random 32-bit value capped so + that the case fits, `2^32 - blocks`) and length (0 to 1024 bytes, 63, 64, 65, 127, 128, 129, + 64 KiB), the three backends' outputs equal and equal to the support header's reference; two + calls continuing by the counter equal one; the same object reused with several nonces and + counters (OpenSSL's re-initialised IV); natively at release only, one case of 2^30 + 64 bytes + (Review Focus 4; skipped where `size_t` is 32 bits or the build is debug). Its Emscripten and + portable twins as `agreement_chacha`'s (Emscripten without OpenSSL). Timing coverage: + `cover_stream_cipher>` and ``. Allocation: + `apply_keystream` allocates nothing on both; OpenSSL's `from_key` allocates through OpenSSL's + memory functions only, as its ChaCha20-Poly1305 case says. Register all in `test/Jamfile` and + `crypto.json`. +- [ ] **Step 2: Run, expect failure.** `B2 toolset=clang libs/crypto/test//chacha20_bearssl`: + the generated refusal "bearssl's ChaCha20 is in " is the + one error, since no engine is specialised yet (or the generator's table still lacks BearSSL: + "ChaCha20 has no backend of that name"). +- [ ] **Step 3: Implement** the two engines and the `crypto.json` cells; rerun the generator. +- [ ] **Step 4: Run.** The five local lanes over the new tests, `libs/crypto/test//timing_coverage_bearssl + libs/crypto/test//timing_coverage_openssl libs/crypto/test//allocation_bearssl + libs/crypto/test//allocation_openssl libs/crypto/test//capabilities libs/crypto/test/messages` + (the generated texts now name three backends: the message tests of Task 3 that pin them are + updated in this commit); `generate.py --check`. MSVC 14.3 and 14.5 x64 debug over the new tests + and `libs/crypto/test/msvc`; arm64 14.5's timing set. Expected: pass. +- [ ] **Step 5: Commit, lint.** `crypto: ChaCha20 on BearSSL and OpenSSL, the three backends' agreement`. Lint step. + +**Lanes:** the five local lanes, MSVC 14.3 and 14.5 x64 debug, arm64 timing set. + +--- + +### Task 5: The asynchronous forms and the browser's refusal + +Model tier: standard. Covers tasks.md 3.1; design D6, R10, R11, R28. + +**Files:** +- Modify (libs/crypto): `include/webcpp/crypto/ciphers/stream_cipher.hpp` (the declarations, the + refusal branch in every member), `include/webcpp/crypto/detail/asynchronous.hpp`, + `include/webcpp/crypto/async.hpp` (its header comment's list, the definitions, the free form, + `crypto::async_from_key`'s branch and refusal text), `test/support/timing_coverage.hpp` + (`cover_async_stream_cipher`, called by `cover_stream_cipher`), the three timing coverage tests, + `test/messages/async_from_key_*` whose text names what `async_from_key` takes, + `test/stream_cipher_shape_test.cpp` (the stand-in gains `async_apply_keystream`, defined with + `detail::complete_by_post` over its synchronous member), `test/Jamfile`, + `doc/tables/crypto.json`. +- Create (libs/crypto): `test/async_stream_cipher_test.cpp`, the message tests + `test/messages/{apply_keystream_asynchronous_backend,async_apply_keystream_asynchronous_backend,async_from_key_chacha20_asynchronous_backend}/` + and their MSVC twins. + +**Interfaces:** +- Consumes: Tasks 3 and 4. +- Produces: + +```cpp +// detail/asynchronous.hpp +template +constexpr void refuse_stream_cipher_on_asynchronous_backend() noexcept { + static_assert(!asynchronous_backend_v, + "webcpp::crypto: WebCrypto has no ChaCha20: no form of the raw stream cipher, " + "synchronous or asynchronous, runs on the browser's backend; name a native " + "backend for it."); +} +// basic_chacha20 (declared in the class, defined in async.hpp with detail::complete_by_post, as +// basic_chacha20_poly1305's async_from_key and async_seal are): +template +static auto async_from_key(Executor const& completion_executor, std::span key_bytes, + CompletionToken&& completion_token); // void(error_code, basic_chacha20) +template +auto async_apply_keystream(Executor const& completion_executor, std::span nonce_bytes, + std::span data_bytes, counter_type initial_counter, + CompletionToken&& completion_token); // void(error_code) +// async.hpp, namespace unauthenticated_encryption: +// (owner decision 7: it names no backend and reads only the algorithm's counter_type; it calls the member) +template +auto async_apply_keystream(Executor const& completion_executor, Cipher& keyed_cipher, + std::span nonce_bytes, std::span data_bytes, + typename Cipher::counter_type initial_counter, CompletionToken&& completion_token); +// crypto::async_from_key: accepts secret_key_encryption::aead::cipher, unauthenticated_encryption::stream_cipher +// or a secret box; refusal text: "webcpp::crypto: async_from_key takes an AEAD (a +// secret_key_encryption::aead::cipher), a stream cipher (a unauthenticated_encryption::stream_cipher) or a secret box: +// a crypto_box is made by from_keys."; a stream cipher on an asynchronous backend calls +// detail::refuse_stream_cipher_on_asynchronous_backend. +``` + + Every member of `basic_chacha20` (`from_key`, `apply_keystream`, the two asynchronous members) + checks `detail::asynchronous_backend_v` right after its guard and calls the refusal, + before naming any member of the engine (ruling P12 of part A, as `basic_chacha20_poly1305` + does). The free synchronous and asynchronous forms name no backend (owner decision 7), so that a + stream cipher of another shape works through them; they meet the refusal through the member they + call, and the message tests' `alone` pins that it is still the one error. + +- [ ] **Step 1: Write the failing tests.** `async_stream_cipher_test.cpp`, on libsodium (and + BearSSL, OpenSSL where linked): with an `io_context` and a callback, `use_awaitable` (where the + build has coroutines, as `async_aead_test`), `deferred`: `async_from_key` gives an object whose + keystream is RFC 8439 section 2.4.2's; `async_apply_keystream`, member and free, gives the + synchronous bytes; each completes through the executor, never inside the initiating call; an + `invalid_key_size` completion's object refuses with `invalid_state`; `counter_overflow` and + `invalid_nonce_size` complete with the data untouched. `stream_cipher_shape_test`: the free + `async_apply_keystream` on the stand-in, with a callback, gives its synchronous bytes for 16 bytes + at counter 255 and completes with `counter_overflow` for 17, the data untouched; a `requires` + expression that it is well formed with `std::uint8_t`. The three message tests on a stand-in + backend (`asynchronous_backend_v = true`, the object a parameter, as + `open_asynchronous_backend`), each `alone`; the updated text of `async_from_key`'s existing + refusal tests. The timing coverage gains the two asynchronous forms on each backend. Register + all. +- [ ] **Step 2: Run, expect failure.** `B2 toolset=clang libs/crypto/test//async_stream_cipher`: + no member `async_from_key` in `basic_chacha20`. +- [ ] **Step 3: Implement** the declarations, the definitions, the refusal and its calls, the + free form, `async_from_key`'s branch; `async.hpp`'s header comment lists the stream cipher's + forms beside the AEADs' and boxes'. Rerun the generator (`crypto.json`'s operation lists + `basic_chacha20::async_from_key`, `basic_chacha20::async_apply_keystream` and the free + `async_apply_keystream`). +- [ ] **Step 4: Run.** The five local lanes over `libs/crypto/test//async_stream_cipher + libs/crypto/test//stream_cipher_shape libs/crypto/test//async_aead libs/crypto/test//timing_coverage_sodium + libs/crypto/test//timing_coverage_bearssl libs/crypto/test//timing_coverage_openssl + libs/crypto/test/messages`; `generate.py --check`. MSVC 14.3 and 14.5 x64 debug over these and + `libs/crypto/test/msvc`; arm64 14.5's timing set. Expected: pass. +- [ ] **Step 5: Commit, lint.** `crypto: ChaCha20's asynchronous forms, member and free, and its refusal on a backend that completes by itself`. Lint step. + +**Lanes:** the five local lanes, MSVC 14.3 and 14.5 x64 debug, arm64 timing set. + +--- + +### Task 6: NIP-44's end-to-end vectors + +Model tier: standard. Covers tasks.md 4.1; design D9, R13. + +**Files:** +- Create (libs/crypto): `test/support/nip44.hpp`, `test/chacha20_nip44_sodium_test.cpp`, + `test/chacha20_nip44_bearssl_test.cpp`, `test/chacha20_nip44_openssl_test.cpp` (one `.cpp` per + backend, crypto's rule; each a call of the support's `run_vectors()`). +- Modify (libs/crypto): `test/Jamfile` (each test names `/third_party//nip44`, + `/third_party//secp256k1`, its backend, `/webcpp/hash//hash`, `/webcpp/codecs//codecs`), + `doc/tables/crypto.json` (the tests in the operation's lists, the source `nip44` cited). + +**Interfaces:** +- Consumes: Tasks 1, 3, 4; secp256k1's `basic_keypair::from_secret`, `public_key::from_bytes`, + `agree` (the shared x, `secure::secret<32>`); webcpp::hash's `hkdf_extract(salt, + input_key_material)`, `hkdf_expand(output, pseudorandom_key, application_info)`, + `hmac_sha2_256`, `sha2_256`; codecs' `codecs::formats::base64` with `codecs::encode` and + `codecs::decode`. Read each signature in its header before writing the support. +- Produces (test only, never in `include/`): + +```cpp +namespace webcpp::test::nip44 { +// NIP-44 version 2, composed from webcpp's pieces as the NIP says. +template boost::system::result> conversation_key( + std::span secret_key, std::span peer_xonly); // agree on 02||x, HKDF-Extract("nip44-v2") +struct message_keys { std::array chacha_key; std::array chacha_nonce; + std::array hmac_key; }; // wiped by the caller +message_keys derive_message_keys(std::span conversation_key, + std::span nonce); // HKDF-Expand, 76 bytes +std::size_t padded_length(std::size_t plaintext_length); // NIP-44's calc_padded_len +template std::string encrypt(std::span conversation_key, + std::span nonce, std::string_view plaintext); // base64 payload +template boost::system::result decrypt( + std::span conversation_key, std::string_view payload); // MAC checked first +template void run_vectors(); // the four valid sections of nip44.vectors.json +} +``` + +- [ ] **Step 1: Write the failing tests.** `run_vectors()` reads + `WEBCPP_TEST_NIP44 "/nip44.vectors.json"` with Boost.JSON (as the Wycheproof readers do) and + checks: every `v2.valid.get_conversation_key` entry (`sec1`, `pub2` -> `conversation_key`); + every `v2.valid.get_message_keys.keys` entry under its `conversation_key` (`chacha_key`, + `chacha_nonce`, `hmac_key`); every `v2.valid.calc_padded_len` pair; every + `v2.valid.encrypt_decrypt` entry (`encrypt` gives `payload`, `decrypt` gives `plaintext`, and + `conversation_key(sec2, pub(sec1))` gives the same conversation key); every + `v2.valid.encrypt_decrypt_long_msg` entry (`pattern` repeated `repeat` times, the SHA-256 of the + plaintext and of the payload). A count of each section's entries is printed and checked nonzero, + so that a renamed key in the file fails the test instead of passing it empty. The `invalid` + sections are not run (R13). The JSON keys are read as the pinned file names them; confirm them + in the file before writing the reader. +- [ ] **Step 2: Run, expect failure.** `B2 toolset=clang libs/crypto/test//chacha20_nip44_sodium`: + `test/support/nip44.hpp` not found. +- [ ] **Step 3: Implement** the support. ChaCha20 is `Cipher::from_key(keys.chacha_key)` and + `apply_keystream(keys.chacha_nonce, padded, 0)`; the payload is `0x02 || nonce || ciphertext || + mac`; every key buffer is wiped with `secure::erase_secret` at the end of its scope. +- [ ] **Step 4: Run.** The five local lanes over the three tests (Emscripten without the OpenSSL + one). MSVC 14.3 and 14.5 x64 debug over them. Expected: pass. +- [ ] **Step 5: Commit, lint.** `crypto: NIP-44 version 2's end-to-end vectors through ChaCha20 on the three backends, NIP-44 composed in the tests alone`. Lint step. + +**Lanes:** the five local lanes, MSVC 14.3 and 14.5 x64 debug. + +--- + +### Task 7: Constant time: the lane's paths and dudect + +Model tier: standard. Covers tasks.md 5.1; design D8. + +**Files (libs/crypto):** modify `test/constant_time/paths.hpp` (a path `keystream(name)` and its two calls in `common_paths`), `test/constant_time/ctgrind_test.cpp` +(OpenSSL's keystream, memcheck alone), `test/constant_time/dudect_test.cpp` (the case +`chacha20_keystream` and its selection name), `test/constant_time/Jamfile` (its comment's list of +paths), `doc/tables/crypto.json` (the family's `lane` cells: sodium memcheck and msan, bearssl +memcheck, msan and dudect natively and on wasip2, openssl memcheck), the generator's outputs. + +- [ ] **Step 1: Write the paths.** `keystream`: a key and 200 bytes of data + marked secret (`Checker::mark_secret`), `from_key`, `apply_keystream` from counter 1, the result + checked with `carries_mark(data)`, the keystream XORed in carrying the secret mark, as + `seal_and_open` checks its outputs (ChaCha20 has no verdict: nothing is marked public); the + object destroyed (its wipe traced). Calls: + `keystream>("BearSSL ChaCha20")` and + `>("ChaCha20 on libsodium")`; in `ctgrind_test.cpp`, + OpenSSL's `chacha20` as its ChaCha20-Poly1305 seal. dudect: the case + `chacha20_keystream`, class 0 the all-zero key and class 1 random keys, nonce, counter and 64 + bytes of data fixed, measuring `apply_keystream` on BearSSL, added to the selection list and to + the program's comment; its A/A control is the program's existing one. +- [ ] **Step 2: Run the planted checks first** (they prove the checkers still see a leak): + `$W/heavy.sh primitives $W/primitives/ct-run/linux.sh crypto constant-time`. Expected: the + planted programs fail as designed, every path passes; no new suppression is needed (ChaCha20 has + no verdict to declassify). +- [ ] **Step 3: dudect natively** at release (`variant=release`), the new case alone through + `--case chacha20_keystream`, then the whole program; on wasip2 through the lane's own run. + Expected: |t| under the program's threshold for the case and its control; a reading at or above + 10 is investigated, never suppressed (the harness's hosted-runner rule does not apply locally). +- [ ] **Step 4: Run** `generate.py --check`; the five local lanes over + `libs/crypto/test/constant_time` where the Jamfile builds them (native and wasip2). Expected: + pass. +- [ ] **Step 5: Commit, lint.** `crypto: ChaCha20 in the constant-time lane (BearSSL and libsodium under memcheck and MemorySanitizer, OpenSSL under memcheck) and in dudect`. Lint step. + +**Lanes:** the constant-time lane, Mac dudect, the native and wasip2 lanes over +`libs/crypto/test/constant_time`. + +--- + +### Task 8: Poly1305, its contract and its purpose namespace, on libsodium + +Model tier: most capable (a new public type, a new purpose namespace, the generated table). Covers +tasks.md 6.1; design D11 to D14, R20 to R25. + +**Files:** +- Create (libs/crypto): `include/webcpp/crypto/authenticators/poly1305.hpp`, + `include/webcpp/crypto/single_use_key_authentication/authenticator.hpp`, + `test/support/authenticator_checks.hpp`, `test/poly1305_sodium_test.cpp`, + `test/authenticator_concepts_test.cpp`, the message tests + `test/messages/{poly1305_on_bearssl,poly1305_on_ctaes,poly1305_unknown_backend,poly1305_default_not_linked,poly1305_header_not_included,authenticate_not_a_single_use_key_authenticator,from_key_poly1305}/` + and their `test/msvc/` twins. +- Modify (libs/crypto): `include/webcpp/crypto/detail/engines.hpp`, `include/webcpp/crypto/config.hpp` + (declares `namespace webcpp::crypto::authenticators {}`, documented as the algorithms that + authenticate, and `namespace webcpp::crypto::single_use_key_authentication {}`, documented as the + home of authenticators whose key is used once), `meta/include-boundaries.json` (if it lists the + purpose namespaces: `single_use_key_authentication/` with `secret_key_encryption/`'s rule), + `include/webcpp/crypto/backends/sodium.hpp`, `include/webcpp/crypto.hpp` (includes + `authenticators/poly1305.hpp` beside `ciphers/chacha20.hpp`), `test/Jamfile`, + `test/messages/Jamfile`, `test/msvc/Jamfile`, the header list, `test/support/timing_coverage.hpp` + (`cover_single_use_key_authenticator`), `test/timing_coverage_sodium_test.cpp`, + `test/allocation_sodium_test.cpp`, `doc/tables/crypto.json`, `AGENTS.md` (eleven traits); the + generator's outputs. +- Create (superproject): `tools/test/fixtures/crypto_jamfiles/poly1305_default/` (`Jamfile`, `app.cpp`). + +**Interfaces:** +- Consumes: crypto's `error::invalid_key_size`, `invalid_tag_size`, `authentication_failed`; + `secure::constant_time_equal`, `secure::declassify`, `secure::erase_secret`. +- Produces (design D11, D13; bodies as D12 orders them): + +```cpp +// +namespace webcpp::crypto::families { +struct poly1305 { static constexpr std::size_t key_size = 32; static constexpr std::size_t tag_size = 16; }; +} +namespace webcpp::crypto::detail { +template struct authenticator_refusal {}; +template struct authenticator_refusal { + WEBCPP_CRYPTO_DETAIL_REFUSE_POLY1305(Backend); +}; +template +struct authenticator_engine : authenticator_refusal { + // authenticate -> error::backend_failure (fail closed): never called. +}; +} +namespace webcpp::crypto::authenticators { +template > class poly1305; // design D11's members +} +// : config, secure, Hash2's digest, System only +namespace webcpp::crypto::single_use_key_authentication { +template concept single_use_key_authenticator = /* design D13 */; +template +[[nodiscard]] boost::system::result authenticate( + std::span key_bytes, std::span message_bytes) noexcept(...); +template +[[nodiscard]] boost::system::result verify(std::span key_bytes, + std::span message_bytes, std::span tag_bytes) noexcept(...); +template + requires(!single_use_key_authenticator) +void authenticate(Arguments&&... arguments) noexcept; // static_assert(detail::dependent_false, D13's text) +template + requires(!single_use_key_authenticator) +void verify(Arguments&&... arguments) noexcept; +} +// : +template <> struct authenticator_engine { + [[nodiscard]] static boost::system::result authenticate(std::span key_bytes, + std::span message_bytes, std::span tag_bytes) noexcept; + // read_canary; sodium_ready(); crypto_onetimeauth_poly1305(tag, message or &empty_byte, size, key) +}; +``` + + `verify`'s tail (design D12), as BearSSL's AEAD open compares: + +```cpp +// NOLINTNEXTLINE(misc-const-correctness): the declassifying request must reach a mutable object +bool tag_matches = secure::constant_time_equal(computed_tag, tag_bytes.first()); +secure::declassify(tag_matches); +secure::erase_secret(computed_tag); +if (!tag_matches) { + return error::authentication_failed; +} +return {}; +``` + +- [ ] **Step 1: Write the failing tests.** + - `authenticator_checks.hpp`, `template void check_single_use_key_authenticator()`, + with RFC 8439's bytes in hex: section 2.5.2 (key, "Cryptographic Forum Research Group", tag + `a8061dc1305136c6c22b8baf0c0127a9`); Appendix A.3's vectors 1 to 11; each through the static + members and the free forms, `verify` accepting each tag. A portable reference + (`reference_poly1305`, about 40 lines from RFC 8439 section 2.5's pseudocode, 130-bit + arithmetic in 26-bit limbs) checked against the same vectors. The guards: keys of 0, 31 and 33 + bytes `invalid_key_size`; tags of 0, 15 and 17 bytes `invalid_tag_size`; both wrong + `invalid_key_size`. Forgeries: each of the 16 tag bytes with its low and high bit flipped, a + message bit flipped, the message one byte shorter, each `authentication_failed`. The empty + message with a null `data()` gives s. The key as a `secure::secret<32>` lvalue, given by + `bytes()`. Overlapping key, message and tag spans. + - `authenticator_concepts_test.cpp`: + `single_use_key_authenticator>`; not for + `ciphers::chacha20_poly1305<>`, `ciphers::chacha20<>`, `ciphers::gcm>`, + `secret_key_encryption::secretbox<>`, `hash::macs::hmac`; + `!unauthenticated_encryption::stream_cipher>`, + `!secret_key_encryption::aead::cipher>`, + `!std::is_default_constructible_v>`; the static and free forms give + the same tags and errors; a generic function over the concept (`tag=generic`). + - Message tests (each `webcpp.compile-diagnostic ... : native wasip2 wasip3 : alone`): + `poly1305_on_bearssl` ("bearssl has no Poly1305", the generated text naming libsodium and + OpenSSL), `poly1305_on_ctaes`, `poly1305_unknown_backend`, `poly1305_default_not_linked`, + `poly1305_header_not_included` (texts copied from `capabilities.hpp` after Step 3's run); + `authenticate_not_a_single_use_key_authenticator` (an HMAC tag type given to the free form); + `from_key_poly1305` (`crypto::from_key>`, `factories.hpp`'s + existing text). Each with its `test/msvc/` twin. + - `timing_coverage_sodium_test.cpp`: + `webcpp::test::cover_single_use_key_authenticator>("poly1305", "sodium")`, + calling the static and free `authenticate`, `verify` with a matching and a mismatching tag, + each checked to have entered its guard. + - `allocation_sodium_test.cpp`: `authenticate` and `verify` over 1 KiB allocate nothing. + - The fixture `poly1305_default`: section 2.5.2 with `authenticators::poly1305<>` and + `/webcpp/crypto//poly1305-default`. + Register `crypto-run poly1305_sodium : poly1305_sodium_test.cpp : /third_party//sodium ;`, + `crypto-run authenticator_concepts : ...`, and the `crypto.json` entries. +- [ ] **Step 2: Run, expect failure.** `B2 toolset=clang libs/crypto/test//poly1305_sodium`: + `authenticators/poly1305.hpp` not found. +- [ ] **Step 3: Implement.** `crypto.json` first (design D14: the family, `sodium` alone in this + task, the default `{"targets": ["native", "wasip2", "wasip3", "emscripten"], "backend": "sodium", + "tests": ["poly1305_sodium", "default_backend_none_linked"], "why": "ChaCha20's and + ChaCha20-Poly1305's default, so that a program composing them links one library + ({libsodium-onetimeauth})"}`, the source `libsodium-onetimeauth`, the namespace + `single_use_key_authentication` and its operation entries, the fixture); run the generator; then + the headers and the engine with `#include `; `AGENTS.md`; + rerun the generator. +- [ ] **Step 4: Run.** The five local lanes over `libs/crypto/test//poly1305_sodium + libs/crypto/test//authenticator_concepts libs/crypto/test//timing_coverage_sodium + libs/crypto/test//allocation_sodium libs/crypto/test//capabilities libs/crypto/test/messages`; + `generate.py --check`; `generate_test.py`; `python3 tools/test/crypto_jamfiles_test.py`. MSVC + 14.3 and 14.5 x64 debug over the new tests and `libs/crypto/test/msvc`; arm64 14.5's timing set. + Expected: pass. +- [ ] **Step 5: Commit, lint.** crypto: `crypto: authenticators::poly1305, RFC 8439's one-time authenticator, the concept single_use_key_authenticator and its free forms, on libsodium`; superproject: `tools: the crypto fixture poly1305_default`. Lint step. + +**Lanes:** the five local lanes, MSVC 14.3 and 14.5 x64 debug, arm64 timing set. + +--- + +### Task 9: Poly1305 on OpenSSL, the agreement, the composition test, the asynchronous forms + +Model tier: standard. Covers tasks.md 6.2 and 6.3; design D14 to D17, R26, R27. + +**Files:** +- Modify (libs/crypto): `include/webcpp/crypto/backends/openssl.hpp`, + `include/webcpp/crypto/authenticators/poly1305.hpp` (the refusal branch in every form), + `include/webcpp/crypto/single_use_key_authentication/authenticator.hpp` (the refusal in the free + forms), `include/webcpp/crypto/detail/asynchronous.hpp`, `include/webcpp/crypto/async.hpp` (its + header comment's list, the static members' definitions, the free asynchronous forms), + `test/support/timing_coverage.hpp` (the asynchronous forms in `cover_single_use_key_authenticator`), + `test/timing_coverage_sodium_test.cpp`, `test/timing_coverage_openssl_test.cpp`, + `test/allocation_openssl_test.cpp`, `test/Jamfile`, `doc/tables/crypto.json`; the generator's outputs. +- Create (libs/crypto): `test/poly1305_openssl_test.cpp`, `test/agreement_poly1305_test.cpp`, + `test/support/composition_checks.hpp`, `test/composition_rfc8439_test.cpp` (the matrix, one + type-parameterised test linking libsodium, BearSSL and OpenSSL, as the agreement tests do; crypto's + one-backend-per-file rule does not apply to a cross-backend test) and its Emscripten twin + `test/composition_rfc8439_emscripten_test.cpp` (libsodium and BearSSL), + `test/async_authenticator_test.cpp`, the message tests + `test/messages/{authenticate_asynchronous_backend,verify_poly1305_asynchronous_backend,async_authenticate_asynchronous_backend,async_verify_asynchronous_backend}/` + and their MSVC twins. + +**Interfaces:** +- Consumes: Task 8's class, engine trait and checks; Tasks 3 and 4's `ciphers::chacha20`; + `ciphers::chacha20_poly1305`'s `from_key` and `seal`. +- Produces: + +```cpp +// backends/openssl.hpp (design D14's row) +template <> struct authenticator_engine { + [[nodiscard]] static boost::system::result authenticate(std::span key_bytes, + std::span message_bytes, std::span tag_bytes) noexcept; + // (no canary: OpenSSL has none) openssl_memory_guard; ERR_set_mark; EVP_MAC_fetch(nullptr, "POLY1305", nullptr); + // EVP_MAC_CTX_new; EVP_MAC_init(context, key, 32, nullptr); EVP_MAC_update; EVP_MAC_final(.., &written, 16), + // written == 16; EVP_MAC_CTX_free; EVP_MAC_free; ERR_pop_to_mark. Every path frees what it made. +}; +// detail/asynchronous.hpp +template +constexpr void refuse_single_use_key_authenticator_on_asynchronous_backend() noexcept { + static_assert(!asynchronous_backend_v, + "webcpp::crypto: WebCrypto has no Poly1305: no form of the single-use key " + "authenticator, synchronous or asynchronous, runs on the browser's backend; name " + "a native backend for it."); +} +// poly1305 (declared in the class, defined in async.hpp with detail::complete_by_post): +template +static auto async_authenticate(Executor const& completion_executor, std::span key_bytes, + std::span message_bytes, CompletionToken&& completion_token); + // void(error_code, result_type), the zeroed tag on an error +template +static auto async_verify(Executor const& completion_executor, std::span key_bytes, + std::span message_bytes, std::span tag_bytes, + CompletionToken&& completion_token); // void(error_code) +// async.hpp, namespace single_use_key_authentication (as crypto::async_generate calls Keypair::async_generate): +template +auto async_authenticate(Executor const&, std::span key_bytes, + std::span message_bytes, CompletionToken&&); +template +auto async_verify(Executor const&, std::span key_bytes, std::span message_bytes, + std::span tag_bytes, CompletionToken&&); +// test/support/composition_checks.hpp (test only, design D17): +template +void check_rfc8439_composition(); // reports "//" on failure +template void run_composition_matrix(); // over std::tuple combinations +``` + +- [ ] **Step 1: Write the failing tests.** + - `poly1305_openssl_test.cpp`: `check_single_use_key_authenticator>()`; + with `WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE` and the adapter not installed, + `memory_functions_not_installed` from both members (Review Focus 6). + - `agreement_poly1305_test.cpp` (`test/support/agreement.hpp`'s generator): 2000 random keys and + messages (0 to 1024 bytes, 15, 16, 17, 64 KiB), libsodium's and OpenSSL's tags equal and equal + to the reference; its Emscripten twin compares libsodium with the reference alone. + - The composition matrix (owner decision 6, design D17): `check_rfc8439_composition()` + builds RFC 8439 section 2.8's AEAD from the raw pieces: `poly_key` the first 32 bytes of + `ciphers::chacha20`'s keystream at counter 0 (64 zero bytes through `apply_keystream`); + the ciphertext the plaintext through `apply_keystream` from counter 1; + the tag `authenticators::poly1305

::authenticate(poly_key, aad || pad16 || ciphertext || + pad16 || le64(aad_len) || le64(ct_len))`; and asserts byte-for-byte equality of the ciphertext + and the tag with `ciphers::chacha20_poly1305`'s `seal` of the same key, nonce, aad and + plaintext. `composition_rfc8439_test.cpp` runs it over the 18 combinations, S in {sodium, + bearssl, openssl}, P in {sodium, openssl}, A in {sodium, bearssl, openssl}; its Emscripten twin + over the 4 without OpenSSL. Every combination gets the same cases, drawn once: section 2.8.2's + vector (its ciphertext and tag also checked against the RFC's bytes), then random keys and + nonces over every pair of message lengths 0, 1, 15, 16, 17, 63, 64, 65, 255, 1024 and aad + lengths 0, 1, 12, 16, 17. Each assertion's message names the combination, the case and the + lengths. The `poly_key` is wiped after each case. + - `async_authenticator_test.cpp` as `async_stream_cipher_test`: callback, `use_awaitable` where the + build has coroutines, `deferred`; both forms, static and free, give the synchronous tag and + errors (`invalid_key_size`, `invalid_tag_size`, `authentication_failed`), each completing + through the executor, never inside the initiating call; an error's tag is zeroed. + - The four message tests on the stand-in backend, each `alone`. + - Timing coverage: `cover_single_use_key_authenticator>`, + and the asynchronous forms on both backends. Allocation: on OpenSSL nothing through + `operator new`, the MAC context through OpenSSL's memory functions only (R26). + Register all in `test/Jamfile` and `crypto.json`. +- [ ] **Step 2: Run, expect failure.** `B2 toolset=clang libs/crypto/test//poly1305_openssl`: the + generated refusal (no OpenSSL engine yet) is the one error. +- [ ] **Step 3: Implement** the engine and its `crypto.json` cells, the refusal and its calls (after + each form's guard, before naming the engine, ruling P12 of part A), the asynchronous definitions + and free forms, `async.hpp`'s header comment; rerun the generator. +- [ ] **Step 4: Run.** The five local lanes over the new tests and `libs/crypto/test//timing_coverage_sodium + libs/crypto/test//timing_coverage_openssl libs/crypto/test//allocation_openssl + libs/crypto/test//capabilities libs/crypto/test/messages` (the generated texts now name two + backends: Task 8's message tests that pin them are updated in this commit); `generate.py --check`. + MSVC 14.3 and 14.5 x64 debug over these and `libs/crypto/test/msvc`; arm64 14.5's timing set. + Expected: pass. +- [ ] **Step 5: Commit, lint.** `crypto: Poly1305 on OpenSSL, the backends' agreement, RFC 8439's AEAD composed from the raw pieces as an 18-cell cross-backend test, the asynchronous forms and the refusal on a backend that completes by itself`. Lint step. + +**Lanes:** the five local lanes, MSVC 14.3 and 14.5 x64 debug, arm64 timing set. + +--- + +### Task 10: Poly1305 in the constant-time lane and dudect + +Model tier: standard. Covers tasks.md 6.4; design D16. + +**Files (libs/crypto):** `test/constant_time/paths.hpp` (a path `one_time_tag(name)`, its call on libsodium in `common_paths`), `test/constant_time/ctgrind_test.cpp` +(OpenSSL's, memcheck alone), `test/constant_time/dudect_sodium_test.cpp` (the cases +`poly1305_authenticate` and `poly1305_verify`), `test/constant_time/Jamfile` (its comment's +list), `doc/tables/crypto.json` (the family's `lane` cells: sodium memcheck, msan and dudect +natively and on wasip2, openssl memcheck); the generator's outputs. + +- [ ] **Step 1: Write the paths.** `one_time_tag`: a key, 200 bytes of message and a tag marked + secret; `authenticate`, then `verify` with the right tag and with a tag differing in its last + byte; the tag checked with `carries_mark(tag)`; `verify`'s verdict needs no + suppression (crypto declassifies it, D12). dudect: `poly1305_authenticate`, class 0 the all-zero + key and class 1 random keys, 64 bytes of message fixed; `poly1305_verify`, class 0 the right tag + with its last byte flipped and class 1 the right tag with its first byte flipped, both failing, + key and message fixed (a matching tag against a mismatching one measures the public verdict's + return path, |t| 32.71, not the comparison; the AEAD open case also compares two failing + inputs); both added to the selection list and the program's comment. +- [ ] **Step 2: Run the planted checks first**, then the lane: + `$W/heavy.sh primitives $W/primitives/ct-run/linux.sh crypto constant-time`. Expected: the planted + programs fail as designed, every path passes, no new suppression. +- [ ] **Step 3: dudect natively** at release, each case alone (`--case`), then the whole program; + on wasip2 through the lane's run. Expected: |t| under the threshold; a reading at or above 10 is + investigated, never suppressed. +- [ ] **Step 4: Run** `generate.py --check`; the native and wasip2 lanes over + `libs/crypto/test/constant_time`. Expected: pass. +- [ ] **Step 5: Commit, lint.** `crypto: Poly1305 in the constant-time lane (libsodium under memcheck and MemorySanitizer, OpenSSL under memcheck) and in dudect`. Lint step. + +**Lanes:** the constant-time lane, Mac dudect, the native and wasip2 lanes over +`libs/crypto/test/constant_time`. + +--- + +### Task 11: The guide, the examples and the measurements' programs + +Model tier: standard. Covers tasks.md 7.1; design D10, D16, R16. + +**Files (libs/crypto):** modify `doc/chacha.adoc` (the section "ChaCha20, the raw stream cipher" +after ChaCha20-Poly1305's: what it is not, the call, the counter and `counter_overflow`, the +nonce, the backends and the default from the generated tables, the four forms, the browser, the +pitfalls of design D10), the new page `doc/unauthenticated_encryption.adoc` (included by `doc/crypto.adoc` after +`secret_key_encryption.adoc`: when to use the namespace, a protocol that brings its own +authentication such as NIP-44 with its HMAC, never a program's own messages, for which +`secret_key_encryption` is the normal path; the concept, the free forms, the generic function of +`stream_cipher_concepts_test.cpp`'s `tag=generic`, the generated +`namespace-unauthenticated_encryption.adoc`), `doc/secret_key_encryption.adoc` (the table "The +namespaces by purpose" gains the row), `doc/ciphers.adoc` (ChaCha20 among the algorithms, a link +to the page), `doc/tables/crypto.json`'s `namespaces` (the entry `unauthenticated_encryption`, +whose generated table the page includes; Task 3 adds the entry, this task its text), +`doc/async.adoc` (the forms of both), the new page `doc/single_use_key_authentication.adoc` (included after +`unauthenticated_encryption.adoc`; design D16: it opens with the rule that the key is used once, +for one message; for a reusable key `hash::mac` (HMAC); one-time passwords (HOTP, TOTP) are not what +this namespace does, and the page points to no library for them; then the calls, `verify`'s +constant-time comparison, the backends and BearSSL's absence, the four forms, the browser, the +generated `namespace-single_use_key_authentication.adoc`, the generic function of +`authenticator_concepts_test.cpp`; and RFC 8439 section 2.8's AEAD composed from the two raw pieces +as the composition test does it, with the remark that `chacha20_poly1305` is the call to use), +`doc/p2p.adoc` (NIP-44 composed from webcpp's pieces, with the +tests as the worked example, NIP-44 not in crypto), `doc/errors.adoc` (if Task 2 left it short), +`doc/tables/crypto.json` (the rules "ChaCha20 authenticates nothing" and "A Poly1305 key +authenticates one message" in `rules`, the use cases "Apply ChaCha20's keystream for a protocol that +fixes its own construction (NIP-44)" and "Authenticate one message under a one-time key", the +examples in the operations), `bench/operations.hpp` (`keystream`, 16 KiB from counter 1; `one_time_tag`, +16 KiB), `bench/throughput.cpp` (three cells, `chacha20` on libsodium, BearSSL, OpenSSL; two, +`poly1305` on libsodium and OpenSSL), +`test/sizes/Jamfile`, the changelog's source entry as crypto's `AGENTS.md` names it (never a +`CHANGELOG.md`); create `example/chacha20_keystream.cpp` and `.expected` (RFC 8439 section 2.4.2, +the ciphertext in hex, then the plaintext back), `example/poly1305_one_time_tag.cpp` and `.expected` +(RFC 8439 section 2.5.2's tag, then `verify` accepting it and refusing a flipped tag), +`test/sizes/chacha20_{sodium,bearssl,openssl}.cpp`, `test/sizes/poly1305_{sodium,openssl}.cpp` +(as `chacha20_poly1305_*`'s); then the generator. + +- [ ] **Step 1: Write the failing check.** The example's `.expected` first; `generate_test.py` + needs no new test (the family and the rule are data the existing tests cover); the doc build's + check. +- [ ] **Step 2: Run** `B2 toolset=clang libs/crypto/example//chacha20_keystream`: not found. +- [ ] **Step 3: Write** the example, the pages, the bench cells, the sizes programs; rerun the + generator (the family's performance cells read "not measured yet" until the owner's release + measurement pass, R16). +- [ ] **Step 4: Run** `B2 libs/crypto/doc doc`, `python3 tools/doc/doc-check.py` over crypto's + pages, the five local lanes over `libs/crypto/example libs/crypto/bench` (the bench built, not + measured), and the sizes lane at release over the three new programs + (`B2 toolset=clang variant=release libs/crypto/test/sizes`) with `generate.py --sizes` writing + `doc/tables/sizes.json`. Expected: pass; every example's `.expected` matches. +- [ ] **Step 5: Commit, lint.** `crypto: the guide's ChaCha20 section and Poly1305 page, the examples, the sizes and bench programs`. Lint step. + +**Lanes:** the doc build, the five local lanes over the examples and benches, the sizes lane +(release). + +### Task 12: The superproject + +Model tier: fast. Covers tasks.md 7.2. + +**Files (superproject):** `CODING-GUIDELINES.md` (chapter 17's crypto state: the raw ChaCha20 and Poly1305; +the roadmap's crypto line; chapter 19's sizes only from the sizes lane's release build, if it cites +a ChaCha20 size), the gitlink of `libs/crypto`. + +- [ ] Commit the guidelines (`guidelines: crypto's raw ChaCha20 and Poly1305`) and the gitlink + (`libs/crypto: the gitlink at the primitives change ()`). Lint step over the guidelines. + +**Lanes:** none beyond the lint. + +### Task 13: The delivery (a checklist the controller runs) + +Covers tasks.md 7.3 and 7.4. + + +Model tier: the controller; the final review by the most capable model. + +- [ ] Every repository: `git fetch origin`; if `origin/main` moved (crypto, superproject, + proposals), merge it into the branch (never rebase), re-run the lanes it touches, commit. +- [ ] Commit everything; `$W/primitives/refresh-tree.sh`. +- [ ] Lanes, each from scratch, one build directory each, through heavy.sh, over + `libs/crypto/test libs/crypto/example libs/crypto/bench`: + +```bash +B2="env -u CPATH -u CPLUS_INCLUDE_PATH -u C_INCLUDE_PATH b2 --user-config=.local/user-config.jam" +H="$W/heavy.sh primitives"; T="libs/crypto/test libs/crypto/example libs/crypto/bench" +$H $B2 -a --dump-tests --build-dir=bin/lane-clang --out-xml=clang.primitives.xml toolset=clang $T +$H $B2 -a --dump-tests --build-dir=bin/lane-gcc-15 --out-xml=gcc-15.primitives.xml toolset=gcc-15 $T +$H $B2 -a --dump-tests --build-dir=bin/lane-wasip2 --out-xml=wasip2.primitives.xml toolset=clang-wasip2 testing.launcher=tools/boost/asio-wasip2/run.sh $T +$H $B2 -a --dump-tests --build-dir=bin/lane-wasip3 --out-xml=wasip3.primitives.xml toolset=clang-wasip3 testing.launcher=tools/boost/asio-wasip3/run.sh $T +$H $B2 -a --dump-tests --build-dir=bin/lane-emscripten --out-xml=emscripten.primitives.xml toolset=emscripten $T +``` + (wasip2 and wasip3 with `WEBCPP_WASIP2_TEST_TIMEOUT=1800 WEBCPP_WASIP3_TEST_TIMEOUT=1800`); + every test with its `_no_exceptions` twin; the agreement test once more at `variant=release` + natively for its 2^30-byte case. +- [ ] The own lanes: `$H $W/primitives/ct-run/linux.sh crypto constant-time`; crypto's `c-suites` + lane as its Jamfile names it; natively on this Mac the dudect programs (release). +- [ ] MSVC on the VM, the essential set: `run-lane.sh 14.3` and `14.5`, x64 debug, over + `libs/crypto/test libs/crypto/example`; `14.5 --arch arm64` debug over the timing set. Each + `summarize.sh`: `new failures:` empty. +- [ ] Docs and tools: `$B2 doc`; `generate.py --check`; `generate_test.py`; + `python3 tools/test/crypto_jamfiles_test.py`, `crypto_jamfiles_format_test.py`, + `third_party_test.py`, `doc_test.py`; `python3 tools/ci/matrix_test.py`. +- [ ] The report: `python3 tools/report/report.py` over the XML files, every cell green. +- [ ] Lints: macOS full `$H tools/lint/lint.sh --clang-format .local/wasi-sdk/bin/clang-format --clang-tidy .local/wasi-sdk/bin/clang-tidy`; + Linux full `$H $W/linux-lint/run.sh --full $W/primitives/lane-tree`. Clean. +- [ ] The final whole-branch review (most capable model) over crypto and the superproject; fixes + in their own commits; the lanes a fix touches re-run (scoped), then the final head's lanes above + again if a fix touched a header. +- [ ] The proposals: this change's `tasks.md` ticked, `.openspec.yaml` status `implementing` with + `implementation:` the repository, design and spec true to the build, + `reference/STATUS.md` dated; `python3 tools/proposals.py readme` and `check` (0 problems); + OpenSpec 1.10.0's `openspec validate --all --strict` in `libraries/crypto`. +- [ ] Pull requests, in merge order: crypto (`crypto/primitives`), the superproject (the + submodule, the gitlink at crypto's merged `main`, the fixture, the guidelines), then the + proposals; each merged with a merge commit by the stream under the owner's autopilot + instruction; no CI gates them; one CI at the end on the superproject's `main`, every job green, + and its failures fixed in follow-up commits as the autopilot rule says. +- [ ] HANDBACK: `$W/primitives/HANDBACK.md` with the merged SHAs, the lanes' results, dudect's + readings, the findings of the final review and their fixes, and two messages: for + the backend-concepts stream (its catalogue gains `detail::backend::stream_cipher` for `stream_engine` on libsodium, BearSSL and OpenSSL, and its + `crypto.json` capability cell, and `detail::backend::authenticator` for + `authenticator_engine` on libsodium and OpenSSL; tasks.md 7.4), and for + part B (ChaCha20 and Poly1305 are among the constructions WebCrypto lacks; their refusals are + `refuse_stream_cipher_on_asynchronous_backend` and + `refuse_single_use_key_authenticator_on_asynchronous_backend`). + +## Self-review (the planner's) + +- Spec coverage: the type and its contract (Tasks 3, 4), the counter and its overflow (Tasks 2, + 3, 4), the concept and the four forms (Tasks 3, 5), the backends, the default and the refusals + (Tasks 3, 4), the guard, constant time and no heap (Tasks 3, 4, 5, 7), NIP-44's vectors (Tasks + 1, 6); Poly1305's contract (Tasks 8, 9), its namespace, concept and four forms (Tasks 8, 9), its + backends and refusals (Tasks 8, 9), its guard, constant time and no heap (Tasks 8, 9, 10), the + composition (Task 9). No requirement without a task. +- Names checked against crypto's `main` (`origin/main` at the plan's writing, 7b2c776, plus the + formats plan): `basic_chacha20_poly1305`, `detail::aead_state`, `aead_engine`, + `aead_refusal`, `aead_family`, `aead_sizes`, `detail::concept_check_backend`, + `detail::asynchronous_backend_v`, `refuse_aead_on_asynchronous_backend`, + `detail::complete_by_post`, `detail::async_access`, `detail::dependent_false` (engines.hpp), `detail::bearssl_chacha20`, + `WEBCPP_CRYPTO_DETAIL_BEARSSL_PORTABLE`, `sodium_ready`, `read_canary`, + `WEBCPP_CRYPTO_DETAIL_SODIUM_CANARY`, `WEBCPP_CRYPTO_DETAIL_BEARSSL_CANARY`, `openssl_context`, + `crypto::from_key`, `webcpp::test::cover_aead`, `secure::secret`'s `bytes()` (its implicit + conversion is to a fixed-extent span only); + libsodium's `crypto_stream_chacha20_ietf_xor_ic` and its `sodium_misuse` bound + (`stream_chacha20.c`), BearSSL's `br_chacha20_ct_run` (`chacha20_ct.c`, 32-bit counter returned), + OpenSSL's ChaCha20 counter carry (`cipher_chacha20_hw.c`) at the superproject's pins; webcpp::hash's + `hkdf_extract`, `hkdf_expand`, `hmac_sha2_256`, `sha2_256`; codecs' `formats::base64`. +- Poly1305's names checked against crypto's `main` and its pins: `boost::hash2::digest<16>` as the + AEADs' `result_type`, `secure::constant_time_equal` and `secure::declassify` as BearSSL's AEAD + open uses them, `openssl_memory_guard`, `factories.hpp`'s `crypto::from_key` refusal, + `crypto::async_generate` calling the static `Keypair::async_generate`; libsodium's + `crypto_onetimeauth_poly1305`, BearSSL's `br_poly1305_ctmul_run` (keyed from ChaCha20 itself). +- Not checked here (each task's first step reads it): OpenSSL's "POLY1305" `EVP_MAC` in the + superproject's wasip2 and wasip3 OpenSSL builds (Task 9: if a configuration drops it, the + family's OpenSSL targets narrow to native in `crypto.json`, and the design says so); `openssl_context`'s exact parameters for a + cipher without a tag (Task 4), the JSON keys of the pinned `nip44.vectors.json` (Task 6), the + generator's handling of a family with a `counter_type` (it reads none: the sizes are C++'s). diff --git a/libraries/crypto/openspec/changes/primitives/specs/crypto/spec.md b/libraries/crypto/openspec/changes/primitives/specs/crypto/spec.md new file mode 100644 index 0000000..aaf8cfd --- /dev/null +++ b/libraries/crypto/openspec/changes/primitives/specs/crypto/spec.md @@ -0,0 +1,162 @@ +## ADDED Requirements + +### Requirement: ChaCha20: RFC 8439's raw stream cipher +`` SHALL declare `ciphers::chacha20`, an alias of `ciphers::basic_chacha20` whose default `Backend` is `default_backend_t`, with `key_size` 32, `nonce_size` 12, `block_size` 64, `counter_type` `std::uint32_t` and `max_message_size` 2^38. `from_key(key_bytes)` SHALL return `result`, `invalid_key_size` for any other size than 32. `apply_keystream(nonce_bytes, data_bytes, initial_counter)` SHALL XOR into `data_bytes`, in place, RFC 8439 section 2.4's keystream under the object's key and `nonce_bytes`, its first block the block of counter `initial_counter`, and return `result`; encryption and decryption MUST be this one call. Its guards MUST run in this order and leave `data_bytes` untouched: `invalid_state` for a moved-from object, `invalid_nonce_size` for a nonce of another size than 12. Empty data MUST succeed. The nonce MAY lie inside `data_bytes`. A backend's failure MUST zero `data_bytes` and return the backend's error. The object MUST be move-only, a move leaving the source empty and wiped, and its destructor MUST wipe the key. `basic_chacha20` of a type that is no stream family MUST stop the build with one message naming `families::chacha20`. + +#### Scenario: RFC 8439 section 2.4.2 +- **WHEN** a `chacha20` made from section 2.4.2's key applies its keystream to the section's plaintext with its nonce and initial counter 1, on libsodium, BearSSL and OpenSSL +- **THEN** each gives the section's ciphertext, and a second call with the same arguments gives the plaintext back + +#### Scenario: The block function's vectors +- **WHEN** 64 zero bytes are given to `apply_keystream` with each key, nonce and counter of RFC 8439 Appendix A.1 +- **THEN** the bytes are each vector's keystream block + +#### Scenario: The nonce inside the data +- **WHEN** the nonce given to `apply_keystream` is a span over the first 12 bytes of the data +- **THEN** the result is the keystream under the nonce's original bytes, on every backend + +#### Scenario: A moved-from object +- **WHEN** a `chacha20` is moved from and its `apply_keystream` is called +- **THEN** it returns `invalid_state` and the data is unchanged + +### Requirement: ChaCha20: the block counter and its overflow +`crypto::error` SHALL gain the value `counter_overflow` (22), with its message, in the category `webcpp.crypto`. `apply_keystream` MUST return `counter_overflow`, after `invalid_state` and `invalid_nonce_size` and before any backend runs, leaving `data_bytes` untouched, exactly when the number of blocks of the algorithm's `block_size` the data needs (its size divided by `block_size`, rounded up) is greater than 2^w minus `initial_counter`, w the width in bits of the algorithm's `counter_type`; for ChaCha20, 64-byte blocks and 2^32. `` SHALL hold this computation once, as `detail::counter_overflows(data_size, initial_counter)`, a `constexpr` function every stream cipher's `apply_keystream` calls; it MUST accept every size at or under that bound on every backend, and MUST NOT return `message_too_long`. No backend MUST be given a call whose counter would pass 2^32 - 1, so that none wraps the counter, carries it into the nonce or aborts the program. + +#### Scenario: The counter's last block +- **WHEN** 64 bytes are given with initial counter 2^32 - 1, and 128 bytes with initial counter 2^32 - 2, on libsodium, BearSSL and OpenSSL +- **THEN** each call succeeds and the three backends give the same bytes + +#### Scenario: One byte past the counter +- **WHEN** 65 bytes are given with initial counter 2^32 - 1 +- **THEN** the call returns `counter_overflow`, the data is unchanged, and the program does not abort on libsodium + +#### Scenario: A stream continued by the counter +- **WHEN** 128 bytes are processed in one call from counter 7, and the same bytes in two calls of 64 bytes from counters 7 and 8 +- **THEN** both give the same bytes + +### Requirement: ChaCha20: the stream cipher concept in unauthenticated_encryption and the four forms +`` SHALL declare, in the namespace `webcpp::crypto::unauthenticated_encryption` (which `` declares and which holds no algorithm), the concept `unauthenticated_encryption::stream_cipher`: `key_size`, `nonce_size` and `block_size` convertible to `std::size_t`, `block_size` above 0, a type `counter_type` that is a standard unsigned integer type of at most 64 bits, `from_key(key_bytes)` giving `result`, and `apply_keystream(nonce_bytes, data_bytes, initial_counter)` giving `result`; and its free form `unauthenticated_encryption::apply_keystream(cipher, nonce_bytes, data_bytes, initial_counter)`, which calls the member. The concept and its free forms MUST read the algorithm's own `nonce_size`, `block_size` and `counter_type` and MUST NOT assume ChaCha20's 12-byte nonce, 64-byte block or 32-bit counter; the free forms MUST name no backend, so that a stream cipher of another shape satisfies the concept and works through them unchanged. `ciphers::chacha20` MUST satisfy `stream_cipher` and MUST NOT satisfy `secret_key_encryption::aead::cipher` or `secret_key_encryption::authenticated_box`; no AEAD, box or block cipher of crypto MUST satisfy `stream_cipher`. `crypto::from_key>(key_bytes)` SHALL make one. `` SHALL define `basic_chacha20::async_from_key(executor, key_bytes, token)`, completing with `void(boost::system::error_code, basic_chacha20)`, `basic_chacha20::async_apply_keystream(executor, nonce_bytes, data_bytes, initial_counter, token)` and the free `unauthenticated_encryption::async_apply_keystream(executor, cipher, nonce_bytes, data_bytes, initial_counter, token)`, completing with `void(boost::system::error_code)`; `crypto::async_from_key` MUST take a `stream_cipher`. On a synchronous backend each asynchronous form MUST run its synchronous call when the operation is initiated and complete through a post to `executor`, with the synchronous call's errors. On a backend whose `detail::asynchronous_backend_v` is true, every form of `basic_chacha20`, synchronous or asynchronous, member or free, MUST stop the build with one message saying that WebCrypto has no ChaCha20 and naming a native backend. + +#### Scenario: The four forms agree +- **WHEN** the same key, nonce, counter and data are given to the member, the free form, and both asynchronous forms run to completion +- **THEN** the four give the same bytes and the same errors + +#### Scenario: A stream cipher of another shape +- **WHEN** a test-only stand-in stream cipher with an 8-byte nonce, a 16-byte block and a `std::uint8_t` counter is checked against `stream_cipher` at compile time, and given to the free forms with 16 and 17 bytes at counter 255 and with a 12-byte nonce +- **THEN** it satisfies the concept, the free forms give the member's bytes for 16 bytes, return `counter_overflow` for 17 bytes and `invalid_nonce_size` for the 12-byte nonce with the data unchanged, and `detail::counter_overflows` gives the same bounds in `static_assert`s + +#### Scenario: Not an AEAD +- **WHEN** a program checks `secret_key_encryption::aead::cipher>` and `unauthenticated_encryption::stream_cipher>` +- **THEN** both are false + +#### Scenario: The browser's backend +- **WHEN** a program calls `apply_keystream` of a `basic_chacha20` on a backend whose `asynchronous_backend_v` is true +- **THEN** compilation stops with the message that WebCrypto has no ChaCha20, and that error alone + +### Requirement: ChaCha20: the backends, the default and the refusals +`families::chacha20` SHALL be implemented on libsodium (`crypto_stream_chacha20_ietf_xor_ic`) and BearSSL (`br_chacha20_ct_run` or its SSE2 code) on native, wasip2, wasip3 and Emscripten, and on OpenSSL (`EVP_CIPHER` "ChaCha20") on native, wasip2 and wasip3. Its default backend SHALL be libsodium on every target, with the alias `/webcpp/crypto//chacha20-default` linking it. The capability table SHALL list the family, and `supports_v`, `default_backend_t` and the refusals SHALL be generated from it. A program that names ctaes or secp256k1 in the type, names a backend whose header it does not include, uses the default without linking it, or names a type that is no backend, MUST stop where it calls `from_key`, with a message naming the backends and targets that have ChaCha20 and the header or Jamfile line it needs. + +#### Scenario: The backends agree +- **WHEN** libsodium, BearSSL and OpenSSL apply the keystream with the same random keys, nonces and counters to data of 0 to 1024 bytes, block edges and 64 KiB +- **THEN** the three give the same bytes + +#### Scenario: ChaCha20 on ctaes +- **WHEN** a program makes a `ciphers::chacha20` +- **THEN** compilation stops with a message that ctaes has no ChaCha20 and the backends that have it + +#### Scenario: The default not linked +- **WHEN** a program uses `ciphers::chacha20<>` without `/webcpp/crypto//chacha20-default` or libsodium in its Jamfile +- **THEN** compilation stops with a message naming the alias to add + +### Requirement: ChaCha20: the timing guard, constant time and no heap +Every function of `basic_chacha20`, the free `unauthenticated_encryption::apply_keystream` and `unauthenticated_encryption::async_apply_keystream`, and every asynchronous member MUST hold `secure::timing_guard` as its first statement, and each backend's timing coverage test MUST check that each entered its guard. `apply_keystream` MUST allocate nothing on any backend; `from_key` MUST allocate nothing on libsodium and BearSSL. The constant-time lane MUST run the keystream with its key and data marked secret on BearSSL and libsodium under memcheck and MemorySanitizer, and on OpenSSL under memcheck, and dudect MUST measure BearSSL's keystream natively and on wasip2. + +#### Scenario: Every call enters its guard +- **WHEN** the timing coverage test of a backend calls `from_key`, `apply_keystream`, the free forms and the asynchronous forms of `chacha20` +- **THEN** each call is counted as having entered its own guard + +#### Scenario: No allocation +- **WHEN** `apply_keystream` runs on each backend under the allocation tests' counting allocator +- **THEN** no allocation is counted + +### Requirement: ChaCha20: NIP-44's end-to-end vectors +The tests SHALL run NIP-44 version 2's vectors (paulmillr/nip44's `nip44.vectors.json`, a pinned test-data submodule of the superproject whose SHA-256 is the one NIP-44's text states) through a NIP-44 composed in the tests alone from crypto's ChaCha20 (counter 0) and secp256k1 agreement, webcpp::hash's HKDF and HMAC-SHA256, and webcpp::codecs' base64, on each of the three backends: every entry of `valid.get_conversation_key`, `valid.get_message_keys`, `valid.encrypt_decrypt` and `valid.encrypt_decrypt_long_msg`. No header of crypto MUST hold NIP-44. + +#### Scenario: A NIP-44 payload +- **WHEN** each `valid.encrypt_decrypt` entry's conversation key, nonce and plaintext are encrypted, and its payload decrypted, by the tests' composition on each backend +- **THEN** the encryption gives the entry's payload and the decryption its plaintext + +#### Scenario: A long message +- **WHEN** each `valid.encrypt_decrypt_long_msg` entry's pattern, repeated, is encrypted with its conversation key and nonce +- **THEN** the SHA-256 of the plaintext and of the payload are the entry's + +### Requirement: Poly1305: RFC 8439's one-time authenticator +`` SHALL declare `authenticators::poly1305`, whose default `Backend` is `default_backend_t`, with `key_size` 32, `tag_size` 16 and `result_type` `boost::hash2::digest<16>`, and no constructor. Its static `authenticate(key_bytes, message_bytes)` SHALL return `result`, RFC 8439 section 2.5's tag of `message_bytes` under the one-time key `key_bytes` (r || s), for every message length, the empty message included. Its static `verify(key_bytes, message_bytes, tag_bytes)` SHALL return `result`: success when `tag_bytes` is the tag `authenticate` gives, `authentication_failed` otherwise, the comparison made by `secure::constant_time_equal` and the computed tag wiped before it returns. Their guards MUST run in this order and read no byte: `invalid_key_size` for a key of another size than 32, then, in `verify`, `invalid_tag_size` for a tag of another size than 16. A backend's failure MUST return the backend's error, never `authentication_failed`, and leave `authenticate`'s tag zeroed. No new value of `crypto::error` SHALL be added for Poly1305. Nothing SHALL be written into the caller's spans, and no backend SHALL be given a null pointer. + +#### Scenario: RFC 8439 section 2.5.2 +- **WHEN** `poly1305::authenticate` is given the section's key and its message "Cryptographic Forum Research Group", on libsodium and OpenSSL +- **THEN** each gives the section's tag, and `verify` with that tag succeeds + +#### Scenario: Appendix A.3 +- **WHEN** each of RFC 8439 Appendix A.3's eleven vectors is given to `authenticate` and `verify` +- **THEN** `authenticate` gives each vector's tag and `verify` accepts it, on every backend + +#### Scenario: A forged tag +- **WHEN** `verify` is given a tag with one bit flipped, or a message with one bit flipped +- **THEN** it returns `authentication_failed` + +#### Scenario: The guards' order +- **WHEN** `verify` is given a key of 31 bytes and a tag of 15 bytes +- **THEN** it returns `invalid_key_size`; with a key of 32 bytes it returns `invalid_tag_size` + +### Requirement: Poly1305: the single_use_key_authentication namespace, its concept and the four forms +`` SHALL declare, in the namespace `webcpp::crypto::single_use_key_authentication` (which `` declares and which holds no algorithm), the concept `single_use_key_authenticator`: `key_size` and `tag_size` convertible to `std::size_t`, a type `result_type`, a static `authenticate(key_bytes, message_bytes)` giving `result` and a static `verify(key_bytes, message_bytes, tag_bytes)` giving `result`; and the free forms `authenticate(key_bytes, message_bytes)` and `verify(key_bytes, message_bytes, tag_bytes)`, which call the static members. `authenticators::poly1305` MUST satisfy it and MUST NOT satisfy `unauthenticated_encryption::stream_cipher` or `secret_key_encryption::aead::cipher`; no AEAD, box, stream cipher or webcpp::hash MAC MUST satisfy it. The free forms given a type that does not satisfy it MUST stop the build with one message naming `authenticators::poly1305` and `webcpp::hash::mac` for a reusable key. There MUST be no `from_key`, and `crypto::from_key>` MUST stop the build. `` SHALL define the static members `async_authenticate(executor, key_bytes, message_bytes, token)`, completing with `void(boost::system::error_code, result_type)`, and `async_verify(executor, key_bytes, message_bytes, tag_bytes, token)`, completing with `void(boost::system::error_code)`, and the free `single_use_key_authentication::async_authenticate` and `async_verify` with the same arguments, which call them. On a synchronous backend each asynchronous form MUST run its synchronous call when the operation is initiated and complete through a post to `executor`, with the synchronous call's errors. On a backend whose `detail::asynchronous_backend_v` is true, every form of `poly1305`, synchronous or asynchronous, static member or free, MUST stop the build with one message saying that WebCrypto has no Poly1305 and naming a native backend. + +#### Scenario: The four forms agree +- **WHEN** the same key, message and tag are given to the static members, the free forms, and the asynchronous forms run to completion +- **THEN** they give the same tag and the same errors, `authentication_failed` included + +#### Scenario: Not a cipher +- **WHEN** a program checks `single_use_key_authenticator>`, `single_use_key_authenticator>` and `unauthenticated_encryption::stream_cipher>` +- **THEN** all three are false + +#### Scenario: The browser's backend +- **WHEN** a program calls `authenticate` or `async_verify` of `poly1305` on a backend whose `asynchronous_backend_v` is true +- **THEN** compilation stops with the message that WebCrypto has no Poly1305, and that error alone + +### Requirement: Poly1305: the backends, the default and the refusals +`families::poly1305` SHALL be implemented on libsodium (`crypto_onetimeauth_poly1305`) on native, wasip2, wasip3 and Emscripten, and on OpenSSL (the `EVP_MAC` "POLY1305") on native, wasip2 and wasip3. Its default backend SHALL be libsodium on every target, with the alias `/webcpp/crypto//poly1305-default` linking it. The capability table SHALL list the family, and `supports_v`, `default_backend_t` and the refusals SHALL be generated from it. A program that names BearSSL, ctaes or secp256k1 in the type, names a backend whose header it does not include, uses the default without linking it, or names a type that is no backend, MUST stop where it calls `authenticate` or `verify`, with a message naming the backends and targets that have Poly1305 and the header or Jamfile line it needs. + +#### Scenario: The backends agree +- **WHEN** libsodium and OpenSSL authenticate the same random messages of 0 to 1024 bytes, 15, 16, 17 bytes and 64 KiB under the same random keys +- **THEN** the two give the same tag, equal to the tests' reference written from RFC 8439 section 2.5 + +#### Scenario: Poly1305 on BearSSL +- **WHEN** a program calls `authenticators::poly1305::authenticate` +- **THEN** compilation stops with a message that BearSSL has no Poly1305 and naming libsodium and OpenSSL + +### Requirement: Poly1305: the timing guard, constant time and no heap +Every static member of `poly1305` and every free form of `single_use_key_authentication` MUST hold `secure::timing_guard` as its first statement, and the timing coverage tests of libsodium and OpenSSL MUST check that each entered its guard. `authenticate` and `verify` MUST allocate nothing on libsodium and nothing through `operator new` on OpenSSL, whose MAC context is allocated and freed in the call through OpenSSL's memory functions. The constant-time lane MUST run `authenticate` and `verify` with the key, the message and the tag marked secret on libsodium under memcheck and MemorySanitizer and on OpenSSL under memcheck, and dudect MUST measure libsodium's `authenticate` and crypto's `verify` comparison natively and on wasip2. + +#### Scenario: Every call enters its guard +- **WHEN** the timing coverage test of a backend calls the static members, the free forms and the asynchronous forms of `poly1305`, `verify` with a matching and a mismatching tag +- **THEN** each call is counted as having entered its own guard + +#### Scenario: No allocation +- **WHEN** `authenticate` and `verify` run on libsodium under the allocation tests' counting allocator +- **THEN** no allocation is counted + +### Requirement: Poly1305: RFC 8439's AEAD composed from the raw pieces, as a test +The tests SHALL build RFC 8439 section 2.8's AEAD from `ciphers::chacha20` and `authenticators::poly1305

` alone: the one-time key the first 32 bytes of the keystream at counter 0, the ciphertext the plaintext's keystream from counter 1, the tag Poly1305 over the aad, its padding to 16 bytes, the ciphertext, its padding, and the two lengths as 64-bit little-endian values; and SHALL assert that the ciphertext and the tag equal, byte for byte, `ciphers::chacha20_poly1305`'s seal of the same key, nonce, aad and plaintext, for every combination of `S` in libsodium, BearSSL and OpenSSL, `P` in libsodium and OpenSSL and `A` in libsodium, BearSSL and OpenSSL (18 combinations, the 4 without OpenSSL on Emscripten), in one type-parameterised test whose failure names its combination. `ciphers::chacha20_poly1305` MUST keep calling each backend's combined function; no header of crypto MUST hold the composition. + +#### Scenario: Section 2.8.2 +- **WHEN** each of the 18 combinations composes, and `chacha20_poly1305` seals, section 2.8.2's plaintext with its key, nonce and aad +- **THEN** both give the section's ciphertext and tag + +#### Scenario: Every length pair +- **WHEN** random keys and nonces are used with messages of 0, 1, 15, 16, 17, 63, 64, 65, 255 and 1024 bytes and aad of 0, 1, 12, 16 and 17 bytes +- **THEN** for every pair and every combination the composed ciphertext and tag equal the AEAD's + +#### Scenario: A failure names its combination +- **WHEN** one combination's composed tag differs from its AEAD's +- **THEN** the test's message names the raw ChaCha20's, Poly1305's and the AEAD's backends, the case and the lengths diff --git a/libraries/crypto/openspec/changes/primitives/tasks.md b/libraries/crypto/openspec/changes/primitives/tasks.md new file mode 100644 index 0000000..c67f8b5 --- /dev/null +++ b/libraries/crypto/openspec/changes/primitives/tasks.md @@ -0,0 +1,41 @@ +# Tasks + +Implemented after crypto's `formats`, codecs' Q1 and crypto's `hpke` merge, and before crypto's +`backend-concepts` (design, "The queue"). Each task writes its tests first; the library builds at +the end of every task. The plan is `reference/plan.md`. + +## 1. Test data and the error value + +- [x] 1.1 The superproject's test-data submodule `third_party/libs/nip44` (paulmillr/nip44, pinned) after its licence check and the vectors' SHA-256 against NIP-44's text, its `third_party/Jamfile` entry and define `WEBCPP_TEST_NIP44`, wasmtime's directory, CODING-GUIDELINES.md's third-party row (design D9, R13) +- [x] 1.2 `error::counter_overflow = 22`, its message, `error_test`, the guide's error table (D7, R12) + +## 2. The type, its contract and its backends + +- [x] 2.1 `ciphers/stream_cipher.hpp` (`families::chacha20`, `basic_chacha20`), `unauthenticated_encryption/stream_cipher.hpp` (the concept `unauthenticated_encryption::stream_cipher`, reading the algorithm's own `nonce_size`, `block_size` and `counter_type`, the free `unauthenticated_encryption::apply_keystream`, `detail::counter_overflows`; owner decision 7) and the namespace declared in `config.hpp` and listed in `crypto.json`'s namespaces (owner decision 5), `ciphers/chacha20.hpp`, `stream_state` and `stream_engine` in `detail/engines.hpp`, libsodium's engine; `crypto.json`'s family, default and operation, the generator; RFC 8439's vectors, the guards, the counter's boundary, the concepts; `stream_cipher_shape_test`, a test-only stand-in stream cipher of another nonce size, block size and counter type through the concept, the free form and the counter's refusal (owner decision 7); the message tests of the refusals with their MSVC twins; the timing coverage and the allocation test on libsodium; the superproject's `chacha20_default` fixture (D1 to D5, D9, R1 to R9, R15, R17, R19, R28) +- [x] 2.2 BearSSL's and OpenSSL's engines, their vector tests (BearSSL's portable twin), the agreement of the three backends with its Emscripten and portable twins, their timing coverage and allocation tests (D4, D9, R18) + +## 3. The asynchronous forms + +- [x] 3.1 `async_from_key` and `async_apply_keystream` in `async.hpp`, the free `unauthenticated_encryption::async_apply_keystream`, `crypto::async_from_key` taking a stream cipher, `detail::refuse_stream_cipher_on_asynchronous_backend` (in the members; the free forms name no backend, owner decision 7); their tests, `stream_cipher_shape_test`'s stand-in through the free asynchronous form, the stand-in backend's message tests with MSVC twins, the timing coverage (D6, R10, R11) + +## 4. NIP-44's end-to-end vectors + +- [x] 4.1 `test/support/nip44.hpp` (test only) and `chacha20_nip44_test` on the three backends, the four valid sections (D9, R13) + +## 5. Constant time + +- [x] 5.1 The constant-time lane's paths (BearSSL and libsodium under memcheck and MemorySanitizer, OpenSSL under memcheck), dudect's `chacha20_keystream` case natively and on wasip2, `crypto.json`'s lane cells (D8) + +## 6. Poly1305, the single-use key authenticator (owner decision 6) + +- [x] 6.1 `authenticators/poly1305.hpp` (`families::poly1305`, `authenticators::poly1305`, the primary `authenticator_engine`), `single_use_key_authentication/authenticator.hpp` (the concept `single_use_key_authenticator`, the free `authenticate` and `verify` and their catch-alls), the namespaces `authenticators` and `single_use_key_authentication` declared in `config.hpp` and listed in `crypto.json`'s namespaces, `authenticator_engine` in `detail/engines.hpp`, libsodium's engine; `crypto.json`'s family, default and operations, the generator; RFC 8439's section 2.5.2 and Appendix A.3 vectors, the guards, the forged tags, the concepts; the message tests of the refusals (BearSSL, ctaes, an unknown backend, the default not linked, the header not included, not an authenticator, `from_key`) with their MSVC twins; the timing coverage and the allocation test on libsodium; the superproject's `poly1305_default` fixture (D11 to D14, R20 to R25) +- [x] 6.2 OpenSSL's engine, its vector test, the agreement of the two backends with its Emscripten twin against the tests' reference, its timing coverage and allocation test; the composition matrix, RFC 8439 section 2.8's AEAD built from the raw ChaCha20 (libsodium, BearSSL, OpenSSL) and Poly1305 (libsodium, OpenSSL) and equal to `chacha20_poly1305`'s seal (libsodium, BearSSL, OpenSSL), 18 combinations in one type-parameterised test (owner decision 6) (D14, D16, D17, R26, R27) +- [x] 6.3 `async_authenticate` and `async_verify` in `async.hpp`, static members and free forms, `detail::refuse_single_use_key_authenticator_on_asynchronous_backend`; their tests, the stand-in backend's message tests with MSVC twins, the timing coverage (D15) +- [x] 6.4 The constant-time lane's paths (libsodium under memcheck and MemorySanitizer, OpenSSL under memcheck), dudect's `poly1305_authenticate` and `poly1305_verify` cases natively and on wasip2, `crypto.json`'s lane cells (D16) + +## 7. The pages, the measurements' programs and the delivery + +- [x] 7.1 The guide (the pages `unauthenticated_encryption.adoc` and `single_use_key_authentication.adoc`, `chacha.adoc`'s section, `secret_key_encryption.adoc`'s table of namespaces by purpose, `ciphers.adoc`, `errors.adoc`, `async.adoc`, `p2p.adoc`), the examples `chacha20_keystream` and `poly1305_one_time_tag` and their `.expected`, the rules and the use cases of `crypto.json`, the sizes programs and the bench cells of both algorithms, the generated files, the changelog's source entry (D10, D16, R16) +- [x] 7.2 The superproject: the gitlink, the guidelines' crypto lines, the sizes lane at release if a cited size changed +- [x] 7.3 Every lane on the final head (native clang and gcc, wasip2, wasip3, Emscripten, MSVC 14.3 and 14.5 x64 debug, arm64 14.5's DIT and timing tests, the constant-time lane, Mac dudect, the doc build, the macOS and Linux lints), pull requests in order (crypto, superproject, proposals), merges, one CI at the end +- [x] 7.4 backend-concepts told of the new engines (its catalogue's `stream_cipher` and `authenticator` capabilities), part B of the two refusals it lists