diff --git a/.github/workflows/library.yml b/.github/workflows/library.yml index 7a196af4..303e6e08 100644 --- a/.github/workflows/library.yml +++ b/.github/workflows/library.yml @@ -423,22 +423,24 @@ jobs: WEBCPP_WASIP2_TEST_TIMEOUT: ${{ (matrix.library == 'crypto' && matrix.lane == 'constant-time') && '1800' || '600' }} run: python3 tools/ci/matrix.py own-lane "$LANE" - # crypto's constant-time lane: every dudect output printed, a warning for every |t| of 10 - # or more, and on a runner GitHub hosts a case over 10 measured again in two fresh - # processes, failing when two of the three exceed 10 (libs/crypto's change api-gaps, D7). - # The launcher's bound is the lane's, so a run of the judge's own lasts at most that, and - # the judge's subprocess timeout (2400 s) lies beyond it. + # crypto's and secure's constant-time lanes, each by its own library's judge: every dudect + # output printed, a warning for every |t| of 10 or more, and on a runner GitHub hosts a case + # over 10 measured again in two fresh processes, failing when two of the three exceed 10 + # (libs/crypto's change api-gaps, D7; secure's judge is a copy of crypto's). The launcher's + # bound is the lane's, so a run of the judge's own lasts at most that, and the judge's + # subprocess timeout (2400 s) lies beyond it. - name: Judge dudect - if: ${{ !cancelled() && matrix.library == 'crypto' && matrix.lane == 'constant-time' }} + if: ${{ !cancelled() && matrix.lane == 'constant-time' && (matrix.library == 'crypto' || matrix.library == 'secure') }} env: WEBCPP_WASIP2_TEST_TIMEOUT: '1800' + LIBRARY: ${{ matrix.library }} TARGET: ${{ matrix.platform }} RERUN: ${{ runner.environment == 'github-hosted' && '--rerun' || '' }} shell: bash run: | # RERUN is empty off the hosted runners, so it is left unquoted to vanish. # shellcheck disable=SC2086 - python3 libs/crypto/test/constant_time/dudect_judge.py --bin bin \ + python3 "libs/$LIBRARY/test/constant_time/dudect_judge.py" --bin bin \ --target "$TARGET" $RERUN --launcher tools/boost/asio-wasip2/run.sh - name: Save the third-party builds diff --git a/.gitmodules b/.gitmodules index 7a031b31..ee3794b9 100644 --- a/.gitmodules +++ b/.gitmodules @@ -96,3 +96,6 @@ [submodule "third_party/libs/botan"] path = third_party/libs/botan url = https://github.com/randombit/botan.git +[submodule "libs/secure"] + path = libs/secure + url = ../secure.git diff --git a/AGENTS.md b/AGENTS.md index 5e069d8d..9669879d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -77,7 +77,9 @@ for web developers and for AI developers (`CODING-GUIDELINES.md` chapter 16). | beast | HTTP and WebSocket applications using native/WASIp3 sockets, browser WebSocket/fetch, WASI host HTTP or supplied streams | native, emscripten, wasip2, wasip3, by backend | a submodule at `libs/beast`; all 53 upstream applications remain in its compatibility matrix | | cobalt | Boost.Cobalt coroutine applications with shipped Wasm adaptations and optional corrected SSL | native, emscripten, wasip2, wasip3, by capability | a submodule at `libs/cobalt`; see its feature and application matrices for variants | | config | webcpp's configuration, which every library includes first: the target, exceptions and webcpp's version, as Boost.Config is Boost's; webcpp's own | native, wasip2, wasip3, emscripten | a submodule at `libs/config` | -| crypto | AES-GCM, the AES block cipher, random_device, constant_time_equal and secp256k1 over C libraries built from source (BearSSL, OpenSSL, libsecp256k1, ctaes), webcpp's own | native, wasip2, wasip3, emscripten (OpenSSL not on emscripten); its own lane c-suites | a submodule at libs/crypto | +| crypto | AES-GCM, the AES block cipher, random_device and secp256k1 over C libraries built from source (BearSSL, OpenSSL, libsecp256k1, ctaes), webcpp's own | native, wasip2, wasip3, emscripten (OpenSSL not on emscripten); its own lane `c-suites` | a submodule at `libs/crypto`; depends on hash and secure | +| hash | hashing and key derivation: Boost.Hash2's algorithms by alias, Keccak-256, BLAKE3, HKDF, PBKDF2, Argon2 and scrypt over C backends (XKCP, BLAKE3, libsodium, BearSSL, OpenSSL, Botan) and a browser backend; a wrapper | native, wasip2, wasip3, emscripten (by backend); its own lane `c-suites` | a submodule at `libs/hash`; depends on config and secure | +| secure | the side-channel and secret-in-memory primitives crypto, hash and codecs share (the DIT timing guard, `erase_secret`, `secret`, `constant_time_equal`, `declassify` and constant-time building blocks); no algorithm; webcpp's own | native, wasip2, wasip3, emscripten; its own lane `constant-time` | a submodule at `libs/secure`; header-only, depends on config alone | | xactor | a deterministic actor system, webcpp's own | native, wasip2, wasip3 (`xactor_asio` native only) | a submodule at `libs/xactor`; the model for every port | | xstate | a port of XState 5.33.2's state machines and actors; depends on xactor and Boost.JSON | native, wasip2, wasip3; its oracle lane | a submodule at `libs/xstate`; the first user of the shared oracle (`CODING-GUIDELINES.md` chapter 12) | | pratt | a Pratt parser engine, generic through concepts, with a calculator built on it, webcpp's own | native, emscripten, wasip2, wasip3 | a submodule at `libs/pratt`; born with the allocation rule (`CODING-GUIDELINES.md` chapter 4) | @@ -105,8 +107,8 @@ webcpp/ .clang-tidy clang-tidy's checks, every repository's pyrightconfig.json Pyright's settings for every Python file libs// a library: a repository of its own, a submodule here (asio, beast, cobalt, - config, crypto, xactor, xstate, pratt, wasi, trystero, document, idna, - lexical, webrtc) + config, crypto, hash, secure, xactor, xstate, pratt, wasi, trystero, + document, idna, lexical, webrtc) third_party/ third-party code the libraries and their tests use, not webcpp's: each a submodule under third_party/libs/, pinned at a commit and keeping its own licence (openssl, libdatachannel, bearssl, secp256k1, bitcoin for diff --git a/CODING-GUIDELINES.md b/CODING-GUIDELINES.md index 369b203c..0610db98 100644 --- a/CODING-GUIDELINES.md +++ b/CODING-GUIDELINES.md @@ -103,6 +103,8 @@ Not built yet: `tools/test/emscripten_test.py`, `tools/test/crypto_jamfiles_test.py`, `tools/test/crypto_jamfiles_format_test.py`, `tools/test/hash_jamfiles_test.py`, `tools/test/hash_jamfiles_format_test.py`, + `tools/test/secure_jamfiles_test.py`, `tools/test/secure_collect_test.py`, + `tools/test/secure_dudect_judge_test.py`, `tools/test/external_test.py`, `tools/test/doc_test.py`, `tools/test/harness_test.py`, `tools/test/third_party_test.py`, @@ -1323,7 +1325,17 @@ site's own decisions follow in the next sections. `hash2-mul128-msvc-arm64.patch`, Boost 1.92.0's `mul128.hpp` that MSVC for ARM64 rejects (C2601) wherever `boost/hash2/xxh3.hpp` is included, fixed upstream by https://github.com/boostorg/hash2/pull/49; the owner approved - carrying it on 2026-11-22. + carrying it on 2026-11-22. The second is + `cobalt-coroutine-align-msvc.patch`, Boost 1.92.0's Cobalt, whose promises' + `operator new` places a coroutine frame 8 bytes off a 16-byte boundary on + MSVC, where release builds fault on aligned SSE stores into it (hash's + `async_cobalt` on MSVC 14.3 x64): it aligns every coroutine allocation of + Cobalt to 16 on MSVC alone, every size, offset and alignment elsewhere + staying Boost 1.92.0's, after upstream's fix + https://github.com/boostorg/cobalt/commit/d67080b, whose form also changes + the layout off MSVC; it is carried under the owner's standing instruction of + 2026-11-18, pending his confirmation. Cobalt's own bundles carry neither: + native Cobalt reads the configured Boost's headers. Source: `tools/ci/actions/boost/install.sh` (webcpp). - **Boost.JSON's definitions and Boost.Test's header-only framework are objects of webcpp's own build, `/webcpp//boost_json` and @@ -6997,17 +7009,17 @@ cryptography over widely used C libraries that webcpp builds from their sources. Version 0.1 is the proposal's increments 1 and 2, as the owner set them on 2026-11-14: AES-GCM and the AES block cipher, a `random_device` on the system's generator, a constant-time comparison (named `constant_time_equal` -since the uniform-types change), and secp256k1's BIP340 Schnorr and ECDSA +since the uniform-types change, and webcpp::secure's since the secure change: +chapter 17), and secp256k1's BIP340 Schnorr and ECDSA signatures, ECDH, strict DER and the x-only tweak. What is built after it is unreleased and has its blocks below: OpenSSL's memory option, the curves and -constructions of the later changes, and `erase_secret`; what is decided and -not built is in chapter 17. +constructions of the later changes, and `erase_secret` (webcpp::secure's too +since that change); what is decided and not built is in chapter 17. **Scope.** - **crypto holds primitives only, grouped in namespaces whose headers mirror - them: the root (`error`, `random_device`, `constant_time_equal`, - `erase_secret`, `config`), `backends`, `ciphers` (`aes128`, `aes192`, + them: the root (`error`, `random_device`, `config`), `backends`, `ciphers` (`aes128`, `aes192`, `aes256`, `gcm`, `aes128_gcm`, `aes256_gcm`, under ``) and `curves::secp256k1` (under ``).** The owner's rule of 2026-11-15: a protocol's @@ -7074,40 +7086,54 @@ not built is in chapter 17. clang refuses under `on`. Source: `include/webcpp/crypto/detail/limits.hpp` (libs/crypto). - **One public header per responsibility; a backend's header checks that its - library is linked; `config.hpp`, `error.hpp`, `constant_time_equal.hpp`, - `erase_secret.hpp`, `random_device.hpp` and `` compile - with no backend linked.** A program that only draws random bytes or compares - tags names no backend library, and one that only signs names + library is linked; `config.hpp`, `error.hpp`, `random_device.hpp` and + `` compile with no backend linked.** A program that only + draws random bytes names no backend library, and one that only signs names `/third_party//secp256k1` alone. Source: `libraries/crypto/openspec/changes/genesis/reference/spec.md` section 2.2 (proposals); `test/Jamfile`'s headers-alone list (libs/crypto). -- **`constant_time_equal` compares in constant time: it reads every byte, - accumulates the XOR of each pair in a `volatile` local read once after the - loop and reduces it without a branch; spans of different sizes compare - unequal without their contents being read.** Hash2's `digest::operator==` - is `memcmp`; a size is public. - Source: `include/webcpp/crypto/constant_time_equal.hpp` (libs/crypto). +- **crypto's secret hygiene is webcpp::secure's: `secure::constant_time_equal`, + `secure::erase_secret`, `secure::secret`, `secure::declassify` and + `secure::detail::wipe`, with no alias in crypto.** crypto's `constant_time_equal.hpp`, + `erase_secret.hpp`, `secret.hpp`, `detail/wipe.hpp`, `detail/declassify.hpp` + and `detail/timing.hpp` are deleted, and a program that compared tags with + `crypto::constant_time_equal` names `webcpp::secure::constant_time_equal` + (``), which takes any two contiguous + sequences of bytes, Hash2's `digest` and `secret` included, reads + every byte, accumulates the XOR of each pair in a `volatile` local read once + after the loop and reduces it without a branch; sequences of different + sizes compare unequal without their contents being read, and a size is + public (chapter 17, secure). + Source: `libraries/secure/openspec/changes/genesis/design.md` D4 to D6 and + owner decision 5 (proposals); `include/webcpp/secure/constant_time_equal.hpp` + (libs/secure). - **Every public function that runs a backend's cryptographic code, and - `constant_time_equal`, holds `detail::timing_guard` as its first statement: - on 64-bit ARM under macOS, iOS, Linux and Android, where the CPU has - FEAT_DIT, it sets PSTATE.DIT for the call (`msr s3_3_c4_c2_5`, then `isb`) - and returns the thread's DIT as it found it, after an error and an exception - too; on x86, WebAssembly and Windows on ARM64 it is empty. A later - increment's public function that calls a backend holds one too and joins its - backend's coverage test, which checks through the seam - `WEBCPP_CRYPTO_DETAIL_TIMING_ENTERED` that each call entered its own - guard.** None of the C libraries sets DIT, which Apple requires of - constant-time code, and without it libsodium's X25519 was measured not - constant time on Apple silicon; a program does nothing. The guard's cost is - measured from a release build by `bench/collect.py --timing` and published - beside the throughput, and the constant-time lane sets no DIT of its own: it - measures what a program gets. webcpp::hash's keyed functions hold hash's own - copy of the guard, a change to either copy is a change to both, and - `test/timing_hash_interop_test.cpp` runs the two together (chapter 17, hash). + `secure::constant_time_equal`, holds `secure::timing_guard` as its first + statement: + on 64-bit ARM under macOS, iOS, Linux, Android and Windows, where the CPU + has FEAT_DIT, it sets PSTATE.DIT for the call and returns the thread's DIT + as it found it, after an error and while an exception unwinds the call too + (Windows on ARM64 clears DIT when it resumes the thread after a catch, chapter + 17, secure, D3); on x86, WebAssembly and ARM64EC it is empty. A later increment's public function that calls a + backend holds one too and joins its backend's coverage test, which checks + through the seam `WEBCPP_SECURE_TIMING_ENTERED` that each call entered its + own guard, counting the guards declared under `include/webcpp/crypto/`.** + None of the C libraries sets DIT, which Apple requires of constant-time + code, and without it libsodium's X25519 was measured not constant time on + Apple silicon; a program does nothing. The guard is the one of + webcpp::secure, which crypto, hash and the codecs share (chapter 17, + secure), so a keyed call of hash inside a guarded call of crypto nests in + either order, which `test/timing_nested_hash_test.cpp` runs. The guard's + cost of reference is secure's, measured from a release build and published + on its page (`doc/performance.adoc`); crypto's own page publishes the + throughput and keeps its own measurement of the guard, taken + by its bench (37.0 and 1.2 ns, on an idle machine), and the constant-time + lane sets no DIT of its own: it measures what a program gets. Source: `libraries/crypto/openspec/changes/data-independent-timing/design.md` - D1 to D7 (proposals); `include/webcpp/crypto/detail/timing.hpp`, - `test/timing_coverage__test.cpp`, - `test/timing_hash_interop_test.cpp` (libs/crypto). + D1 to D7 (proposals); `libraries/secure/openspec/changes/genesis/design.md` + D2 and D3 (proposals); `test/timing_coverage__test.cpp`, + `test/timing_nested_hash_test.cpp` (libs/crypto); + `include/webcpp/secure/timing_guard.hpp` (libs/secure). - **`` is reached only through `detail/windows.hpp`, which defines `NOMINMAX` and `WIN32_LEAN_AND_MEAN` only when absent and undefines only what it defined, and every header writes `(max)()`, `(min)()` and @@ -7278,7 +7304,8 @@ not built is in chapter 17. `from_secret`, `from_bytes`, `from_key`, `from_keys`, `from_keypair`, `derive_from_seed` and `generate`, with no `make`. Ed25519ph is a scheme, `eddsa_prehashed`; the secret-hygiene utilities are named by what they do: - `constant_time_equal`, `erase_secret`; the AEAD contract is + `constant_time_equal`, `erase_secret` (webcpp::secure's since that name + moved, chapter 17); the AEAD contract is `secret_key_encryption::aead`'s and the secret boxes `secret_key_encryption`'s; the one-shot ChaCha20-Poly1305 template is `ciphers::basic_chacha20_poly1305`. Bytes passed where a signature or a key @@ -7445,10 +7472,14 @@ not built is in chapter 17. (proposals); `test/support/counting.hpp`, `test/openssl_memory/Jamfile` (libs/crypto). - **Key schedules inside webcpp's objects are wiped on destruction and on - move by stores through a `volatile` pointer followed by - `std::atomic_signal_fence(std::memory_order_seq_cst)`.** The optimiser - cannot drop these stores, where it can drop a `memset`. - Source: `include/webcpp/crypto/detail/wipe.hpp` (libs/crypto). + move by webcpp::secure's wipe, `secure::detail::wipe`: stores through a + `volatile` pointer followed by + `std::atomic_signal_fence(std::memory_order_seq_cst)`; a C library's plain + state is erased as a range of one, + `secure::erase_secret(std::span(&context, 1))`.** The optimiser cannot drop + these stores, where it can drop a `memset`. + Source: `include/webcpp/secure/detail/wipe.hpp` (libs/secure); + `libraries/secure/openspec/changes/genesis/design.md` D4 (proposals). **OpenSSL's memory option (built after 0.1.0; plan Tasks 15, 16 and 33).** @@ -7497,9 +7528,15 @@ not built is in chapter 17. external linkage, each block headed by its size and aligned to the larger of `alignof(std::max_align_t)` and `__STDCPP_DEFAULT_NEW_ALIGNMENT__`; with exceptions each call into the resource sits in a `try` whose `catch (...)` - returns null.** OpenSSL calls them as C functions and frees without a size; - no exception may cross OpenSSL. - Source: `include/webcpp/crypto/backends/openssl.hpp` (libs/crypto). + returns null (or, in `free`, swallows the exception), inside a + `secure::timing_guard` engaged only when DIT is set, which sets DIT again + after the catch.** OpenSSL calls them as C functions and frees without a size; + no exception may cross OpenSSL. OpenSSL goes on after either catch inside the + guarded call that reached it, and Windows on ARM64 clears DIT when it resumes + a thread after a catch (chapter 17, secure, D3), so the adapter keeps DIT as + the call's guard wants; it never sets DIT where it was clear. + Source: `include/webcpp/crypto/backends/openssl.hpp`, + `test/openssl_memory/timing_adapter_test.cpp` (libs/crypto). - **On MSVC `backends/openssl.hpp` carries `#pragma detect_mismatch("webcpp_crypto_openssl_memory", ...)`, `"resource"` with the option and `"openssl"` without it.** Two files of one program @@ -8828,7 +8865,7 @@ increments 1 and 2, whose state is first. formats and PEM), `curves::x25519` and `kx_keypair`, `ciphers::aead` with `chacha20_poly1305` (also on BearSSL and OpenSSL), its original form and `xchacha20_poly1305`, `ciphers::secretbox`, `hybrid::box` and `sealed_box`, - and `secret` with the errors 15 to 20. `supports_v` and + and `secure::secret` with the errors 15 to 20. `supports_v` and `default_backend_t` read the capability table, which `doc/tables/generate.py` writes from `crypto.json` and the tests the Jamfiles declare (it replaced `capabilities.py` and `measure.py`); the own lanes are `c-suites` (the @@ -8845,7 +8882,7 @@ increments 1 and 2, whose state is first. timing), which wasmtime does not set; with DIT set in wasmtime's main thread, an experiment and not the lane, the case reads |t| 1.5 to 2.1. The native dudect programs no longer set DIT: the library sets it in each call on - 64-bit ARM (chapter 15); the WebAssembly cannot set it. The page's + 64-bit ARM, through webcpp::secure's guard (chapter 15); the WebAssembly cannot set it. The page's constant-time table and `crypto.json` record it as an open finding, not a pass, and the lane prints its value without judging it. Valgrind, MemorySanitizer and dudect are not run on wasip3 or Emscripten, which the @@ -8864,7 +8901,7 @@ increments 1 and 2, whose state is first. - **Built on the branch `crypto/secp256k1-modules` of the library and the superproject, on increment 1's merged trees, awaiting the owner's merge: - libsecp256k1's remaining modules.** ECDH in three forms, each a `secret` + libsecp256k1's remaining modules.** ECDH in three forms, each a `secure::secret` (`agree_hashed`, `agree`, `agree_point` since unified-sign), recoverable signatures (`sign(crypto::ecdsa_sha256_recoverable, input)` and `recover`), the tweaks, negation and @@ -8930,8 +8967,9 @@ Tasks 3.1 to 3.6, built on its branch, merged 2026-11-22).** - **Constant time is checked deterministically on Linux x86-64 and arm64 (Valgrind memcheck and MemorySanitizer, each harness failing on a planted leak, and libsecp256k1's `ctime_tests`), and statistically by dudect's - method natively and under wasmtime on wasip2, through the seam - `WEBCPP_CRYPTO_DETAIL_DECLASSIFY`.** `constant_time_equal` compiles in the + method natively and under wasmtime on wasip2, through webcpp::secure's + `secure::declassify` (built under `WEBCPP_SECURE_CT_VALGRIND` or + `WEBCPP_SECURE_CT_MSAN`).** `secure::constant_time_equal` compiles in the user's translation unit, so it is checked at -O2 and -Os; under wasmtime the engine's compiler decides whether BearSSL's `bmul64` stays constant time. The page's per-target cells are generated from the lane's own entries, and @@ -9005,7 +9043,7 @@ Tasks 3.1 to 3.6, built on its branch, merged 2026-11-22).** - **`ciphers::chacha20_poly1305` on BearSSL and OpenSSL is one shot only, with a nonce of exactly 12 bytes, refuses a message over 2^38 - 64 bytes with `message_too_long`, and where BearSSL leaves the tag check to its caller the - backend compares with `constant_time_equal` and zeroes `data` on a mismatch; + backend compares with `secure::constant_time_equal` and zeroes `data` on a mismatch; it is a family of the one-shot template `ciphers::basic_chacha20_poly1305`, not new traits.** BearSSL's ChaCha20-Poly1305 is one function over the whole message; 12 @@ -9527,11 +9565,12 @@ summary. `organization/openspec/changes/site-increments-4-5/specs/site/spec.md` (proposals). -### hash (hashing and key derivation over Boost.Hash2 and C backends; wrapper; accepted 2026-11-14, increments 1 to 7 built, not merged) +### hash (hashing and key derivation over Boost.Hash2 and C backends; wrapper; accepted 2026-11-14, increments 1 to 7 merged) webcpp::hash is one entry point for hashing and key derivation in a C++20 -program on every target webcpp has, a wrapper (`"port-of": null`). Increment 1 -is built on the library's branch (`libs/hash`, to become `webcpporg/hash`): +program on every target webcpp has, a wrapper (`"port-of": null`). It is +implemented in `webcpporg/hash`, the submodule `libs/hash`, its increments 1 to +7 merged into the `main` of its repository and of the superproject. Increment 1: Boost.Hash2's algorithms and `hmac` re-exported by alias (`algorithms.hpp`, `hmac.hpp`); Keccak-256 with the original padding over XKCP's permutation (`keccak.hpp`) and BLAKE3 over its official C implementation (`blake3.hpp`), @@ -9573,9 +9612,8 @@ allocates nothing in webcpp's own code; increment 7 adds an asynchronous family in `async.hpp` over webcpp::asio (any completion token, Cobalt's `use_op` included): the password hashes and PBKDF2 on a thread pool where the build has threads, the digests, HMAC and HKDF through a post, and `backends::webcrypto`, -the browser's WebCrypto on Emscripten, which only that family takes. Its -repository, `webcpporg/hash`, is still to be created by the owner (gates G1, G2 -and G4); the proposal, with the specification, the design and the plan, is in +the browser's WebCrypto on Emscripten, which only that family takes. The +proposal, with the specification, the design and the plan, is in `libraries/hash/openspec/changes/genesis/` (proposals). - **Two constructions of webcpp's own, over an audited primitive each, and no @@ -9608,7 +9646,7 @@ and G4); the proposal, with the specification, the design and the plan, is in Source: `libraries/hash/openspec/changes/genesis/reference/spec.md` section 5 (proposals). - **Every function that computes on a key, a password or a key derivation's - secret input holds `detail::timing_guard` as its first statement, on every + secret input holds `secure::timing_guard` as its first statement, on every backend: `mac`, the key derivations, the password hashes (`bcrypt_verify` included), and the keyed modes of BLAKE2b (`digest_of` and `hasher` when the options carry a key) and of the `blake3` class, which construct it with @@ -9625,17 +9663,29 @@ and G4); the proposal, with the specification, the design and the plan, is in (`test/timing_coverage__test.cpp`) reads `doc/capabilities.json` and fails when a keyed cell has no call, when a call's first guard is not its own function's, or when an unkeyed function enters one: a new keyed - function or cell holds the guard and gets its call. The guard is a copy of - webcpp::crypto's (`include/webcpp/hash/detail/timing.hpp`; crypto depends on - hash, so hash cannot include crypto's), with the engaged flag added; a change - to either copy is made to both, and crypto's - `test/timing_hash_interop_test.cpp` runs the two nested in either order. Its - cost is measured from a release build by `bench/collect.py --timing` and - published in `doc/performance.adoc`. + function or cell holds the guard and gets its call. The guard is webcpp::secure's, the one guard + crypto and hash share (hash depends on config and secure and on no other + webcpp library), with its `guard_engaged` flag: hash's first copy, + `detail/timing.hpp`, is deleted, and so is `detail/wipe.hpp`, whose stores + are `secure::detail::wipe`, reached through `secure::erase_secret` (a range + of one erases a C library's plain state). A test of hash counts its own + guards through the seam `WEBCPP_SECURE_TIMING_ENTERED`, filtered by + `include/webcpp/hash/` in the guard's `file_name()`, and reads + `secure::test::wipe_record` (`WEBCPP_SECURE_TEST_WIPE_RECORD`) for what a + wipe zeroed; crypto's `test/timing_nested_hash_test.cpp` runs a guarded call + of hash inside a guarded call of crypto. The guard's cost of reference is + secure's, measured from a release build and published in secure's + `doc/performance.adoc`; hash's own page keeps its own measurement of the + guard, taken by its bench on an idle machine. The guard leaves the thread's + DIT as it found it after an error and while an exception unwinds the call; + Windows on ARM64 clears DIT when it resumes the thread after a catch (chapter + 17, secure, D3), and hash's own catches inside a guarded scope (Botan's + boundary) only erase and free before they return. Source: `libraries/hash/openspec/changes/data-independent-timing/design.md` - D1 to D9 (proposals); `include/webcpp/hash/detail/timing.hpp`, - `test/timing_coverage__test.cpp` (libs/hash); - `test/timing_hash_interop_test.cpp` (libs/crypto). + D1 to D9, whose copy of the guard `libraries/secure/openspec/changes/genesis/design.md` + D2 and D4 replaced (proposals); `test/timing_coverage__test.cpp`, + `test/support/timing_seam.hpp`, `test/support/wipe_record.hpp` (libs/hash); + `test/timing_nested_hash_test.cpp` (libs/crypto). - **hash follows crypto's naming rule: public names spelled out, algorithm proper names excepted.** HKDF's `ikm`, `prk` and `info` are renamed by a change of hash's. @@ -9661,6 +9711,252 @@ and G4); the proposal, with the specification, the design and the plan, is in Source: `libraries/hash/openspec/changes/genesis/reference/spec.md` section 1.5 (proposals). +### secure (side-channel and secret-in-memory primitives; own; accepted 2026-11-24, implemented) + +webcpp::secure is the one home of the primitives that crypto, hash and the +codecs share to keep a secret from leaking through time and through memory, and +holds no algorithm (`"port-of": null`, category Cryptography). It is +implemented in `webcpporg/secure`, the submodule `libs/secure`, merged into the +`main` of its repository and of the superproject with hash's and crypto's +migrations onto it. Its headers are ``, which includes the +others, and `` +with ``; its target is `/webcpp/secure//secure`, +header-only, depending on config and Boost's assert alone; every name is in +`webcpp::secure` (the blocks in `webcpp::secure::constant_time`, test support in +`webcpp::secure::test`), every function is `noexcept` and none allocates or +throws. The proposal, with the specification, the design and the plan, is in +`libraries/secure/openspec/changes/genesis/` (proposals); the page is +`libs/secure/doc/`. The owner's nine decisions of 2026-11-24 are binding: a new +library with no algorithm; config alone as its dependency, config staying macros +only; everything under `webcpp::secure` and ``; the guard as a +public API; `erase_secret`, `constant_time_equal` and `secret` moved from +crypto with their names and no alias; the checkers' markers; the constant-time +building blocks codecs needs; test support in each library's own +`test/support/`; and the migrations of hash and then crypto in the same +delivery. + +- **D1: one target, `secure`, headers only, nothing compiled and nothing + linked; no header of another webcpp library but config's.** `config.hpp`, + included first by every public header, includes `` first + and defines `WEBCPP_SECURE_NO_EXCEPTIONS` by chapter 6's rule; include guards + are `WEBCPP_SECURE__HPP`; `secure::detail` is not API and no header of + another library includes a header of `detail/`. The system calls the guard + makes are the C library's and the compiler's intrinsics. Every test runs with + exceptions on and off (`secure-run`, `secure-compile`), on native (clang and + gcc 15), wasip2, wasip3 and Emscripten, and on MSVC 14.3 and 14.5. + Source: `libraries/secure/openspec/changes/genesis/design.md` D1 + (proposals); `build.jam`, `include/webcpp/secure/config.hpp` (libs/secure). +- **D2: `timing_guard`, `cpu_has_dit()` and `dit_is_set()` are public, the one + guard of webcpp's libraries, and nest in any order.** An engaged guard runs + the seam (a test's build), sets DIT when the CPU has FEAT_DIT and it is clear, + and leaves DIT at its end as it found it: it clears DIT when it set it, and a + guard that found DIT set reads it again and sets it if something inside its + scope cleared it (a catch on Windows on ARM64, D3); a disengaged guard + (`timing_guard{false}`, for a function keyed only by its arguments) does + nothing, the seam included; each write keeps its `memory` clobber and an + `isb` after it; the guard is not copyable and not movable. A guard that finds + DIT set leaves it set, so crypto inside hash, hash inside crypto and a program + that set DIT itself all keep their state, and DIT is one thread's: a guard + never changes another's. The seam is `WEBCPP_SECURE_TIMING_ENTERED(where)`, + defined by a test before its first include in every translation unit of its + program (the constructor then takes a trailing `std::source_location`, so + the One Definition Rule applies); without it no function name or path reaches + a program. A library tells its own guards by `file_name()`, anchored on + `include/webcpp//` with either separator (B6). The page says what DIT + covers, Arm's list of data-independent instructions, and what it does not: + memory access patterns, branches, and arithmetic on registers that the + compiler may move across the writes. The guard costs 37.0 ns where it sets + and clears DIT, 1.2 ns where DIT is already set (two `mrs`) and nothing where + disengaged, + measured on a release build on an Apple M5 Max at a 1-minute load of 1.9, as + the page states (`bench/collect.py`, 2026-11-26). + Source: `libraries/secure/openspec/changes/genesis/design.md` D2 and owner + decision 4 (proposals); `include/webcpp/secure/timing_guard.hpp`, + `test/timing_guard_*_test.cpp`, `doc/guard.adoc` (libs/secure). +- **D3: coverage by target, and FEAT_DIT on Windows.** The guard acts on + `defined(__aarch64__) && (defined(__APPLE__) || defined(__linux__))` (Android + included) and on `defined(_MSC_VER) && defined(_M_ARM64) && !defined(_M_ARM64EC)`; + there `WEBCPP_SECURE_TIMING_COVERED` is defined. Elsewhere (x86, ARM64EC, + WebAssembly) it is an empty class and both functions return `false`. FEAT_DIT + is read once: by `sysctlbyname("hw.optional.arm.FEAT_DIT")` on Apple's + systems, `getauxval(AT_HWCAP)` and `HWCAP_DIT` on Linux, and on Windows, which + documents neither a feature flag nor a user-mode read of `ID_AA64PFR0_EL1`, + by one read of the DIT register under `__try` and `__except`, whose filter + takes `STATUS_ILLEGAL_INSTRUCTION` as absent, in a function of its own that + holds no object needing unwinding (C2712); it needs `` and + ``, not ``. No DIT instruction runs where FEAT_DIT may + be absent but that read. Measured: on the owner's Windows 11 ARM64 machine, + MSVC 14.3 and 14.5, debug and release, the guard sets DIT and keeps it across + sleeps. Windows on ARM64 keeps DIT through the search for a handler, the + unwinding and the catch block, then resumes the thread after the catch (or in + an `__except` block) with DIT clear, from set as from clear + (`RtlRestoreContext`, observed on MSVC 14.3 and 14.5, debug and release; + Microsoft documents none of it): a guard whose scope holds the catch leaves + DIT as it found it at its end, code that computes on a secret after such a + catch holds a guard of its own, code that catches inside a guarded scope and + returns into a C library holds, around its `try`, a guard engaged only when + DIT is set (crypto's OpenSSL memory adapter), and after a catch outside every + guard DIT is clear. **Not tested: the path where FEAT_DIT is absent, which no + machine available ran; the filter is small, reviewed and fails closed.** + Source: `libraries/secure/openspec/changes/genesis/design.md` D3 and B7 + (proposals); `include/webcpp/secure/timing_guard.hpp`, + `test/timing_guard_windows_test.cpp`, `test/timing_guard_exceptions_test.cpp`, + `doc/guard.adoc` (libs/secure). +- **D4: `erase_secret(Range&&)` is crypto's, moved, over `secure::detail::wipe`, + and a C library's plain state is erased as a range of one (B1).** It takes a + contiguous sized range of non-const, trivially copyable elements, zeroes + `size() * sizeof(element)` bytes (a `std::string`'s size, not its capacity), + has no pointer and size form, and a refused range stops the build with a + message naming the ranges it takes. The wipe is stores through a `volatile` + pointer and then `std::atomic_signal_fence(std::memory_order_seq_cst)`. Its + test seam (B9) is hash's moved: a program built with + `WEBCPP_SECURE_TEST_WIPE_RECORD` defines + `secure::test::wipe_record(void const*, std::size_t)`, which `detail::wipe` + calls once its bytes are zero; without the macro nothing is declared. The + wipe covers the object's own storage, not a copy in a register or a + temporary. + Source: `libraries/secure/openspec/changes/genesis/design.md` D4, B1 and B9 + (proposals); `include/webcpp/secure/erase_secret.hpp`, + `include/webcpp/secure/detail/wipe.hpp`, `test/erase_secret_test.cpp`, + `test/wipe_record_test.cpp` (libs/secure). +- **D5: `constant_time_equal(first, second)` is one function over any two + contiguous sized ranges of one-byte elements (`std::uint8_t`, + `unsigned char`, `char`, `std::byte`), and over a `secret` or a type whose + `bytes()` view it reads (B2).** It names no Boost.Hash2 type, so a `digest` + works through its own range. Different sizes compare unequal without reading + the contents, a size being public; otherwise every byte is read, the XOR of + each pair accumulated with OR in a `volatile` local read once after the loop + and reduced to one bit without a branch (BearSSL's tag check, as crypto's), + under an engaged guard. A by-value `bytes()` result is held for the whole + comparison, so a temporary key's view does not dangle; `char` with the high bit + set and a sequence whose `data()` is null with a size of 31 against 32 bytes + are pinned by tests. + Source: `libraries/secure/openspec/changes/genesis/design.md` D5 and B2 + (proposals); `include/webcpp/secure/constant_time_equal.hpp`, + `test/constant_time_equal_test.cpp` (libs/secure). +- **D6: `secret` is crypto's, moved with its interface.** `N > 0`; + zero-initialised; move-only, the source wiped on move and the target wiped + before it takes new bytes, a self-move changing nothing; `clone()` the only + copy; `bytes()` and the implicit view as `std::span` + on an lvalue, deleted on an rvalue so that no view dangles; `writable()` on an + lvalue; wiped on destruction through `detail::wipe`. A function that accepts + a secret accepts it through `bytes()` although it is not a range. + Source: `libraries/secure/openspec/changes/genesis/design.md` D6 + (proposals); `include/webcpp/secure/secret.hpp`, `test/secret_test.cpp` + (libs/secure). +- **D7: `declassify(x)` is a function template on a non-const trivially + copyable lvalue, empty in a program's build, memcheck's or MemorySanitizer's + in a checker's (B3).** Library code calls it on a value derived from secrets + that it branches on by design, right before the branch; the value is never + const, so that the branch reads it again. Under `WEBCPP_SECURE_CT_VALGRIND` it + is `VALGRIND_MAKE_MEM_DEFINED` and includes ``; under + `WEBCPP_SECURE_CT_MSAN` it is `__msan_unpoison`; defining both stops the + build; neither includes anything in a program's build. The other half, + marking a secret and reading a checker's shadow, only a test does + (`test/support/constant_time_marks.hpp`), copied rather than moved from + crypto's, which keeps its own for its lane. + Source: `libraries/secure/openspec/changes/genesis/design.md` D7 and B3 + (proposals); `include/webcpp/secure/declassify.hpp`, + `test/declassify_compile_test.cpp` (libs/secure). +- **D8: the constant-time blocks (`constant_time::value_barrier`, + `mask_from_bit`, `is_zero_mask`, `is_equal_mask`, `is_less_mask`, + `is_in_range_mask`, `select`, `lookup`, `select_bytes`, `equal_mask`, + `less_mask`) take any unsigned integral type but `bool`, return masks (all + zeros or all ones, never a `bool`) and pass every mask through + `value_barrier` (B4, B5).** `value_barrier` is an `asm volatile` statement + with the value in a register on GCC and clang (BoringSSL's), a `volatile` + round trip on MSVC, on WebAssembly and under clang's MemorySanitizer (which + reports an `asm` statement's register input), and the identity in a constant + expression. `std::unsigned_integral` admits `bool`, so the blocks are + constrained by `detail::mask_word`, `std::unsigned_integral && !std::same_as`. + `lookup` reads every entry in order, compares the index in the wider of + `std::size_t` and the entry (a 64-bit entry keeps its top half on + WebAssembly's 32-bit `size_t`) and returns a value-initialised element for an + index past the table, `SIZE_MAX` included; its cost is the table's size, so a + caller with a large public table indexes it directly. The byte blocks read + every byte of both sequences, whose sizes are public and must be equal + (`BOOST_ASSERT` in a debug build; unequal sizes give the zero mask or write + nothing, pinned with assertions off); `less_mask` compares as big-endian + unsigned numbers. There are no signed blocks and no `msb`. Tests check every + block against a plain reference over every pair, and triple for + `is_in_range_mask`, of `std::uint8_t`, at random over the wider types with + their edges, in constant expressions where declared, and for allocation (a + counting `operator new` of every form sees none). + Source: `libraries/secure/openspec/changes/genesis/design.md` D8, B4 and B5 + (proposals); `include/webcpp/secure/constant_time.hpp`, + `test/constant_time_test.cpp`, `test/constant_time_sizes_test.cpp`, + `test/allocation_test.cpp` (libs/secure). +- **D9 and O1: test support lives in each library's own `test/support/`.** + secure's own are `timing_seam.hpp` (a recorder counting guards entered, + keeping the first's `function_name()`, filtered by `file_name()`), + `timing_dit.hpp` (`force_dit`, to test that a program that set DIT keeps it) + and `constant_time_marks.hpp`, in `webcpp::secure::test`; hash keeps its seam + recorder and DIT helper and its wipe recorder, and crypto keeps its seam + recorder and marks and has a DIT helper, each pointed at secure's seam and + counting its own library's guards. Not in `tools/node-test`, and no + `webcpp::core` library is made for them (owner's decision O1 of + 2026-11-24); hex helpers stay where they are. + Source: `libraries/secure/openspec/changes/genesis/design.md` D9 and O1 + (proposals); `test/support/` (libs/secure, libs/hash, libs/crypto). +- **D10: the lane `constant-time` (`test/constant_time/`) checks the machine + code of every block, `constant_time_equal` and `secret`'s moves, at the + speed and the space optimisation, and every checker runs planted leaks that it + must report.** memcheck (Valgrind, the operands marked undefined, ctgrind) + and MemorySanitizer (clang) report a `select` written with a branch and a + `lookup` that indexes; memcheck also reports a branch on an undeclassified + verdict; dudect, natively, with a control of two identical classes, measures + `constant_time_equal`, `lookup`, `select_bytes` and `less_mask` and a planted + comparison that returns at the first byte that differs. The CI's judge + (`test/constant_time/dudect_judge.py`, crypto's copied, tested by + `tools/test/secure_dudect_judge_test.py`) warns at |t| of 10 and fails a + hosted runner on two of three. The lane's programs are native only, one + checker build each, with no `_no_exceptions` twins, and its Jamfile says so; + the lane is `matrix.py`'s and `library.yml`'s, with its packages. **Measured + limits, recorded on the page and not hidden:** MemorySanitizer does not + report a branch on an undeclassified verdict (it drops a subtraction's carry, + so the verdict comes out initialised), and memcheck checks it; under + MemorySanitizer `value_barrier` is the round trip, not the `asm` statement; a + checker sees one compiler and one build, and the runs for the page used + Valgrind with gcc 14 because gcc 15 was not in the lane's container; dudect + shows a leak and cannot prove there is none; the x86-64 lane was not run + locally. + Source: `libraries/secure/openspec/changes/genesis/design.md` D10 + (proposals); `test/constant_time/Jamfile`, `doc/blocks.adoc` (libs/secure); + `tools/ci/matrix.py`, `tools/test/secure_dudect_judge_test.py` (webcpp). +- **D11: the documentation and the one measurement.** The page (`doc/`): what + secure is and is not, the guard with its coverage table, nesting, `guard_engaged` + and seam, erasing, `secret`, `constant_time_equal`, `declassify`, the + blocks with their limits, the guard's cost and the changelog. The cost is + measured by `bench/collect.py` from a release build (it refuses another + variant), which writes `doc/measurements.json` and `doc/performance.adoc` + (generated, never edited) and states the machine's load averages, the + figures to be taken on an idle machine with a 1 minute load average below 2; + `tools/test/secure_collect_test.py` tests the script. The guard's lane on the + owner's Windows ARM64 virtual machine runs in a release build too, which the + withdrawn change did not. + Source: `libraries/secure/openspec/changes/genesis/design.md` D11 + (proposals); `bench/collect.py`, `doc/performance.adoc` (libs/secure). +- **B6 to B8: one seam told by `file_name()`; FEAT_DIT on Windows by an + SEH-guarded read; `` includes every header.** None of the + headers brings a heavy dependency, so the convenience header costs a program + nothing it did not ask for, and `convenience_header_test` compiles it alone. + Source: `libraries/secure/openspec/changes/genesis/design.md` B6 to B8 + (proposals); `test/convenience_header_test.cpp`, + `test/timing_seam_support_test.cpp` (libs/secure). +- **The migrations are in the delivery (owner decision 9).** hash's guard and + wipe and then crypto's every guard, wipe, erase, comparison, secret and + declassify are secure's; `crypto/detail/timing.hpp`, `detail/wipe.hpp`, + `detail/declassify.hpp`, `erase_secret.hpp`, `constant_time_equal.hpp` and + `secret.hpp` and hash's `detail/timing.hpp` and `detail/wipe.hpp` are deleted + with no alias; hash depends on config and secure, crypto on hash and secure; + crypto's `timing_hash_interop_test` is `timing_nested_hash_test`, which nests + a guarded hash call in a guarded crypto call; the tools' user Jamfile tests + copy `libs/secure` as they copy hash's. + Source: `libraries/secure/openspec/changes/genesis/design.md` Migration Plan + (proposals); `tools/test/secure_jamfiles_test.py`, + `tools/test/crypto_jamfiles_test.py`, `tools/test/hash_jamfiles_test.py` + (webcpp). + ## 18. Proposed, not decided The proposals not yet decided, each briefly, with the questions they leave diff --git a/doc/releases/0.1.0.adoc b/doc/releases/0.1.0.adoc index fd4ada5a..2ef3aef4 100644 --- a/doc/releases/0.1.0.adoc +++ b/doc/releases/0.1.0.adoc @@ -39,6 +39,10 @@ each also a Boost.URL grammar rule, from R. * link:{library-pages}pratt/{library-page}[pratt]: a header-only Pratt-parsing engine for {cpp}20, with a decimal calculator built on it, from R. +* link:{library-pages}secure/{library-page}[secure]: the side-channel and +secret-in-memory primitives of crypto, hash and the codecs for {cpp}20: a +DIT timing guard, erase_secret, secret, constant_time_equal, declassify and +constant-time blocks, with no algorithm, from R. * link:{library-pages}trystero/{library-page}[trystero]: a port of Trystero 0.26.0, serverless WebRTC rooms wire-compatible with the original, for {cpp}20, from R. @@ -77,6 +81,10 @@ None. * Improved lint preparation by separating OpenSSL headers from archive builds and upstream tests. * Changed the CI's lint to twelve shards, which a slow runner no longer takes past its time limit. * Added the user's Jamfiles of webcpp::crypto, tested as fixtures of a test of the tools. +* Added the user's Jamfiles of webcpp::secure, tested as fixtures of a test of the tools, and `libs/secure` to the copy of the user's Jamfiles tests of crypto and hash. +* Added secure_collect_test.py, which tests the script that measures the timing guard's cost from release builds. +* Added secure_dudect_judge_test.py, which runs crypto's judge's tests against secure's copy. +* Added secure's constant-time lane to matrix.py and library.yml: memcheck, MemorySanitizer and dudect over its blocks, each with a planted leak that must fail. * Added a judge to crypto's constant-time lane: dudect results warn at 10, and hosted runners fail on two of three. * Added same-as: to crypto's user Jamfiles test, which keeps copied programs identical. * Added not-contains: to crypto's user Jamfiles test, which shows the canary is a library's only link error. diff --git a/libs/crypto b/libs/crypto index 3314a1d1..7b2c7769 160000 --- a/libs/crypto +++ b/libs/crypto @@ -1 +1 @@ -Subproject commit 3314a1d122220f960fc72920b239131ee314b6a3 +Subproject commit 7b2c7769c9d45804e0e365bdce8e465df021c7cc diff --git a/libs/hash b/libs/hash index 569b51bc..98978579 160000 --- a/libs/hash +++ b/libs/hash @@ -1 +1 @@ -Subproject commit 569b51bc5d160a1d6dc290229b4fcde323b053ea +Subproject commit 98978579349ed06bc11937a94d31bae346258971 diff --git a/libs/secure b/libs/secure new file mode 160000 index 00000000..951401a3 --- /dev/null +++ b/libs/secure @@ -0,0 +1 @@ +Subproject commit 951401a39cba8855c1866b1cb58f1fa53837c735 diff --git a/tools/ci/actions/boost/patches/cobalt-coroutine-align-msvc.patch b/tools/ci/actions/boost/patches/cobalt-coroutine-align-msvc.patch new file mode 100644 index 00000000..625711df --- /dev/null +++ b/tools/ci/actions/boost/patches/cobalt-coroutine-align-msvc.patch @@ -0,0 +1,348 @@ +Boost 1.92.0's Boost.Cobalt gives a coroutine frame storage aligned to std::max_align_t only: its +promises' operator new (promise_memory_resource_base in boost/cobalt/this_coro.hpp, Cobalt's +promise, task, generator and detached) stores the memory resource in the first +sizeof(std::max_align_t) bytes of the block and returns the address after them. On MSVC +std::max_align_t is 8 bytes and __STDCPP_DEFAULT_NEW_ALIGNMENT__ is 16, so the frame lies 8 bytes +off a 16-byte boundary, though an operator new without std::align_val_t must return storage +aligned to 16 there. MSVC's optimizer stores into the frame with aligned SSE instructions (movaps), +which fault: webcpp::hash's async_cobalt test exited with 0xC0000005 on MSVC 14.3 x64 release in +every run (the fault at movaps [frame+0x6D90] with the frame at 8 mod 16). The upstream fix is +https://github.com/boostorg/cobalt/commit/d67080b ("Added MSVC max_align workaround"), which adds +boost::cobalt::coroutine_align and coroutine_align_t to config.hpp and uses them in every coroutine +allocation of Cobalt. This patch takes the same names and the same places, MSVC's values (16, and +a 16-byte type aligned to 16) and upstream's change to the unsized branch of detail/main.hpp, in +one other form: the header before a frame is counted in sizeof(coroutine_align_t), where upstream +counts it in coroutine_align. Off MSVC, coroutine_align is alignof(std::max_align_t) and +coroutine_align_t is std::max_align_t, so every size, offset and alignment is Boost 1.92.0's (the +alignment the patch passes is the one the resources took by default), and only MSVC's build +changes; upstream's form would also shrink the header off MSVC, from 32 to 16 bytes on x86-64 and +arm64 Linux and on WebAssembly. Remove this file once the Boost that +tools/ci/actions/boost/install.sh pins contains the upstream fix: install.sh then fails, saying the +patch does not apply. + +diff --git a/boost/cobalt/composition.hpp b/boost/cobalt/composition.hpp +--- a/boost/cobalt/composition.hpp ++++ b/boost/cobalt/composition.hpp +@@ -98,14 +98,14 @@ struct composition_promise + using tt = std::pair; + + // | memory_resource | size_t | | coroutine. +- constexpr auto block_size = sizeof(tt) / sizeof(std::max_align_t) +- + (sizeof(tt) % sizeof(std::max_align_t) ? 1 : 0); ++ constexpr auto block_size = sizeof(tt) / sizeof(coroutine_align_t) ++ + (sizeof(tt) % sizeof(coroutine_align_t) ? 1 : 0); + + + auto res = std::get(std::tie(args...)).get_allocator().resource(); +- const auto p = res->allocate(size + (block_size * sizeof(std::max_align_t))); ++ const auto p = res->allocate(size + (block_size * sizeof(coroutine_align_t)), coroutine_align); + new (p) tt(res, size); +- return static_cast(p) + block_size; ++ return static_cast(p) + block_size; + } + + static void operator delete(void * raw) noexcept +@@ -113,16 +113,16 @@ struct composition_promise + using tt = std::pair; + + // | memory_resource | size_t | | coroutine. +- constexpr auto block_size = sizeof(tt) / sizeof(std::max_align_t) +- + (sizeof(tt) % sizeof(std::max_align_t) ? 1 : 0); ++ constexpr auto block_size = sizeof(tt) / sizeof(coroutine_align_t) ++ + (sizeof(tt) % sizeof(coroutine_align_t) ? 1 : 0); + +- const auto p = static_cast(raw) - block_size; ++ const auto p = static_cast(raw) - block_size; + + const auto tp = *reinterpret_cast(p); + const auto res = tp.first; + const auto size = tp.second; + +- res->deallocate(p, size + (block_size * sizeof(std::max_align_t))); ++ res->deallocate(p, size + (block_size * sizeof(coroutine_align_t)), coroutine_align); + } + + completion_handler handler; +diff --git a/boost/cobalt/config.hpp b/boost/cobalt/config.hpp +--- a/boost/cobalt/config.hpp ++++ b/boost/cobalt/config.hpp +@@ -6,6 +6,7 @@ + // + + #include ++#include + + #ifndef BOOST_COBALT_CONFIG_HPP + #define BOOST_COBALT_CONFIG_HPP +@@ -90,6 +91,21 @@ namespace pmr = boost::container::pmr; + namespace pmr = std::pmr; + #endif + ++// The alignment of the storage cobalt gives a coroutine frame, and coroutine_align_t the unit of ++// the header before it. std::max_align_t is only 8-byte aligned on MSVC, but the compiler may emit ++// aligned SSE stores into the frame. Elsewhere they are alignof(std::max_align_t) and ++// std::max_align_t, as in Boost 1.92.0, so that nothing changes there. ++#if defined(BOOST_MSVC) ++constexpr static std::size_t coroutine_align = 16; ++struct alignas(coroutine_align) coroutine_align_t ++{ ++ unsigned char bytes_[coroutine_align]; ++}; ++#else ++constexpr static std::size_t coroutine_align = alignof(std::max_align_t); ++using coroutine_align_t = std::max_align_t; ++#endif ++ + } + + #if !defined(BOOST_COBALT_SOURCE) && !defined(BOOST_ALL_NO_LIB) && !defined(BOOST_COBALT_NO_LIB) +diff --git a/boost/cobalt/detail/main.hpp b/boost/cobalt/detail/main.hpp +--- a/boost/cobalt/detail/main.hpp ++++ b/boost/cobalt/detail/main.hpp +@@ -56,29 +56,29 @@ struct main_promise : signal_helper, + #if defined(__cpp_sized_deallocation) + void * operator new(const std::size_t size) + { +- return my_resource->allocate(size); ++ return my_resource->allocate(size, coroutine_align); + } + + void operator delete(void * raw, const std::size_t size) + { +- return my_resource->deallocate(raw, size); ++ return my_resource->deallocate(raw, size, coroutine_align); + } + #else + void * operator new(const std::size_t size) + { + // embed the size at the end +- constexpr auto sz = (std::max)(alignof(std::max_align_t), sizeof(std::size_t)); +- auto data = my_resource->allocate(size + sz); ++ constexpr auto sz = (std::max)(coroutine_align, sizeof(std::size_t)); ++ auto data = my_resource->allocate(size + sz, coroutine_align); + + return static_cast(data) + sz; + } + + void operator delete(void * data) + { +- constexpr auto sz = (std::max)(alignof(std::max_align_t), sizeof(std::size_t)); ++ constexpr auto sz = (std::max)(coroutine_align, sizeof(std::size_t)); + const auto size = *reinterpret_cast(static_cast(data) - sz); + +- return my_resource->deallocate(data, size); ++ return my_resource->deallocate(data, size, coroutine_align); + } + #endif + +diff --git a/boost/cobalt/detail/monotonic_resource.hpp b/boost/cobalt/detail/monotonic_resource.hpp +--- a/boost/cobalt/detail/monotonic_resource.hpp ++++ b/boost/cobalt/detail/monotonic_resource.hpp +@@ -67,7 +67,7 @@ struct monotonic_resource + } + } + +- constexpr void * allocate(std::size_t size, std::align_val_t align_ = std::align_val_t(alignof(std::max_align_t))) ++ constexpr void * allocate(std::size_t size, std::align_val_t align_ = std::align_val_t(coroutine_align)) + { + const auto align = (std::max)(static_cast(align_), alignof(block_)); + // let's say size = 11, and align is 8, that leaves us with 3 +diff --git a/boost/cobalt/detail/sbo_resource.hpp b/boost/cobalt/detail/sbo_resource.hpp +--- a/boost/cobalt/detail/sbo_resource.hpp ++++ b/boost/cobalt/detail/sbo_resource.hpp +@@ -33,19 +33,19 @@ struct sbo_resource + #endif + constexpr std::size_t align_as_max_(std::size_t size) + { +- auto diff = size % alignof(std::max_align_t ); ++ auto diff = size % coroutine_align; + if (diff > 0) +- return size + alignof(std::max_align_t) - diff; ++ return size + coroutine_align - diff; + else + return size; + } + constexpr void align_as_max_() + { + const auto buffer = static_cast(buffer_.p) - static_cast(nullptr); +- const auto diff = buffer % alignof(std::max_align_t ); ++ const auto diff = buffer % coroutine_align; + if (diff > 0) + { +- const auto padding = alignof(std::max_align_t) - diff; ++ const auto padding = coroutine_align - diff; + buffer_.p = static_cast(static_cast(nullptr) + buffer + padding); + if (padding >= buffer_.size) [[unlikely]] + { +@@ -143,13 +143,13 @@ struct sbo_resource + #if defined(BOOST_COBALT_NO_PMR) + [[nodiscard]] + void* +- allocate(size_t bytes, size_t alignment = alignof(std::max_align_t)) ++ allocate(size_t bytes, size_t alignment = coroutine_align) + { + return ::operator new(bytes, do_allocate(bytes, alignment)); + } + + void +- deallocate(void* p, size_t bytes, size_t alignment = alignof(std::max_align_t)) ++ deallocate(void* p, size_t bytes, size_t alignment = coroutine_align) + { + return do_deallocate(p, bytes, alignment); + } +diff --git a/boost/cobalt/this_coro.hpp b/boost/cobalt/this_coro.hpp +--- a/boost/cobalt/this_coro.hpp ++++ b/boost/cobalt/this_coro.hpp +@@ -341,17 +341,17 @@ struct promise_memory_resource_base + static void * operator new(const std::size_t size, Args & ... args) + { + auto res = detail::get_memory_resource_from_args(args...); +- const auto p = res->allocate(size + sizeof(std::max_align_t)); ++ const auto p = res->allocate(size + sizeof(coroutine_align_t), coroutine_align); + auto pp = static_cast(p); + *pp = res; +- return static_cast(p) + 1; ++ return static_cast(p) + 1; + } + + static void operator delete(void * raw, const std::size_t size) noexcept + { +- const auto p = static_cast(raw) - 1; ++ const auto p = static_cast(raw) - 1; + pmr::memory_resource * res = *reinterpret_cast(p); +- res->deallocate(p, size + sizeof(std::max_align_t)); ++ res->deallocate(p, size + sizeof(coroutine_align_t), coroutine_align); + } + #else + template +@@ -360,14 +360,14 @@ struct promise_memory_resource_base + using tt = std::pair; + + // | memory_resource | size_t | | coroutine. +- constexpr auto block_size = sizeof(tt) / sizeof(std::max_align_t) +- + (sizeof(tt) % sizeof(std::max_align_t) ? 1 : 0); ++ constexpr auto block_size = sizeof(tt) / sizeof(coroutine_align_t) ++ + (sizeof(tt) % sizeof(coroutine_align_t) ? 1 : 0); + + + auto res = detail::get_memory_resource_from_args(args...); +- const auto p = res->allocate(size + (block_size * sizeof(std::max_align_t))); ++ const auto p = res->allocate(size + (block_size * sizeof(coroutine_align_t)), coroutine_align); + new (p) tt(res, size); +- return static_cast(p) + block_size; ++ return static_cast(p) + block_size; + } + + static void operator delete(void * raw) noexcept +@@ -375,16 +375,16 @@ struct promise_memory_resource_base + using tt = std::pair; + + // | memory_resource | size_t | | coroutine. +- constexpr auto block_size = sizeof(tt) / sizeof(std::max_align_t) +- + (sizeof(tt) % sizeof(std::max_align_t) ? 1 : 0); ++ constexpr auto block_size = sizeof(tt) / sizeof(coroutine_align_t) ++ + (sizeof(tt) % sizeof(coroutine_align_t) ? 1 : 0); + +- const auto p = static_cast(raw) - block_size; ++ const auto p = static_cast(raw) - block_size; + + const auto tp = *reinterpret_cast(p); + const auto res = tp.first; + const auto size = tp.second; + +- res->deallocate(p, size + (block_size * sizeof(std::max_align_t))); ++ res->deallocate(p, size + (block_size * sizeof(coroutine_align_t)), coroutine_align); + } + #endif + +@@ -400,14 +400,14 @@ private: + template + void *allocate_coroutine(const std::size_t size, AllocatorType alloc_) + { +- using alloc_type = typename std::allocator_traits::template rebind_alloc; ++ using alloc_type = typename std::allocator_traits::template rebind_alloc; + alloc_type alloc{alloc_}; + +- const std::size_t aligned_size = size / sizeof(std::max_align_t) +- + (size % sizeof(std::max_align_t) > 0 ? 1 : 0); ++ const std::size_t aligned_size = size / sizeof(coroutine_align_t) ++ + (size % sizeof(coroutine_align_t) > 0 ? 1 : 0); + +- const std::size_t alloc_size = sizeof(AllocatorType) / sizeof(std::max_align_t) +- + (sizeof(AllocatorType) % sizeof(std::max_align_t) > 0 ? 1 : 0); ++ const std::size_t alloc_size = sizeof(AllocatorType) / sizeof(coroutine_align_t) ++ + (sizeof(AllocatorType) % sizeof(coroutine_align_t) > 0 ? 1 : 0); + + const auto raw = std::allocator_traits::allocate(alloc, alloc_size + aligned_size); + new(raw + aligned_size) alloc_type(std::move(alloc)); +@@ -418,14 +418,14 @@ void *allocate_coroutine(const std::size_t size, AllocatorType alloc_) + template + void deallocate_coroutine(void *raw_, const std::size_t size) + { +- using alloc_type = typename std::allocator_traits::template rebind_alloc; +- const auto raw = static_cast(raw_); ++ using alloc_type = typename std::allocator_traits::template rebind_alloc; ++ const auto raw = static_cast(raw_); + +- const std::size_t aligned_size = size / sizeof(std::max_align_t) +- + (size % sizeof(std::max_align_t) > 0 ? 1 : 0); ++ const std::size_t aligned_size = size / sizeof(coroutine_align_t) ++ + (size % sizeof(coroutine_align_t) > 0 ? 1 : 0); + +- const std::size_t alloc_size = sizeof(AllocatorType) / sizeof(std::max_align_t) +- + (sizeof(AllocatorType) % sizeof(std::max_align_t) > 0 ? 1 : 0); ++ const std::size_t alloc_size = sizeof(AllocatorType) / sizeof(coroutine_align_t) ++ + (sizeof(AllocatorType) % sizeof(coroutine_align_t) > 0 ? 1 : 0); + + auto alloc_p = reinterpret_cast(raw + aligned_size); + auto alloc = std::move(*alloc_p); +@@ -439,20 +439,20 @@ void deallocate_coroutine(void *raw_, const std::size_t size) + template + void *allocate_coroutine(const std::size_t size, AllocatorType alloc_) + { +- using alloc_type = typename std::allocator_traits::template rebind_alloc; ++ using alloc_type = typename std::allocator_traits::template rebind_alloc; + alloc_type alloc{alloc_}; + +- const std::size_t aligned_size = size / sizeof(std::max_align_t) +- + (size % sizeof(std::max_align_t) > 0 ? 1 : 0); ++ const std::size_t aligned_size = size / sizeof(coroutine_align_t) ++ + (size % sizeof(coroutine_align_t) > 0 ? 1 : 0); + +- const std::size_t alloc_size = sizeof(AllocatorType) / sizeof(std::max_align_t) +- + (sizeof(AllocatorType) % sizeof(std::max_align_t) > 0 ? 1 : 0); ++ const std::size_t alloc_size = sizeof(AllocatorType) / sizeof(coroutine_align_t) ++ + (sizeof(AllocatorType) % sizeof(coroutine_align_t) > 0 ? 1 : 0); + +- const std::size_t size_size = sizeof(std::size_t) / sizeof(std::max_align_t) +- + (sizeof(std::size_t) % sizeof(std::max_align_t) > 0 ? 1 : 0); ++ const std::size_t size_size = sizeof(std::size_t) / sizeof(coroutine_align_t) ++ + (sizeof(std::size_t) % sizeof(coroutine_align_t) > 0 ? 1 : 0); + + +- static_assert(alignof(std::max_align_t) >= sizeof(std::size_t)); ++ static_assert(alignof(coroutine_align_t) >= sizeof(std::size_t)); + const auto raw = std::allocator_traits::allocate(alloc, alloc_size + aligned_size + size_size); + + new(raw) alloc_type(std::move(alloc)); +@@ -464,14 +464,14 @@ void *allocate_coroutine(const std::size_t size, AllocatorType alloc_) + template + void deallocate_coroutine(void *raw_) + { +- using alloc_type = typename std::allocator_traits::template rebind_alloc; +- const auto raw = static_cast(raw_); ++ using alloc_type = typename std::allocator_traits::template rebind_alloc; ++ const auto raw = static_cast(raw_); + +- const std::size_t size_size = sizeof(std::size_t) / sizeof(std::max_align_t) +- + (sizeof(std::size_t) % sizeof(std::max_align_t) > 0 ? 1 : 0); ++ const std::size_t size_size = sizeof(std::size_t) / sizeof(coroutine_align_t) ++ + (sizeof(std::size_t) % sizeof(coroutine_align_t) > 0 ? 1 : 0); + const std::size_t aligned_size = *reinterpret_cast(raw - size_size); +- const std::size_t alloc_size = sizeof(AllocatorType) / sizeof(std::max_align_t) +- + (sizeof(AllocatorType) % sizeof(std::max_align_t) > 0 ? 1 : 0); ++ const std::size_t alloc_size = sizeof(AllocatorType) / sizeof(coroutine_align_t) ++ + (sizeof(AllocatorType) % sizeof(coroutine_align_t) > 0 ? 1 : 0); + + auto alloc_p = reinterpret_cast(raw - alloc_size - size_size); + auto alloc = std::move(*alloc_p); diff --git a/tools/ci/matrix.py b/tools/ci/matrix.py index 30351219..aba55d5f 100755 --- a/tools/ci/matrix.py +++ b/tools/ci/matrix.py @@ -194,14 +194,15 @@ # The packages an own lane needs from the runner's apt, by (library, lane, target): an own lane # runs on its runner, never in the container, so they come with its entry ("apt"), which the -# own-lanes job installs on Linux. crypto's constant-time lane runs its native programs under -# Valgrind's memcheck (valgrind, with valgrind/memcheck.h) and under MemorySanitizer, whose -# runtime and sanitizer/ headers are libclang-rt-18-dev's, and its driver reads -# MemorySanitizer's frames with llvm-symbolizer-18, which llvm-18 installs; on wasip2 it runs -# dudect alone, which needs none. The lint, which analyses those programs natively, installs -# every package of the table (lint-packages). +# own-lanes job installs on Linux. crypto's and secure's constant-time lanes run their native +# programs under Valgrind's memcheck (valgrind, with valgrind/memcheck.h) and under +# MemorySanitizer, whose runtime and sanitizer/ headers are libclang-rt-18-dev's, and their +# drivers read MemorySanitizer's frames with llvm-symbolizer-18, which llvm-18 installs; on +# wasip2 crypto's runs dudect alone, which needs none. The lint, which analyses those programs +# natively, installs every package of the table (lint-packages). OWN_LANE_PACKAGES: dict[tuple[str, str, str], tuple[str, ...]] = { - ('crypto', 'constant-time', 'native'): ('valgrind', 'llvm-18', 'libclang-rt-18-dev')} + ('crypto', 'constant-time', 'native'): ('valgrind', 'llvm-18', 'libclang-rt-18-dev'), + ('secure', 'constant-time', 'native'): ('valgrind', 'llvm-18', 'libclang-rt-18-dev')} # MSVC's lanes build 64-bit programs, embed their manifest with the linker and abbreviate b2's # paths against Windows's MAX_PATH, as xstate-cpp's green Windows jobs did. b2 abbreviates each diff --git a/tools/ci/matrix_test.py b/tools/ci/matrix_test.py index 03c7ece8..800ac73e 100755 --- a/tools/ci/matrix_test.py +++ b/tools/ci/matrix_test.py @@ -1335,13 +1335,15 @@ def test_a_browser_lane_has_the_pinned_chrome(root): def test_an_own_lane_installs_its_packages(root): # An own lane runs on its runner, never in the container, so the packages it needs come with - # its entry, by library, lane and target: crypto's constant-time lane natively has Valgrind, - # llvm-18 (llvm-symbolizer-18, which reads MemorySanitizer's frames) and libclang-rt-18-dev - # (clang-18's MemorySanitizer runtime and its sanitizer/ headers); on wasip2, where it runs - # dudect alone, none; every other own lane none. The own-lanes job installs them with apt on - # Linux, only where the list is not empty, before the lane runs. + # its entry, by library, lane and target: crypto's and secure's constant-time lanes natively + # have Valgrind, llvm-18 (llvm-symbolizer-18, which reads MemorySanitizer's frames) and + # libclang-rt-18-dev (clang-18's MemorySanitizer runtime and its sanitizer/ headers); + # crypto's on wasip2, where it runs dudect alone, none; every other own lane none. The + # own-lanes job installs them with apt on Linux, only where the list is not empty, before the + # lane runs. packages = ('valgrind', 'llvm-18', 'libclang-rt-18-dev') - assert matrix.OWN_LANE_PACKAGES == {('crypto', 'constant-time', 'native'): packages} + assert matrix.OWN_LANE_PACKAGES == {('crypto', 'constant-time', 'native'): packages, + ('secure', 'constant-time', 'native'): packages} boost_only(root) oracle_library(root, 'beta') harness.add_library(root, 'crypto', @@ -1350,9 +1352,16 @@ def test_an_own_lane_installs_its_packages(root): 'webcpp.run plain : plain.cpp ;\n' 'webcpp.lane constant-time : plain : native wasip2 ;\n', {'plain.cpp': 'int main() {}\n'}) + harness.add_library(root, 'secure', + 'import webcpp ;\n' + 'webcpp.targets native ;\n' + 'webcpp.run plain : plain.cpp ;\n' + 'webcpp.lane constant-time : plain : native ;\n', + {'plain.cpp': 'int main() {}\n'}) assert {entry.get('id', entry['lane']): entry['apt'] for entry in own_lanes(root)} == { 'oracle': [], 'native.crypto.constant-time': list(packages), - 'wasip2.crypto.constant-time': []}, own_lanes(root) + 'wasip2.crypto.constant-time': [], 'native.secure.constant-time': list(packages)}, \ + own_lanes(root) steps = job_steps(workflow_jobs()['own-lanes']) installs = [step for step in steps if 'matrix.apt' in step] assert len(installs) == 1, installs @@ -1366,7 +1375,8 @@ def test_an_own_lane_installs_its_packages(root): def test_the_lint_installs_the_own_lanes_packages(root): # The lint analyses every own lane's programs, natively with clang-18 on Linux, so it needs # their headers: lint-packages prints every package of OWN_LANE_PACKAGES once, sorted, the - # one source, and the lint job installs them before the lint runs. + # one source (crypto's and secure's constant-time lanes list the same three), and the lint + # job installs them before the lint runs. result = run(root, 'lint-packages') assert result.returncode == 0, (result.returncode, result.stderr) assert result.stdout == 'libclang-rt-18-dev llvm-18 valgrind\n', result.stdout diff --git a/tools/hash/doc_tables.py b/tools/hash/doc_tables.py index 969c9ec6..ae7ab734 100644 --- a/tools/hash/doc_tables.py +++ b/tools/hash/doc_tables.py @@ -756,8 +756,8 @@ def llms_txt(data: Data) -> str: 'examples, never as this library\'s API.', '', 'Timing: every MAC, key derivation and password hash, and BLAKE2b\'s and BLAKE3\'s ' 'keyed modes, set DIT (data-independent timing) around each call on 64-bit ARM under ' - 'Apple\'s systems and Linux where the CPU has FEAT_DIT, on every synchronous backend, ' - 'and leave the thread\'s DIT as they found it; ' + 'Apple\'s systems, Linux and Windows where the CPU has FEAT_DIT, on every synchronous ' + 'backend, and leave the thread\'s DIT as they found it; ' 'unkeyed digests and Boost.Hash2\'s hmac by alias do not, so an HMAC with DIT is ' f'mac>. [Section]({page}#hash-backends-dit)', '', f'- [The guide]({page}): every chapter, example and table', @@ -841,17 +841,21 @@ def dit_section(data: Data) -> list[str]: f'({link("Apple, enable DIT for constant-time cryptographic operations", APPLE_DIT)}). ' 'None of the libraries hash calls sets it, so hash does: every function that computes ' 'on a key, a password or a key derivation\'s secret input runs its whole body inside ' - '`detail::timing_guard`, on every synchronous backend, which on 64-bit ARM under ' - 'macOS, iOS, Linux and Android, where the CPU has FEAT_DIT (`hw.optional.arm.FEAT_DIT` ' - 'on Apple\'s systems, `HWCAP_DIT` on Linux), sets DIT for the call and returns with ' + '`webcpp::secure::timing_guard`, webcpp::secure\'s guard, on every synchronous backend, ' + 'which on 64-bit ARM under macOS, iOS, Linux, Android and Windows, where the CPU has ' + 'FEAT_DIT (`hw.optional.arm.FEAT_DIT` on Apple\'s systems, `HWCAP_DIT` on Linux, one ' + 'read of the register under structured exception handling on Windows), sets DIT for the ' + 'call and returns with ' 'the thread\'s DIT as it found it: clear when it was clear, set when the program set ' 'it itself (Apple\'s `timingsafe_enable_if_supported`) or an outer call did. An error ' - 'and an exception leave it as found too, and DIT is a thread\'s own state, so a call ' - 'never changes another thread\'s. A program does nothing. Elsewhere the guard executes ' + 'leaves it as found too, and so does an exception, while it unwinds the call. After the ' + 'catch, Windows on ARM64 clears DIT when it resumes the thread: a program there that set ' + 'DIT itself and catches an exception from a call sets it again after the catch ' + '(webcpp::secure\'s guide, "Exceptions" of its guard). DIT is a thread\'s own state, so ' + 'a call never changes another thread\'s. Otherwise a program does nothing. Elsewhere ' + 'the guard executes ' 'no instruction: on x86 the counterpart, DOITM, is a register only the kernel writes; ' - 'on WebAssembly the engine decides; on Windows on ARM64 no documented way to ask ' - 'whether the CPU has FEAT_DIT was found, and DIT\'s instructions trap on a CPU without ' - 'it.', '', + 'on WebAssembly the engine decides.', '', 'The functions that set DIT, on every synchronous backend of their cells:', ''] for chapter, names in keyed.items(): lines.append(f'* {KEYED_CHAPTERS[chapter]}: {listed(names)}.') @@ -890,10 +894,10 @@ def dit_section(data: Data) -> list[str]: 'otherwise than it found it, from a thread with DIT clear and from one that set it; it ' 'checks that the unkeyed functions enter none. `test/timing_during_test.cpp` reads DIT ' 'while HKDF, PBKDF2 and `mac` compute, through a hash that records it at each update, ' - 'on the calling thread and on an `async_pbkdf2` pool\'s. The guard ' - 'is hash\'s own copy of ' - 'webcpp::crypto\'s, which depends on hash: a change to one is a change to the other, and ' - 'crypto\'s test `timing_hash_interop_test` runs both nested, in either order.', ''] + 'on the calling thread and on an `async_pbkdf2` pool\'s. The guard is secure\'s, shared ' + 'with webcpp::crypto and webcpp::codecs: secure\'s `timing_guard_nesting_test` nests ' + 'guards as two libraries do, and crypto\'s `timing_nested_hash_test` runs a keyed call ' + 'of hash inside a guarded call of crypto.', ''] if (data.library / 'doc' / 'performance.adoc').is_file(): lines += ['What the guard adds to a call, measured from a release build, is in ' '<>.', ''] diff --git a/tools/test/cobalt_ssl_test.py b/tools/test/cobalt_ssl_test.py index 0788ad38..fb2091dc 100644 --- a/tools/test/cobalt_ssl_test.py +++ b/tools/test/cobalt_ssl_test.py @@ -66,7 +66,8 @@ def test_changed_ssl_maintainer_input_is_refused(root: Path) -> None: ssl_source.write_text(ssl_source.read_text() + '\n// Different upstream input.\n') result = subprocess.run( [sys.executable, str(harness.ROOT / 'libs/cobalt/upstream/sync.py'), - '--boost-include', str(harness.boost_include()), '--boost-source', str(source), '--check'], + '--boost-include', str(harness.released_cobalt_headers(root / 'released Boost')), + '--boost-source', str(source), '--check'], text=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, timeout=60) harness.expect(result, False, 'upstream file differs from pinned Cobalt 1.92: libs/cobalt/src/io/ssl.cpp') diff --git a/tools/test/cobalt_wasip3_test.py b/tools/test/cobalt_wasip3_test.py index 70a7c695..ec69cc7e 100644 --- a/tools/test/cobalt_wasip3_test.py +++ b/tools/test/cobalt_wasip3_test.py @@ -54,7 +54,8 @@ def test_modified_maintainer_input_is_refused(root: Path) -> None: endpoint.write_text(endpoint.read_text() + '\n// Different upstream input.\n') result = subprocess.run( [sys.executable, str(harness.ROOT / 'libs/cobalt/upstream/sync.py'), - '--boost-include', str(harness.boost_include()), '--boost-source', str(source), '--check'], + '--boost-include', str(harness.released_cobalt_headers(root / 'released Boost')), + '--boost-source', str(source), '--check'], text=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, timeout=60) harness.expect(result, False, 'upstream file differs from pinned Cobalt 1.92: libs/cobalt/src/io/endpoint.cpp') diff --git a/tools/test/crypto_jamfiles_test.py b/tools/test/crypto_jamfiles_test.py index 3f0e7872..6a233508 100644 --- a/tools/test/crypto_jamfiles_test.py +++ b/tools/test/crypto_jamfiles_test.py @@ -30,7 +30,8 @@ def main(argv: list[str]) -> int: - return user_jamfiles.main('crypto_jamfiles', CASES, ('config', 'crypto', 'hash'), NOT_YET, argv) + return user_jamfiles.main('crypto_jamfiles', CASES, ('config', 'secure', 'crypto', 'hash'), + NOT_YET, argv) if __name__ == '__main__': diff --git a/tools/test/fixtures/crypto_jamfiles/both_bearssl_named/app.cpp b/tools/test/fixtures/crypto_jamfiles/both_bearssl_named/app.cpp index b9f9955a..3495cf9a 100644 --- a/tools/test/fixtures/crypto_jamfiles/both_bearssl_named/app.cpp +++ b/tools/test/fixtures/crypto_jamfiles/both_bearssl_named/app.cpp @@ -12,7 +12,7 @@ #include #include #include -#include +#include #include #include @@ -41,7 +41,7 @@ int main() { } auto const tag = aead->seal(nonce, {}, data); bool const sealed = - tag && data == cipher && webcpp::crypto::constant_time_equal(*tag, expected_tag); + tag && data == cipher && webcpp::secure::constant_time_equal(*tag, expected_tag); bool const opened = aead->open(nonce, {}, data, expected_tag) && data == std::array{}; auto const name = aead_type::backend_type::name; diff --git a/tools/test/fixtures/crypto_jamfiles/box_xchacha20poly1305_default/app.cpp b/tools/test/fixtures/crypto_jamfiles/box_xchacha20poly1305_default/app.cpp index 5c8d67f1..6a09d835 100644 --- a/tools/test/fixtures/crypto_jamfiles/box_xchacha20poly1305_default/app.cpp +++ b/tools/test/fixtures/crypto_jamfiles/box_xchacha20poly1305_default/app.cpp @@ -9,9 +9,9 @@ // does not print and an independent implementation computed, opens it with Bob's keys, each an // X25519 key pair and the peer's public key, and prints the backend that ran. The keys and nonce // are NaCl's test's. -#include #include #include +#include #include #include @@ -71,7 +71,7 @@ int main() { auto bob = box::from_keys(*bob_pair, *alice_key); if (alice && bob) { auto const sealed = alice->seal(nonce, data); - ok = sealed && webcpp::crypto::constant_time_equal(*sealed, expected_tag) && + ok = sealed && webcpp::secure::constant_time_equal(*sealed, expected_tag) && std::equal(expected_head.begin(), expected_head.end(), data.begin()) && bob->open(nonce, data, *sealed) && data == plaintext; } diff --git a/tools/test/fixtures/crypto_jamfiles/box_xsalsa20poly1305_default/app.cpp b/tools/test/fixtures/crypto_jamfiles/box_xsalsa20poly1305_default/app.cpp index 7401ecd4..c3624775 100644 --- a/tools/test/fixtures/crypto_jamfiles/box_xsalsa20poly1305_default/app.cpp +++ b/tools/test/fixtures/crypto_jamfiles/box_xsalsa20poly1305_default/app.cpp @@ -9,9 +9,9 @@ // keys (box2.c), each an X25519 key pair and the peer's public key, and prints the backend that // ran. The keys and nonce are the test's: a real program draws its key pair with generate(), and // a nonce at random for every message. -#include #include #include +#include #include #include @@ -71,7 +71,7 @@ int main() { auto bob = box::from_keys(*bob_pair, *alice_key); if (alice && bob) { auto const sealed = alice->seal(nonce, data); - ok = sealed && webcpp::crypto::constant_time_equal(*sealed, expected_tag) && + ok = sealed && webcpp::secure::constant_time_equal(*sealed, expected_tag) && std::equal(expected_head.begin(), expected_head.end(), data.begin()) && bob->open(nonce, data, *sealed) && data == plaintext; } diff --git a/tools/test/fixtures/crypto_jamfiles/chacha20_poly1305_default/app.cpp b/tools/test/fixtures/crypto_jamfiles/chacha20_poly1305_default/app.cpp index f7bae48b..e7ac0b73 100644 --- a/tools/test/fixtures/crypto_jamfiles/chacha20_poly1305_default/app.cpp +++ b/tools/test/fixtures/crypto_jamfiles/chacha20_poly1305_default/app.cpp @@ -9,7 +9,7 @@ // that ran. The key and nonce are the RFC's: a real program draws its key from random_device and // never reuses a nonce under it. #include -#include +#include #include #include @@ -47,7 +47,7 @@ int main() { bool ok = false; if (sealer) { auto const tag = sealer->seal(nonce, associated_data, data); - ok = tag && webcpp::crypto::constant_time_equal(*tag, expected_tag) && + ok = tag && webcpp::secure::constant_time_equal(*tag, expected_tag) && std::equal(expected_head.begin(), expected_head.end(), data.begin()) && sealer->open(nonce, associated_data, data, expected_tag) && data == plaintext; } diff --git a/tools/test/fixtures/crypto_jamfiles/chacha20_poly1305_original_default/app.cpp b/tools/test/fixtures/crypto_jamfiles/chacha20_poly1305_original_default/app.cpp index 20498eb9..309e4742 100644 --- a/tools/test/fixtures/crypto_jamfiles/chacha20_poly1305_original_default/app.cpp +++ b/tools/test/fixtures/crypto_jamfiles/chacha20_poly1305_original_default/app.cpp @@ -9,7 +9,7 @@ // ciphertext against libsodium's, opens it again, and prints the backend that ran. The key and // nonce are the test's: a real program draws its key from random_device and numbers its nonces. #include -#include +#include #include #include @@ -43,7 +43,7 @@ int main() { bool ok = false; if (sealer) { auto const tag = sealer->seal(nonce, associated_data, data); - ok = tag && webcpp::crypto::constant_time_equal(*tag, expected_tag) && + ok = tag && webcpp::secure::constant_time_equal(*tag, expected_tag) && std::equal(expected_head.begin(), expected_head.end(), data.begin()) && sealer->open(nonce, associated_data, data, expected_tag) && data == plaintext; } diff --git a/tools/test/fixtures/crypto_jamfiles/ed25519_default/app.cpp b/tools/test/fixtures/crypto_jamfiles/ed25519_default/app.cpp index 4a37c2e4..951f29c8 100644 --- a/tools/test/fixtures/crypto_jamfiles/ed25519_default/app.cpp +++ b/tools/test/fixtures/crypto_jamfiles/ed25519_default/app.cpp @@ -7,9 +7,9 @@ // Signs RFC 8032's first Ed25519 test (section 7.1, TEST 1: the empty message) with a key pair // made from its seed on the default backend, checks the signature against the RFC's and verifies // it, and prints the backend that ran. The seed is the RFC's: a real program draws its own. -#include #include #include +#include #include #include @@ -18,6 +18,7 @@ int main() { namespace crypto = webcpp::crypto; + namespace secure = webcpp::secure; namespace ed25519 = webcpp::crypto::curves::ed25519; std::array const seed{ 0x9d, 0x61, 0xb1, 0x9d, 0xef, 0xfd, 0x5a, 0x60, 0xba, 0x84, 0x4a, @@ -37,7 +38,7 @@ int main() { if (key) { auto const signature = key->sign(crypto::eddsa, message); auto const public_key = key->public_key(); - ok = signature && public_key && crypto::constant_time_equal(signature->bytes(), expected) && + ok = signature && public_key && secure::constant_time_equal(signature->bytes(), expected) && crypto::verify(crypto::eddsa, *signature, message, *public_key).has_value(); } auto const name = ed25519::keypair::backend_type::name; diff --git a/tools/test/fixtures/crypto_jamfiles/encrypt_and_sign/app.cpp b/tools/test/fixtures/crypto_jamfiles/encrypt_and_sign/app.cpp index d1d7833f..41f84cf1 100644 --- a/tools/test/fixtures/crypto_jamfiles/encrypt_and_sign/app.cpp +++ b/tools/test/fixtures/crypto_jamfiles/encrypt_and_sign/app.cpp @@ -8,9 +8,9 @@ // NIST test vector (GCM test case 14), opens it again, then signs a message with BIP340 through // libsecp256k1, verifies the signature, and refuses a changed message. #include -#include #include #include +#include #include #include @@ -34,7 +34,7 @@ int main() { } auto const tag = aead->seal(nonce, {}, data); bool const sealed = - tag && data == cipher && webcpp::crypto::constant_time_equal(*tag, expected_tag); + tag && data == cipher && webcpp::secure::constant_time_equal(*tag, expected_tag); bool const opened = aead->open(nonce, {}, data, expected_tag) && data == std::array{}; auto const name = webcpp::crypto::ciphers::aes256_gcm::backend_type::name; diff --git a/tools/test/fixtures/crypto_jamfiles/gcm_default/app.cpp b/tools/test/fixtures/crypto_jamfiles/gcm_default/app.cpp index 14b60607..803b61b3 100644 --- a/tools/test/fixtures/crypto_jamfiles/gcm_default/app.cpp +++ b/tools/test/fixtures/crypto_jamfiles/gcm_default/app.cpp @@ -9,7 +9,7 @@ // prints the backend that ran. The zero key and nonce are the test vector's: a real program draws // its key from random_device and never reuses a nonce under it. #include -#include +#include #include #include @@ -33,7 +33,7 @@ int main() { } auto const tag = aead->seal(nonce, {}, data); bool const sealed = - tag && data == cipher && webcpp::crypto::constant_time_equal(*tag, expected_tag); + tag && data == cipher && webcpp::secure::constant_time_equal(*tag, expected_tag); bool const opened = aead->open(nonce, {}, data, expected_tag) && data == std::array{}; auto const name = webcpp::crypto::ciphers::aes256_gcm::backend_type::name; diff --git a/tools/test/fixtures/crypto_jamfiles/kx_default/app.cpp b/tools/test/fixtures/crypto_jamfiles/kx_default/app.cpp index ddb46c5a..c2039580 100644 --- a/tools/test/fixtures/crypto_jamfiles/kx_default/app.cpp +++ b/tools/test/fixtures/crypto_jamfiles/kx_default/app.cpp @@ -8,8 +8,8 @@ // computes each side's session keys from the other's public key, checks the client's transmit // key against kx.exp's and the server's receive key, and prints the backend that ran. The seeds // are libsodium's test's: a real program draws its key pair with generate(). -#include #include +#include #include #include @@ -39,8 +39,8 @@ int main() { auto const client_keys = client->client_session_keys(*server_public); auto const server_keys = server->server_session_keys(*client_public); ok = client_keys && server_keys && - webcpp::crypto::constant_time_equal(client_keys->transmit.bytes(), expected) && - webcpp::crypto::constant_time_equal(server_keys->receive.bytes(), expected); + webcpp::secure::constant_time_equal(client_keys->transmit.bytes(), expected) && + webcpp::secure::constant_time_equal(server_keys->receive.bytes(), expected); } } auto const name = key_exchange::kx_keypair<>::backend_type::name; diff --git a/tools/test/fixtures/crypto_jamfiles/secp256k1_default/app.cpp b/tools/test/fixtures/crypto_jamfiles/secp256k1_default/app.cpp index ff96477d..477963b5 100644 --- a/tools/test/fixtures/crypto_jamfiles/secp256k1_default/app.cpp +++ b/tools/test/fixtures/crypto_jamfiles/secp256k1_default/app.cpp @@ -7,9 +7,9 @@ // Signs BIP 340's first test vector (secret key 3, a zero message and zero auxiliary data) with // a key pair on the default backend, checks the signature against the vector's and verifies it, // and prints the backend that ran. The secret key is the vector's: a real program draws its own. -#include #include #include +#include #include #include @@ -34,7 +34,7 @@ int main() { auto const signature = key->sign(webcpp::crypto::schnorr, message, aux); auto const public_key = key->public_key(); ok = signature && public_key && - webcpp::crypto::constant_time_equal(signature->bytes(), expected) && + webcpp::secure::constant_time_equal(signature->bytes(), expected) && webcpp::crypto::verify(webcpp::crypto::schnorr, *signature, message, *public_key); } auto const name = secp256k1::keypair::backend_type::name; diff --git a/tools/test/fixtures/crypto_jamfiles/secp256k1_ellswift_default/app.cpp b/tools/test/fixtures/crypto_jamfiles/secp256k1_ellswift_default/app.cpp index 028b6583..7f066ea6 100644 --- a/tools/test/fixtures/crypto_jamfiles/secp256k1_ellswift_default/app.cpp +++ b/tools/test/fixtures/crypto_jamfiles/secp256k1_ellswift_default/app.cpp @@ -8,9 +8,9 @@ // checks that each decodes to its key pair's public key and that both sides of BIP 324's // exchange agree, and prints the backend that ran. The secrets and the randomness are fixed: a // real program draws its own, and never prints a shared secret. -#include #include #include +#include #include #include @@ -28,6 +28,7 @@ std::array repeated(std::uint8_t value) { int main() { namespace crypto = webcpp::crypto; + namespace secure = webcpp::secure; namespace secp256k1 = webcpp::crypto::curves::secp256k1; auto const initiator = secp256k1::keypair::from_secret(repeated(0x11)); auto const responder = secp256k1::keypair::from_secret(repeated(0x22)); @@ -44,7 +45,7 @@ int main() { secp256k1::ellswift_party::initiator); auto const theirs = secp256k1::ellswift_xdh(*responder, *sent, *received, secp256k1::ellswift_party::responder); - ok = mine && theirs && crypto::constant_time_equal(mine->bytes(), theirs->bytes()); + ok = mine && theirs && secure::constant_time_equal(mine->bytes(), theirs->bytes()); } } auto const name = crypto::default_backend_t::name; diff --git a/tools/test/fixtures/crypto_jamfiles/secretbox_xchacha20poly1305_default/app.cpp b/tools/test/fixtures/crypto_jamfiles/secretbox_xchacha20poly1305_default/app.cpp index 9b7cd458..560281ec 100644 --- a/tools/test/fixtures/crypto_jamfiles/secretbox_xchacha20poly1305_default/app.cpp +++ b/tools/test/fixtures/crypto_jamfiles/secretbox_xchacha20poly1305_default/app.cpp @@ -8,8 +8,8 @@ // backend, checks the tag and the ciphertext against the test's, opens it again, and prints the // backend that ran. The key and nonce are the test's: a real program draws its key from // random_device, and a 24-byte nonce drawn at random for every message is safe. -#include #include +#include #include #include @@ -48,7 +48,7 @@ int main() { bool ok = false; if (sealer) { auto const tag = sealer->seal(nonce, data); - ok = tag && webcpp::crypto::constant_time_equal(*tag, expected_tag) && data == expected && + ok = tag && webcpp::secure::constant_time_equal(*tag, expected_tag) && data == expected && sealer->open(nonce, data, expected_tag) && data == plaintext; } auto const name = secretbox::backend_type::name; diff --git a/tools/test/fixtures/crypto_jamfiles/secretbox_xsalsa20poly1305_default/app.cpp b/tools/test/fixtures/crypto_jamfiles/secretbox_xsalsa20poly1305_default/app.cpp index f145a7e5..8f4b05f9 100644 --- a/tools/test/fixtures/crypto_jamfiles/secretbox_xsalsa20poly1305_default/app.cpp +++ b/tools/test/fixtures/crypto_jamfiles/secretbox_xsalsa20poly1305_default/app.cpp @@ -8,8 +8,8 @@ // the tag and the ciphertext's first bytes against secretbox.exp, opens it again, and prints the // backend that ran. The key and nonce are the test's: a real program draws its key from // random_device, and a 24-byte nonce drawn at random for every message is safe. -#include #include +#include #include #include @@ -53,7 +53,7 @@ int main() { bool ok = false; if (sealer) { auto const tag = sealer->seal(nonce, data); - ok = tag && webcpp::crypto::constant_time_equal(*tag, expected_tag) && + ok = tag && webcpp::secure::constant_time_equal(*tag, expected_tag) && std::equal(expected_head.begin(), expected_head.end(), data.begin()) && sealer->open(nonce, data, expected_tag) && data == plaintext; } diff --git a/tools/test/fixtures/crypto_jamfiles/server/app.cpp b/tools/test/fixtures/crypto_jamfiles/server/app.cpp index 14b60607..803b61b3 100644 --- a/tools/test/fixtures/crypto_jamfiles/server/app.cpp +++ b/tools/test/fixtures/crypto_jamfiles/server/app.cpp @@ -9,7 +9,7 @@ // prints the backend that ran. The zero key and nonce are the test vector's: a real program draws // its key from random_device and never reuses a nonce under it. #include -#include +#include #include #include @@ -33,7 +33,7 @@ int main() { } auto const tag = aead->seal(nonce, {}, data); bool const sealed = - tag && data == cipher && webcpp::crypto::constant_time_equal(*tag, expected_tag); + tag && data == cipher && webcpp::secure::constant_time_equal(*tag, expected_tag); bool const opened = aead->open(nonce, {}, data, expected_tag) && data == std::array{}; auto const name = webcpp::crypto::ciphers::aes256_gcm::backend_type::name; diff --git a/tools/test/fixtures/crypto_jamfiles/web/app.cpp b/tools/test/fixtures/crypto_jamfiles/web/app.cpp index 14b60607..803b61b3 100644 --- a/tools/test/fixtures/crypto_jamfiles/web/app.cpp +++ b/tools/test/fixtures/crypto_jamfiles/web/app.cpp @@ -9,7 +9,7 @@ // prints the backend that ran. The zero key and nonce are the test vector's: a real program draws // its key from random_device and never reuses a nonce under it. #include -#include +#include #include #include @@ -33,7 +33,7 @@ int main() { } auto const tag = aead->seal(nonce, {}, data); bool const sealed = - tag && data == cipher && webcpp::crypto::constant_time_equal(*tag, expected_tag); + tag && data == cipher && webcpp::secure::constant_time_equal(*tag, expected_tag); bool const opened = aead->open(nonce, {}, data, expected_tag) && data == std::array{}; auto const name = webcpp::crypto::ciphers::aes256_gcm::backend_type::name; diff --git a/tools/test/fixtures/crypto_jamfiles/x25519_default/app.cpp b/tools/test/fixtures/crypto_jamfiles/x25519_default/app.cpp index 4bf4fa95..f504c09e 100644 --- a/tools/test/fixtures/crypto_jamfiles/x25519_default/app.cpp +++ b/tools/test/fixtures/crypto_jamfiles/x25519_default/app.cpp @@ -8,8 +8,8 @@ // and Bob's public key on the default backend, checks it against the RFC's, and prints the // backend that ran. The keys are the RFC's: a real program draws its own, and never prints a // shared secret. -#include #include +#include #include #include @@ -39,7 +39,7 @@ int main() { return 1; } auto const shared = alice->agree(*bob); - bool const ok = shared && webcpp::crypto::constant_time_equal(shared->bytes(), expected); + bool const ok = shared && webcpp::secure::constant_time_equal(shared->bytes(), expected); auto const name = x25519::keypair::backend_type::name; std::printf("x25519 %s backend=%.*s\n", ok ? "ok" : "FAILED", static_cast(name.size()), name.data()); diff --git a/tools/test/fixtures/crypto_jamfiles/xchacha20_poly1305_default/app.cpp b/tools/test/fixtures/crypto_jamfiles/xchacha20_poly1305_default/app.cpp index 55f543f3..01001ffd 100644 --- a/tools/test/fixtures/crypto_jamfiles/xchacha20_poly1305_default/app.cpp +++ b/tools/test/fixtures/crypto_jamfiles/xchacha20_poly1305_default/app.cpp @@ -9,7 +9,7 @@ // backend that ran. The key and nonce are the draft's: a real program draws its key from // random_device; a 24-byte nonce drawn at random is safe. #include -#include +#include #include #include @@ -50,7 +50,7 @@ int main() { bool ok = false; if (sealer) { auto const tag = sealer->seal(nonce, associated_data, data); - ok = tag && webcpp::crypto::constant_time_equal(*tag, expected_tag) && + ok = tag && webcpp::secure::constant_time_equal(*tag, expected_tag) && std::equal(expected_head.begin(), expected_head.end(), data.begin()) && sealer->open(nonce, associated_data, data, expected_tag) && data == plaintext; } diff --git a/tools/test/fixtures/crypto_jamfiles/secret_of_no_bytes_on_emscripten/Jamfile b/tools/test/fixtures/secure_jamfiles/erase_secret_const_range_on_emscripten/Jamfile similarity index 83% rename from tools/test/fixtures/crypto_jamfiles/secret_of_no_bytes_on_emscripten/Jamfile rename to tools/test/fixtures/secure_jamfiles/erase_secret_const_range_on_emscripten/Jamfile index 4b12ef4a..d6727101 100644 --- a/tools/test/fixtures/crypto_jamfiles/secret_of_no_bytes_on_emscripten/Jamfile +++ b/tools/test/fixtures/secure_jamfiles/erase_secret_const_range_on_emscripten/Jamfile @@ -5,5 +5,5 @@ # https://www.boost.org/LICENSE_1_0.txt) # tag::jamfile[] -exe app : app.cpp /webcpp/crypto//crypto ; +exe app : app.cpp /webcpp/secure//secure ; # end::jamfile[] diff --git a/tools/test/fixtures/secure_jamfiles/erase_secret_const_range_on_emscripten/app.cpp b/tools/test/fixtures/secure_jamfiles/erase_secret_const_range_on_emscripten/app.cpp new file mode 100644 index 00000000..5bcec29b --- /dev/null +++ b/tools/test/fixtures/secure_jamfiles/erase_secret_const_range_on_emscripten/app.cpp @@ -0,0 +1,25 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// erase_secret writes the buffer it erases: a program that hands it a const string stops at the +// call, with a message that names the ranges it takes, and with that error alone. + +#include + +#include + +namespace { + +void forget(std::string const& password) { + webcpp::secure::erase_secret(password); +} + +} // namespace + +int main() { + forget("correct horse battery staple"); + return 0; +} diff --git a/tools/test/fixtures/secure_jamfiles/erase_secret_const_range_on_emscripten/erase_secret_const_range_on_emscripten.outcome b/tools/test/fixtures/secure_jamfiles/erase_secret_const_range_on_emscripten/erase_secret_const_range_on_emscripten.outcome new file mode 100644 index 00000000..769ecee5 --- /dev/null +++ b/tools/test/fixtures/secure_jamfiles/erase_secret_const_range_on_emscripten/erase_secret_const_range_on_emscripten.outcome @@ -0,0 +1,16 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +# The compiler's line of the refusal starts with the header's path on the machine, so the message is +# a contains: line. wasip2 and wasip3 have the same message in a compile-diagnostic +# (test/messages/erase_secret_const_range); compile-diagnostic is clang's and skips Emscripten, so this +# fixture is the Emscripten one. +[all] +targets: emscripten +build: fails +# tag::messages[] +contains: webcpp::secure: erase_secret zeroes a buffer the program may write, of trivially copyable elements: a std::vector, a std::string, a std::array, a std::span; this range's elements are const or not trivially copyable. +# end::messages[] diff --git a/tools/test/fixtures/secure_jamfiles/program/Jamfile b/tools/test/fixtures/secure_jamfiles/program/Jamfile new file mode 100644 index 00000000..d6727101 --- /dev/null +++ b/tools/test/fixtures/secure_jamfiles/program/Jamfile @@ -0,0 +1,9 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +# tag::jamfile[] +exe app : app.cpp /webcpp/secure//secure ; +# end::jamfile[] diff --git a/tools/test/fixtures/secure_jamfiles/program/app.cpp b/tools/test/fixtures/secure_jamfiles/program/app.cpp new file mode 100644 index 00000000..774e83cb --- /dev/null +++ b/tools/test/fixtures/secure_jamfiles/program/app.cpp @@ -0,0 +1,35 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// A program that names /webcpp/secure//secure alone: it holds a timing guard, compares two +// buffers in constant time and erases one of them. + +#include + +#include +#include +#include + +int main() { + namespace secure = webcpp::secure; + std::array first{}; + std::array second{}; + first.fill(0x5a); + second.fill(0x5a); + secure::timing_guard const guard; + if (secure::constant_time_equal(first, second)) { + std::printf("equal\n"); + } + secure::erase_secret(first); + bool erased = true; + for (std::uint8_t const byte : first) { + erased = erased && byte == 0; + } + if (erased && !secure::constant_time_equal(first, second)) { + std::printf("erased\n"); + } + return 0; +} diff --git a/tools/test/fixtures/secure_jamfiles/program/program.outcome b/tools/test/fixtures/secure_jamfiles/program/program.outcome new file mode 100644 index 00000000..748014c0 --- /dev/null +++ b/tools/test/fixtures/secure_jamfiles/program/program.outcome @@ -0,0 +1,14 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +# Spec scenario "A program that erases a buffer builds nothing": builds and runs on every +# target, and no library is compiled for secure. +[all] +targets: native wasip2 wasip3 emscripten +build: succeeds +run: app +equal +erased diff --git a/tools/test/fixtures/secure_jamfiles/program_no_exceptions/Jamfile b/tools/test/fixtures/secure_jamfiles/program_no_exceptions/Jamfile new file mode 100644 index 00000000..2dcb9018 --- /dev/null +++ b/tools/test/fixtures/secure_jamfiles/program_no_exceptions/Jamfile @@ -0,0 +1,8 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +# The same program with exceptions off: nothing in webcpp::secure needs them. +exe app : app.cpp /webcpp/secure//secure : off ; diff --git a/tools/test/fixtures/secure_jamfiles/program_no_exceptions/app.cpp b/tools/test/fixtures/secure_jamfiles/program_no_exceptions/app.cpp new file mode 100644 index 00000000..774e83cb --- /dev/null +++ b/tools/test/fixtures/secure_jamfiles/program_no_exceptions/app.cpp @@ -0,0 +1,35 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// A program that names /webcpp/secure//secure alone: it holds a timing guard, compares two +// buffers in constant time and erases one of them. + +#include + +#include +#include +#include + +int main() { + namespace secure = webcpp::secure; + std::array first{}; + std::array second{}; + first.fill(0x5a); + second.fill(0x5a); + secure::timing_guard const guard; + if (secure::constant_time_equal(first, second)) { + std::printf("equal\n"); + } + secure::erase_secret(first); + bool erased = true; + for (std::uint8_t const byte : first) { + erased = erased && byte == 0; + } + if (erased && !secure::constant_time_equal(first, second)) { + std::printf("erased\n"); + } + return 0; +} diff --git a/tools/test/fixtures/secure_jamfiles/program_no_exceptions/program_no_exceptions.outcome b/tools/test/fixtures/secure_jamfiles/program_no_exceptions/program_no_exceptions.outcome new file mode 100644 index 00000000..5a8dbf9c --- /dev/null +++ b/tools/test/fixtures/secure_jamfiles/program_no_exceptions/program_no_exceptions.outcome @@ -0,0 +1,14 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +# The program of the case program, with exceptions off. +[all] +targets: native wasip2 wasip3 emscripten +build: succeeds +same-as: program/app.cpp app.cpp +run: app +equal +erased diff --git a/tools/test/fixtures/secure_jamfiles/secret_of_no_bytes_on_emscripten/Jamfile b/tools/test/fixtures/secure_jamfiles/secret_of_no_bytes_on_emscripten/Jamfile new file mode 100644 index 00000000..d6727101 --- /dev/null +++ b/tools/test/fixtures/secure_jamfiles/secret_of_no_bytes_on_emscripten/Jamfile @@ -0,0 +1,9 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +# tag::jamfile[] +exe app : app.cpp /webcpp/secure//secure ; +# end::jamfile[] diff --git a/tools/test/fixtures/crypto_jamfiles/secret_of_no_bytes_on_emscripten/app.cpp b/tools/test/fixtures/secure_jamfiles/secret_of_no_bytes_on_emscripten/app.cpp similarity index 73% rename from tools/test/fixtures/crypto_jamfiles/secret_of_no_bytes_on_emscripten/app.cpp rename to tools/test/fixtures/secure_jamfiles/secret_of_no_bytes_on_emscripten/app.cpp index 6112fe31..51e595ca 100644 --- a/tools/test/fixtures/crypto_jamfiles/secret_of_no_bytes_on_emscripten/app.cpp +++ b/tools/test/fixtures/secure_jamfiles/secret_of_no_bytes_on_emscripten/app.cpp @@ -5,8 +5,9 @@ // https://www.boost.org/LICENSE_1_0.txt) // A program that names a secret of no bytes stops where it names it. -#include + +#include int main() { - return static_cast(webcpp::crypto::secret<0>::size_bytes); + return static_cast(webcpp::secure::secret<0>::size_bytes); } diff --git a/tools/test/fixtures/crypto_jamfiles/secret_of_no_bytes_on_emscripten/secret_of_no_bytes_on_emscripten.outcome b/tools/test/fixtures/secure_jamfiles/secret_of_no_bytes_on_emscripten/secret_of_no_bytes_on_emscripten.outcome similarity index 90% rename from tools/test/fixtures/crypto_jamfiles/secret_of_no_bytes_on_emscripten/secret_of_no_bytes_on_emscripten.outcome rename to tools/test/fixtures/secure_jamfiles/secret_of_no_bytes_on_emscripten/secret_of_no_bytes_on_emscripten.outcome index 7454a2fd..156d4b30 100644 --- a/tools/test/fixtures/crypto_jamfiles/secret_of_no_bytes_on_emscripten/secret_of_no_bytes_on_emscripten.outcome +++ b/tools/test/fixtures/secure_jamfiles/secret_of_no_bytes_on_emscripten/secret_of_no_bytes_on_emscripten.outcome @@ -12,5 +12,5 @@ targets: emscripten build: fails # tag::messages[] -contains: webcpp::crypto: a secret of no bytes holds nothing. +contains: webcpp::secure: a secret of no bytes holds nothing. # end::messages[] diff --git a/tools/test/harness.py b/tools/test/harness.py index 7ae9501b..8df11cfc 100644 --- a/tools/test/harness.py +++ b/tools/test/harness.py @@ -460,6 +460,27 @@ def boost_source() -> Path: return Path(found.group(1)) if found else (ROOT / '.local/boost-source').resolve() +def released_cobalt_headers(destination: Path) -> Path: + """destination, filled with Boost.Cobalt's headers of the configured Boost as its release + archive has them, the pinned inputs of libs/cobalt/upstream/sync.py: the CI's Boost carries + the patches of tools/ci/actions/boost/patches, and each one applied to these headers is taken + back out here. Returns destination, a directory for sync.py's --boost-include.""" + (destination / 'boost').mkdir(parents=True, exist_ok=True) + shutil.copyfile(boost_include() / 'boost/cobalt.hpp', destination / 'boost/cobalt.hpp') + # copyfile: Homebrew's headers are read-only, and a patch taken out rewrites a copy. + shutil.copytree(boost_include() / 'boost/cobalt', destination / 'boost/cobalt', + copy_function=shutil.copyfile) + environment = dict(os.environ, GIT_CEILING_DIRECTORIES=str(destination.parent)) + for patch in sorted((ROOT / 'tools/ci/actions/boost/patches').glob('*.patch')): + reverse = ('git', '-C', str(destination), 'apply', '--reverse', + '--include=boost/cobalt.hpp', '--include=boost/cobalt/*') + if subprocess.run((*reverse, '--check', str(patch)), env=environment, + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, + check=False).returncode == 0: + subprocess.run((*reverse, str(patch)), env=environment, check=True) + return destination + + # A line of a user-config.jam that configures gcc, and the version it names. USING_GCC = re.compile(r'^\s*using\s+gcc\s*(?::\s*([^\s:;]+))?', re.MULTILINE) diff --git a/tools/test/hash_jamfiles_test.py b/tools/test/hash_jamfiles_test.py index 69f316a6..067fe982 100644 --- a/tools/test/hash_jamfiles_test.py +++ b/tools/test/hash_jamfiles_test.py @@ -98,7 +98,8 @@ def message_faults(cases: list[Path]) -> list[str]: def main(argv: list[str]) -> int: - return user_jamfiles.main('hash_jamfiles', CASES, ('config', 'hash', 'crypto', 'asio'), NOT_YET, + return user_jamfiles.main('hash_jamfiles', CASES, + ('config', 'secure', 'hash', 'crypto', 'asio'), NOT_YET, argv, message_faults) diff --git a/tools/test/secure_collect_test.py b/tools/test/secure_collect_test.py new file mode 100644 index 00000000..ff936ed3 --- /dev/null +++ b/tools/test/secure_collect_test.py @@ -0,0 +1,266 @@ +#!/usr/bin/env python3 +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +"""Checks that libs/secure/bench/collect.py, which measures bench/timing and renders +doc/performance.adoc, builds its page only from release builds: a program whose build directory, +b2's bench///..., names another variant, or does not say, is refused before it +runs or anything is written; one at variant=release is measured, its figures stored with UTC's date +and the load averages and rendered, whether the data existed or not (an older measurement is +replaced); a program that fails, and a line or a data file that is not the form collect.py reads, +are refused with a message, not a traceback, before anything is written; `--render-only` refuses +data whose build is not variant=release, before it writes the page, and renders the committed data +as the committed page; and exactly one of `--timing` and `--render-only` is given. Run with the +names of some cases to run only those.""" + +from __future__ import annotations + +import datetime +import json +import subprocess +import sys +import tempfile +from collections.abc import Callable +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +COLLECT = ROOT / 'libs/secure/bench/collect.py' +DATA = ROOT / 'libs/secure/doc/measurements.json' +PAGE = ROOT / 'libs/secure/doc/performance.adoc' +# A stand-in's body that fails when run, after saying so. +FAILS = 'echo "the stand-in ran" >&2\nexit 3\n' + + +def run(*args: str | Path) -> subprocess.CompletedProcess[str]: + return subprocess.run([sys.executable, str(COLLECT), *map(str, args)], cwd=ROOT, + capture_output=True, text=True, check=False, timeout=120) + + +def program(scratch: Path, variant: str, body: str = FAILS) -> Path: + """A stand-in of bench/timing where b2 builds it at variant, which runs body (by default, it + fails).""" + path = (scratch / 'bin/libs/secure/bench/clang-darwin-21' / variant + / 'cxxstd-20-iso' / 'timing') + path.parent.mkdir(parents=True) + path.write_text('#!/bin/sh\n' + body) + path.chmod(0o755) + return path + + +def expect(done: subprocess.CompletedProcess[str], status: int, *texts: str) -> None: + if done.returncode != status: + raise AssertionError(f'exit {done.returncode}, not {status}\n{done.stdout}{done.stderr}') + for text in texts: + if text not in done.stderr: + raise AssertionError(f'{text!r} is not in the error:\n{done.stderr}') + + +GUARD = {'dit': True, 'clear': 12.345, 'set': 0.678, 'disengaged': -0.04, + 'clear_fastest': 11.25, 'clear_slowest': 19.75, 'set_fastest': 0.25, 'set_slowest': 1.75, + 'disengaged_fastest': -0.25, 'disengaged_slowest': 0.375, 'iterations': 10000000, + 'runs': 5, 'target': 'native', 'compiler': 'clang'} + + +def timing_program(scratch: Path, line: str = json.dumps(GUARD)) -> Path: + """A stand-in of bench/timing at variant=release whose --measure prints line.""" + return program(scratch, 'release', 'if [ "$1" = --measure ]; then ' + f"echo '{line}'; else exit 3; fi\n") + + +def test_a_program_not_built_at_variant_release_is_refused(scratch: Path) -> None: + data, page = scratch / 'data.json', scratch / 'page.adoc' + for variant in ('debug', 'profile'): + exe = program(scratch / variant, variant) + done = run('--timing', exe, '--data', data, '--page', page) + expect(done, 1, f'timing={exe} was built at variant={variant}', + 'only from release builds') + if 'the stand-in ran' in done.stderr or data.exists() or page.exists(): + raise AssertionError(f'{variant}: the program ran or a file was written') + stray = scratch / 'stray/timing' + stray.parent.mkdir() + stray.write_text('') + done = run('--timing', stray, '--data', data, '--page', page) + expect(done, 1, f'timing={stray}', 'bench//', 'only from release builds') + + +def test_the_committed_data_is_not_replaced_by_a_refused_program(scratch: Path) -> None: + data, page = scratch / 'data.json', scratch / 'page.adoc' + data.write_text(DATA.read_text()) + exe = program(scratch, 'debug') + expect(run('--timing', exe, '--data', data, '--page', page), 1, 'only from release builds') + if data.read_text() != DATA.read_text() or page.exists(): + raise AssertionError('the data was rewritten or the page written') + + +def test_a_program_built_at_variant_release_is_measured_stored_and_rendered( + scratch: Path) -> None: + data, page = scratch / 'data.json', scratch / 'page.adoc' + before = datetime.datetime.now(datetime.timezone.utc).date().isoformat() + # The data need not exist, and an older measurement is replaced. + for existing in (None, DATA.read_text()): + if existing is not None: + data.write_text(existing) + expect(run('--timing', timing_program(scratch / str(existing is None)), '--data', data, + '--page', page), 0) + written = json.loads(data.read_text()) + stored = {key: written[f'{key}_ns'] for key in GUARD if isinstance(GUARD[key], float)} + if stored != {key: value for key, value in GUARD.items() if isinstance(value, float)} or \ + written['dit'] is not True or written['build'] != 'variant=release' or \ + written['iterations'] != GUARD['iterations'] or written['runs'] != 5: + raise AssertionError(f'the guard was not stored as measured: {written}') + utc = {datetime.datetime.now(datetime.timezone.utc).date().isoformat(), before} + if written['date'] not in utc: + raise AssertionError(f"the date {written['date']} is not UTC's {utc}") + loads = written['load_average_before_after'] + if len(loads) != 2 or any(len(load) != 3 for load in loads): + raise AssertionError(f'the load averages are not two triples: {loads}') + text = page.read_text() + for expected in ('[#secure-performance]', '<>', '| 12.3', '| 11.2', '| 19.8', + '| 0.7', '| 0.2', '| 1.8', '| 0.0', '| 0.4', 'load averages were', + 'The guard sets DIT on this machine', '10,000,000 guards'): + if expected not in text: + raise AssertionError(f'{expected!r} is not on the page:\n{text}') + if 'provisional' in text: + raise AssertionError(f'the page says provisional:\n{text}') + + +def test_a_machine_without_dit_says_the_rows_are_noise(scratch: Path) -> None: + data, page = scratch / 'data.json', scratch / 'page.adoc' + line = json.dumps({**GUARD, 'dit': False}) + expect(run('--timing', timing_program(scratch, line), '--data', data, '--page', page), 0) + if 'does not set DIT on this machine' not in page.read_text(): + raise AssertionError('the page does not say the guard sets nothing here') + + +def test_a_program_that_fails_is_refused_with_a_message(scratch: Path) -> None: + data, page = scratch / 'data.json', scratch / 'page.adoc' + exe = program(scratch, 'release') + done = run('--timing', exe, '--data', data, '--page', page) + expect(done, 1, 'timing --measure: exit 3', 'the stand-in ran') + if 'Traceback' in done.stderr or data.exists() or page.exists(): + raise AssertionError(f'a traceback, or a file was written:\n{done.stderr}') + + +def test_a_timing_line_or_data_of_another_form_is_refused_with_a_message(scratch: Path) -> None: + data, page = scratch / 'data.json', scratch / 'page.adoc' + lines = { + 'not json': 'line (not JSON)', + json.dumps({key: value for key, value in GUARD.items() if key != 'disengaged'}): + 'line.disengaged (missing)', + json.dumps({**GUARD, 'clear': 'fast'}): 'line.clear', + json.dumps({**GUARD, 'dit': 1}): 'line.dit', + } + for index, (line, named) in enumerate(lines.items()): + data.write_text(DATA.read_text()) + done = run('--timing', timing_program(scratch / str(index), line), '--data', data, + '--page', page) + expect(done, 1, 'not the form collect.py reads', named) + if 'Traceback' in done.stderr or page.exists() or data.read_text() != DATA.read_text(): + raise AssertionError(f'{line}: a traceback, or a file was written:\n{done.stderr}') + committed = json.loads(DATA.read_text()) + for change, named in ((lambda d: d.pop('set_ns'), 'data.set_ns (missing)'), + (lambda d: d.update(dit='yes'), 'data.dit'), + (lambda d: d.update(machine=3), 'data.machine (not an object)'), + (lambda d: d.update(load_average_before_after=[]), + 'data.load_average_before_after (not a list, or empty)')): + broken = json.loads(json.dumps(committed)) + change(broken) + data.write_text(json.dumps(broken)) + done = run('--render-only', '--data', data, '--page', page) + expect(done, 1, 'not the data collect.py writes', named) + if 'Traceback' in done.stderr or page.exists(): + raise AssertionError(f'{named}: a traceback, or the page was written:\n{done.stderr}') + data.write_text('not json') + expect(run('--render-only', '--data', data, '--page', page), 1, 'cannot be read') + expect(run('--render-only', '--data', scratch / 'missing.json', '--page', page), 1, + 'cannot be read') + + +def test_render_only_refuses_data_not_built_at_variant_release(scratch: Path) -> None: + committed = json.loads(DATA.read_text()) + page = scratch / 'page.adoc' + for build in ('variant=debug', 'variant=release optimization=speed', None): + data = json.loads(json.dumps(committed)) + if build is None: + del data['build'] + else: + data['build'] = build + path = scratch / 'data.json' + path.write_text(json.dumps(data)) + done = run('--render-only', '--data', path, '--page', page) + expect(done, 1, 'only from release builds') + if page.exists(): + raise AssertionError(f'{build}: the page was written') + path = scratch / 'data.json' + path.write_text(json.dumps(committed)) + expect(run('--render-only', '--data', path, '--page', page), 0) + if page.read_text() != PAGE.read_text(): + raise AssertionError('the committed data does not render the committed page') + + +def test_the_load_note_states_only_the_loads_and_only_at_two_or_more(scratch: Path) -> None: + committed = json.loads(DATA.read_text()) + for loads, noted in (([[4.5, 4.0, 3.0], [1.0, 1.0, 1.0]], True), + ([[1.0, 1.0, 1.0], [2.0, 1.0, 1.0]], True), + ([[0.5, 1.0, 1.0], [1.99, 1.0, 1.0]], False)): + data, page = scratch / 'data.json', scratch / 'page.adoc' + data.write_text(json.dumps({**committed, 'load_average_before_after': loads})) + expect(run('--render-only', '--data', data, '--page', page), 0) + text = page.read_text() + note = [line for line in text.splitlines() if line.startswith('NOTE:')] + if bool(note) != noted: + raise AssertionError(f'{loads}: the note is {"absent" if noted else "present"}') + if noted: + for expected in (f'{loads[0][0]:.2f} before and {loads[1][0]:.2f}', 'below 2', + "upper bound of an idle machine's"): + if expected not in ' '.join(text.split()): + raise AssertionError(f'{expected!r} is not in the note:\n{text}') + for claim in ('system tasks', 'no build', 'core was free', 'idle by that rule'): + if claim in text: + raise AssertionError(f'the page claims a cause, {claim!r}:\n{text}') + + +def test_exactly_one_of_timing_and_render_only_is_given(scratch: Path) -> None: + data, page = scratch / 'data.json', scratch / 'page.adoc' + data.write_text(DATA.read_text()) + exe = timing_program(scratch) + for arguments in ((), ('--timing', exe, '--render-only')): + done = run(*arguments, '--data', data, '--page', page) + expect(done, 1, 'give --timing to measure, or --render-only to render') + if data.read_text() != DATA.read_text() or page.exists(): + raise AssertionError(f'{arguments}: a file was written') + + +CASES: list[Callable[[Path], None]] = [ + test_a_program_not_built_at_variant_release_is_refused, + test_the_committed_data_is_not_replaced_by_a_refused_program, + test_a_program_built_at_variant_release_is_measured_stored_and_rendered, + test_a_machine_without_dit_says_the_rows_are_noise, + test_a_program_that_fails_is_refused_with_a_message, + test_a_timing_line_or_data_of_another_form_is_refused_with_a_message, + test_render_only_refuses_data_not_built_at_variant_release, + test_the_load_note_states_only_the_loads_and_only_at_two_or_more, + test_exactly_one_of_timing_and_render_only_is_given, +] + + +def main(argv: list[str]) -> int: + unknown = set(argv) - {case.__name__ for case in CASES} + if unknown: + print(f'secure_collect_test: no case named {", ".join(sorted(unknown))}', file=sys.stderr) + return 2 + for case in CASES: + if argv and case.__name__ not in argv: + continue + with tempfile.TemporaryDirectory(prefix='webcpp secure collect ') as scratch: + case(Path(scratch)) + print(f'{case.__name__}: ok') + print('secure_collect_test: ok') + return 0 + + +if __name__ == '__main__': + sys.exit(main(sys.argv[1:])) diff --git a/tools/test/secure_dudect_judge_test.py b/tools/test/secure_dudect_judge_test.py new file mode 100644 index 00000000..63a00f5d --- /dev/null +++ b/tools/test/secure_dudect_judge_test.py @@ -0,0 +1,22 @@ +#!/usr/bin/env python3 +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +"""Checks libs/secure/test/constant_time/dudect_judge.py, secure's copy of crypto's judge of +dudect's outputs, with crypto_dudect_judge_test.py's cases: the same scratch outputs and fake +programs, run against secure's judge. Run with the names of some cases to run only those.""" + +from __future__ import annotations + +import sys + +import crypto_dudect_judge_test + +crypto_dudect_judge_test.JUDGE = (crypto_dudect_judge_test.ROOT / + 'libs/secure/test/constant_time/dudect_judge.py') + +if __name__ == '__main__': + sys.exit(crypto_dudect_judge_test.main(sys.argv[1:])) diff --git a/tools/test/secure_jamfiles_test.py b/tools/test/secure_jamfiles_test.py new file mode 100644 index 00000000..ce349dd8 --- /dev/null +++ b/tools/test/secure_jamfiles_test.py @@ -0,0 +1,88 @@ +#!/usr/bin/env python3 +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +"""Builds every fixture of tools/test/fixtures/secure_jamfiles, a Jamfile as a user of +webcpp::secure writes it (b2's raw exe), with b2 as a user runs it, and checks its outcome file: +the build's status, the lines a failure prints, and a program's output (CODING-GUIDELINES.md +chapter 8), through user_jamfiles.py. The cases are the spec's scenario "A program that erases a +buffer builds nothing" (program, and program_no_exceptions with `off`), and +the Emscripten case of each message of libs/secure/test/messages. + +Each message of libs/secure/test/messages// (a compile-diagnostic, natively and on WASI) has +the fixture _on_emscripten, its Emscripten case: before building anything, the test checks +that the fixture's app.cpp is the message's source without its expected-error directive, and that +its outcome's one contains: line is the directive's text. + +The scratch superproject holds libs/config and libs/secure. Run with the names of some cases to +run only those, and with --target to run one target.""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +import harness +import user_jamfiles + +CASES = harness.FIXTURES / 'secure_jamfiles' +MESSAGES = harness.ROOT / 'libs/secure/test/messages' + +# Cases whose outcome needs code that is not merged yet, as crypto_jamfiles_test.py's NOT_YET. +NOT_YET: dict[str, str] = {} + +DIRECTIVE = re.compile(r'^// expected-error@\S+ \{\{(.*)\}\}$', re.MULTILINE) + + +def program_of(source: str) -> str: + """A message's source as a user's program: without its expected-error directive, the + clang-format guards around it and the note on clang's -verify, which only the + compile-diagnostic rule reads, and with no run of blank lines left behind.""" + text = re.sub(r'^// expected-error@.*\n', '', source, flags=re.MULTILINE) + text = text.replace('// clang-format off\n// clang-format on\n', '') + text = re.sub(r"^// clang's -verify reads.*\n(?://.*\n)*", '', text, flags=re.MULTILINE) + return re.sub(r'\n\n\n+', '\n\n', text) + + +def message_faults(cases: list[Path]) -> list[str]: + """The faults between libs/secure/test/messages and the fixtures, found without b2: a message + with no fixture _on_emscripten, a fixture whose source or text is not its message's, + and a fixture named for a message there is no directory of.""" + faults: list[str] = [] + by_name = {case.name: case for case in cases} + messages = sorted(p for p in MESSAGES.iterdir() if p.is_dir()) + for message in messages: + name = message.name + case = by_name.get(f'{name}_on_emscripten') + if case is None: + faults.append(f'test/messages/{name} has no fixture {name}_on_emscripten') + continue + source = (message / f'{name}.cpp').read_text() + texts = DIRECTIVE.findall(source) + if (case / 'app.cpp').read_text() != program_of(source): + faults.append(f'{case.name}: app.cpp is not test/messages/{name}/{name}.cpp without ' + 'its directive') + expected = user_jamfiles.outcome(case / f'{case.name}.outcome', 'emscripten') + if expected.targets != ['emscripten'] or expected.contains != texts: + faults.append(f'{case.name}: the outcome is not the text {texts!r} on emscripten ' + 'alone') + names = {m.name for m in messages} + for case in cases: + if case.name.endswith('_on_emscripten') and \ + case.name[:-len('_on_emscripten')] not in names: + faults.append(f'{case.name}: there is no test/messages/' + f'{case.name[:-len("_on_emscripten")]}') + return faults + + +def main(argv: list[str]) -> int: + return user_jamfiles.main('secure_jamfiles', CASES, ('config', 'secure'), NOT_YET, argv, + message_faults) + + +if __name__ == '__main__': + sys.exit(main(sys.argv[1:]))