diff --git a/.github/workflows/library.yml b/.github/workflows/library.yml index 21f867b2..f47f9d0a 100644 --- a/.github/workflows/library.yml +++ b/.github/workflows/library.yml @@ -335,6 +335,17 @@ jobs: with: product: ${{ (matrix.library == 'beast' || matrix.library == 'cobalt') && 'chrome' || 'chrome-headless-shell' }} + # The packages the lane needs from apt (its entry's apt, tools/ci/matrix.py's + # OWN_LANE_PACKAGES): crypto's constant-time lane natively has Valgrind, llvm-18 and + # clang-18's sanitizer runtime. The lane runs on the runner, never in the container, so + # they are installed here. A mirror's transient error is retried, and an index that still + # cannot be fetched fails the step, as in the container's image. + - name: Install the lane's packages + if: runner.os == 'Linux' && join(matrix.apt, ' ') != '' + run: | + sudo apt-get -o Acquire::Retries=5 -o APT::Update::Error-Mode=any update + sudo apt-get -o Acquire::Retries=5 install --yes --no-install-recommends ${{ join(matrix.apt, ' ') }} + - name: Build the native Beast interoperability peer if: matrix.library == 'beast' && (matrix.lane == 'browser' || matrix.lane == 'browser-node') shell: bash @@ -420,13 +431,16 @@ jobs: if-no-files-found: error retention-days: 7 - # The size tables a lane wrote (webcpp.size-table), kept beyond the job. + # The size tables a lane wrote (webcpp.size-table, webcpp.program-sizes, whose JSON a + # library's generator reads), kept beyond the job. - name: Upload the lane's size tables if: always() uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: sizes-${{ matrix.id || matrix.name }} - path: bin/**/*.sizes.md + path: | + bin/**/*.sizes.md + bin/**/*.sizes.json if-no-files-found: ignore - name: Upload OpenSSL upstream test evidence @@ -583,6 +597,15 @@ jobs: with: libraries: 'false' + # The own lanes' packages (tools/ci/matrix.py lint-packages): the lint analyses their + # programs natively, which include valgrind/memcheck.h and clang-18's sanitizer/ headers. + - name: Install the own lanes' packages + run: | + packages="$(python3 tools/ci/matrix.py lint-packages)" + sudo apt-get -o Acquire::Retries=5 -o APT::Update::Error-Mode=any update + # shellcheck disable=SC2086 + sudo apt-get -o Acquire::Retries=5 install --yes --no-install-recommends $packages + # The compilation database is what b2 compiles with its default toolset, the first that # user-config.jam registers, Clang 18, and, for what only a WASI target or emscripten # builds, with the toolset of that target: a WASI dry run generates the bindings its diff --git a/.gitmodules b/.gitmodules index 9748bccc..0f4ca6fb 100644 --- a/.gitmodules +++ b/.gitmodules @@ -89,3 +89,7 @@ path = third_party/libs/blake2 url = https://github.com/BLAKE2/BLAKE2.git shallow = true +[submodule "third_party/libs/ed25519-speccheck"] + path = third_party/libs/ed25519-speccheck + url = https://github.com/novifinancial/ed25519-speccheck.git + shallow = true diff --git a/AGENTS.md b/AGENTS.md index b1f66632..d5a268f9 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -266,8 +266,9 @@ Jamroot is its build configuration, and `libs/` is its repository. - for crypto: nothing installed, with the pinned submodules initialised: `git submodule update --init third_party/libs/bearssl third_party/libs/secp256k1 third_party/libs/bitcoin third_party/libs/wycheproof - third_party/libs/bips`, and `third_party/libs/openssl` for its OpenSSL - backend (below); b2 builds every backend from its sources; + third_party/libs/bips third_party/libs/ed25519-speccheck`, and + `third_party/libs/openssl` for its OpenSSL backend (below); b2 builds every + backend from its sources; - for native Trystero: CMake and Make (nmake on Windows), and the pinned `third_party/libs/libdatachannel` checkout with its required nested sources. Initialize it, and the libsecp256k1 every room links, with `git submodule @@ -1077,7 +1078,7 @@ webcpp.run : + : * : * ; webcpp.run-fail : + : * : * ; webcpp.compile : + : * : * ; webcpp.compile-fail : + : * : * ; -webcpp.compile-diagnostic : + : * : * ; +webcpp.compile-diagnostic : + : * : * : alone ? ; webcpp.boost-test : + : * ; webcpp.example : * : * ; webcpp.headers-alone : : * : * : * ; @@ -1095,7 +1096,7 @@ webcpp.source-only + ; (reference source trees) | `webcpp.compile` | the sources compile | no program is linked; takes `/webcpp//node-test` for its header | | `webcpp.compile-fail` | the sources do not compile | left out of clang-tidy; any error passes it, the wrong one included; takes `/webcpp//node-test` for its header | | `webcpp.link-fail` | the compiled sources fail to link | use a matching successful control to distinguish the intended incompatibility from unrelated failures; the sources remain in clang-tidy | -| `webcpp.compile-diagnostic` | the sources stop with every error they state in clang's `-verify` comments, `// expected-error@:* {{}}` for a header they include or `// expected-error@+1 {{}}` for the next line | compiled with `-Xclang -verify -Xclang -verify-ignore-unexpected=error,note`, so an error not stated and a note are ignored, the cascade that follows a header's `#error` among them; then `tools/compile_diagnostic/check.py` runs the compile again with clang's diagnostic log and fails on any error located in a comment (a `//` one or a `/* */` one over several lines) after an `expected-` of that comment, which is `-verify`'s own report on a directive it could not read and so dropped (a header it names that cannot be located, a `{{...}}` whose `}}` is not on its line), and on a compile that reports no error at all: each directive clang reads, every one outside a branch the preprocessor skips, must be read whole, the header it names found and included, and its error raised in that header; built on b2's `clang` toolset only (native clang, `clang-wasip2`, `clang-wasip3`) and skipped elsewhere, since `-verify` is clang's: a refusal would turn every gcc and msvc lane red for a declaration that holds; left out of clang-tidy; takes `/webcpp//node-test` for its header | +| `webcpp.compile-diagnostic` | the sources stop with every error they state in clang's `-verify` comments, `// expected-error@:* {{}}` for a header they include or `// expected-error@+1 {{}}` for the next line | compiled with `-Xclang -verify -Xclang -verify-ignore-unexpected=error,note`, so an error not stated and a note are ignored, the cascade that follows a header's `#error` among them; with `alone` last, with `-verify-ignore-unexpected=note`, so the stated errors are the compile's only ones and a refusal meant to be the first and only error fails its test when another error follows it; then `tools/compile_diagnostic/check.py` runs the compile again with clang's diagnostic log and fails on any error located in a comment (a `//` one or a `/* */` one over several lines) after an `expected-` of that comment, which is `-verify`'s own report on a directive it could not read and so dropped (a header it names that cannot be located, a `{{...}}` whose `}}` is not on its line), and on a compile that reports no error at all: each directive clang reads, every one outside a branch the preprocessor skips, must be read whole, the header it names found and included, and its error raised in that header; built on b2's `clang` toolset only (native clang, `clang-wasip2`, `clang-wasip3`) and skipped elsewhere, since `-verify` is clang's: a refusal would turn every gcc and msvc lane red for a declaration that holds; left out of clang-tidy; takes `/webcpp//node-test` for its header | | `webcpp.boost-test` | every case of the Boost.Test suite passes | native only, whatever the Jamfile declares; the header-only framework, `tools/boost_test_runner.cpp`, is one object of the suite's, always compiled with exceptions | | `webcpp.source-only` | | declares child source directories whose original Jamfiles are not WebCPP projects; use in `build.jam` before discovery; it changes neither explicit compilation nor lint | | `webcpp.example` | the program exits with 0, and its standard output, carriage returns removed, equals `.expected` beside it | its standard input is `.input` beside it, else empty, never the terminal, on every target (wasmtime passes it through, and node under `-sNODERAWFS=1`, which `off` replaces with NODEFS); run through `testing.launcher` for WASI, and on emscripten with the node on `PATH`, not the one b2's toolset registered, which b2 gives only to its own testing rules, by `tools/example/run_example.py`, which names a failing exit status (or the signal) before the diff; always run again, and `.input` is a source of the run; links `/webcpp//node-test` on every target (Targets, above) | diff --git a/CODING-GUIDELINES.md b/CODING-GUIDELINES.md index cce79aa6..3d25e93e 100644 --- a/CODING-GUIDELINES.md +++ b/CODING-GUIDELINES.md @@ -963,12 +963,13 @@ update --init third_party/libs/`; a build that needs none never looks. | `blake3_vectors` | BLAKE3's official vectors, `test_vectors/test_vectors.json` of the submodule `third_party/libs/blake3` at `f3149ec`, test data: hash's tests read it at run time under the directory its define `WEBCPP_TEST_BLAKE3_VECTORS` gives, on every target (wasmtime is given it, `webcpp.data`), and run again when it changes | CC0-1.0, Apache-2.0, or Apache-2.0 with LLVM exception | | `ca_certificates` | Dated Mozilla/curl CA data snapshot under `third_party/ca_certificates`, verified against its manifest and embedded by a build-generated header; updated explicitly by `tools/ca_certificates/update.py` | MPL-2.0 | | `ctaes` | `src/crypto/ctaes` of `bitcoin/bitcoin` v31.1 at `9be056a` (commit `9be056a8a72b624dae9623b2f7bded92c2a21c91`), the submodule `third_party/libs/bitcoin`, shallow; `third_party/Jamfile` compiles its `ctaes.c` alone, with webcpp::crypto's canary, on every target (`WEBCPP_CRYPTO_HAS_CTAES=1`); the tree's `src/secp256k1/` subtree is never on an include path and no glob over `third_party/libs` reaches it | MIT | +| `ed25519-speccheck` | `novifinancial/ed25519-speccheck` at `65519336` (2021-02-26), shallow, test data: crypto's tests read the twelve Ed25519 edge cases of "Taming the many EdDSAs", its `cases.json`, at run time under the directory its define `WEBCPP_TEST_ED25519_SPECCHECK` gives, on every target (wasmtime is given it, `webcpp.data`), and run again when it changes | Apache-2.0 | | `json-schema-test-suite` | the JSON Schema Test Suite at `5b0ee16` (2026-09-21), test data: a test that names it reads the suite at run time from the directory its define `WEBCPP_TEST_JSON_SCHEMA_TEST_SUITE` gives, on every target (wasmtime is given it, `webcpp.data`), and runs again when a file of the suite changes | MIT | | `libdatachannel` | libdatachannel 0.24.6 at `6b1e2e620f1e37f0eafeee702eaea0043cb305fd`, with pinned libjuice, libsrtp, plog and usrsctp sources; static native archives built by upstream CMake through B2 against the same source-built OpenSSL | MPL-2.0 and the nested dependencies' own licences | | `nativejson-benchmark` | Milo Yip's nativejson-benchmark at `478d572` (2022-10-28), test data: document's benchmarks (`libs/document/bench`) read its `data/canada.json`, `data/citm_catalog.json` and `data/twitter.json` at run time under the directory its define `WEBCPP_TEST_NATIVEJSON_BENCHMARK` gives, on every target (wasmtime is given it, `webcpp.data`), and run again when one of them changes; its own submodules are never checked out | MIT | | `openssl` | OpenSSL 3.5.9 at `45e844fa2a14ec92d146bd8f5778ac130b6625fb`; static libssl/libcrypto and matching generated headers, built by upstream Configure/Make through B2 for native Clang/GCC/MSVC, WASIp2 single and WASIp3 single/cooperative | Apache-2.0 | | `secp256k1` | libsecp256k1 v0.8.0 at `6e2c8bc`; a static library built file by file by `third_party/Jamfile` (`src/secp256k1.c` and its two precomputed tables, every module on) with webcpp::crypto's canary, on every target; its tables by `webcpp-secp256k1-tables` (`auto`: small on Emscripten, large elsewhere); `WEBCPP_CRYPTO_HAS_SECP256K1=1` | MIT | -| `sodium` | libsodium 1.0.22 at `77e1ce5`, the submodule `third_party/libs/libsodium`; a static library built file by file by `third_party/Jamfile` (every `.c` of `src/libsodium/`, no assembly, the defines libsodium's configure finds on each target, upstream's `builds/msvc/version.h` copied into the build directory) with webcpp::hash's canary, on every target; `WEBCPP_HASH_HAS_SODIUM=1`; `sodium-test-config` gives a program its private headers and test defines; shared with webcpp::crypto | ISC | +| `sodium` | libsodium 1.0.22 at `77e1ce5`, the submodule `third_party/libs/libsodium`; a static library built file by file by `third_party/Jamfile` (every `.c` of `src/libsodium/`, no assembly, the defines libsodium's configure finds on each target, upstream's `builds/msvc/version.h` copied into the build directory) with webcpp::hash's canary and webcpp::crypto's (`libs/crypto/src/canary_sodium.c`, configuration `portable`), on every target; `WEBCPP_HASH_HAS_SODIUM=1` and `WEBCPP_CRYPTO_HAS_SODIUM=1`; `sodium-test-config` gives a program its private headers and test defines; shared with webcpp::crypto | ISC | | `sodium_vectors` | libsodium's own tests' expected outputs, `test/default/*.exp` of the submodule `third_party/libs/libsodium` at `77e1ce5`, test data: hash's tests read `generichash3.exp`, `kdf.exp`, `pwhash_argon2i.exp`, `shorthash.exp` and `siphashx24.exp` at run time under the directory its define `WEBCPP_TEST_SODIUM_VECTORS` gives, on every target (wasmtime is given it, `webcpp.data`), and run again when it changes | ISC | | `wycheproof` | C2SP's Wycheproof at `12fd3aaf` (2026-10-06), shallow, test data: crypto's tests read its `testvectors_v1/` at run time under the directory its define `WEBCPP_TEST_WYCHEPROOF` gives, on every target (wasmtime is given it, `webcpp.data`), and run again when one of its files changes | Apache-2.0 | | `xkcp` | XKCP (the Keccak team's code package) at `d20c8fc` (2026-11-10, no release tags); `third_party/Jamfile` compiles its `KeccakP-1600-opt64.c` (Keccak-p[1600], the generic64 profile) and the high-level files over it, `KeccakSponge.c`, `KeccakHash.c` (FIPS 202), `SP800-185.c`, `TurboSHAKE.c` and `KangarooTwelve.c` (serial: no times-N permutation), with webcpp::hash's adapter, `config.h` (`XKCP_has_KeccakP1600`, `_Sponge_Keccak`, `_TurboSHAKE`, `_FIPS202`, `_SP800_185`, `_KangarooTwelve`) and canary, on every target; `WEBCPP_HASH_HAS_XKCP=1` | CC0; `brg_endian.h` under Brian Gladman's terms | @@ -7173,20 +7174,26 @@ and not built is in chapter 17. **Default backend.** -- **The AEADs' default backend is BearSSL on Emscripten, wasip2 and wasip3, - OpenSSL natively when it is linked, BearSSL natively otherwise, and a - program picks BearSSL with `WEBCPP_CRYPTO_DEFAULT_BACKEND_BEARSSL`; - on MSVC the default follows the same rule.** OpenSSL's assembly uses the - CPU's AES and carry-less multiplication instructions on x86-64 and ARMv8, - and BearSSL has them on x86 only; on WebAssembly BearSSL is constant time - where the `no-asm` OpenSSL is not (the owner's decision 2 of 2026-11-14). - Speed and size are not measured until the deferred lanes (chapter 17). - Source: `include/webcpp/crypto/config.hpp` (libs/crypto); the plan's - revision of 2026-11-14 (proposals, `reference/plan.md`). -- **The page warns that natively without OpenSSL a server on ARM runs - BearSSL's portable code, and names `/webcpp/crypto//openssl`; it states no - factor.** BearSSL has no ARMv8 AES or PMULL code; the slowdown on the - source-built OpenSSL is not measured. +- **Each family has one default backend per target, chosen by the target + alone for a stated reason, whatever the program links; no define changes it, + and a program names any other backend in the type.** AES-GCM's is OpenSSL + natively, on MSVC too, and BearSSL on Emscripten, wasip2 and wasip3: + OpenSSL's assembly uses the CPU's AES and carry-less multiplication + instructions on x86-64 and ARMv8, and BearSSL has them on x86 only; on + WebAssembly BearSSL is constant time where the `no-asm` OpenSSL is not. A + program that uses a default it does not link stops where it calls it, with + the Jamfile line and the type that names another backend; version 0.1's + `WEBCPP_CRYPTO_DEFAULT_BACKEND_BEARSSL` and `_OPENSSL` stop the build with the + type to write. Measurements are references and decide no default. + Source: `doc/tables/crypto.json` and the generated + `include/webcpp/crypto/detail/defaults.hpp` (libs/crypto); design D32 and the + owner's answers Q1 to Q4 of 2026-11-17 (proposals, `foundation/design.md`, + `reference/roadmap.md`). +- **The page warns that a native program that names BearSSL runs BearSSL's + portable code on an ARM server, where the default, OpenSSL, uses ARMv8's AES; + the examples use the default and link it on every target with + `/webcpp/crypto//gcm-default`; it states no factor.** BearSSL has no ARMv8 + AES or PMULL code; the slowdown on the source-built OpenSSL is not measured. Source: `doc/aead.adoc` (libs/crypto). **Randomness and memory.** @@ -7357,8 +7364,8 @@ and not built is in chapter 17. - **The user's Jamfiles are the fixtures `tools/test/fixtures/crypto_jamfiles//`, each with its `.outcome` (targets, build, what runs print, what each linker prints), built on a scratch superproject: `web`, `server`, - `both_bearssl_default`, `block`, `encrypt_and_sign`, `openssl_linked`, - `sign`, `sign_small`, and the stops (canaries, OpenSSL on Emscripten); a + `both_bearssl_named`, `gcm_default`, `block`, `encrypt_and_sign`, + `openssl_linked`, `sign`, `sign_small`, and the stops (canaries, OpenSSL on Emscripten); a `same-as:` line keeps a copied program equal to its original, and the page includes each Jamfile and outcome by tag.** A user's Jamfile is what an agent copies, so each one shown is built and run as it is shown. @@ -8082,8 +8089,12 @@ The closure record distinguishes the baseline CI from validation of later change configuration, `-config-.selected` in its own variant directory, which is written when the configuration changes, to a new one or back to one built earlier, so the consumer is built again. Removing a configuration's - directory builds it again. A checkout that differs from its pin stops b2 - before any build, by the library's own `check_checkout`. + directory builds it again. The build record, `build.json` (OpenSSL's and + libdatachannel's), is one of its outputs, published last and whole after + its build removed the earlier one and its archives: a directory an + interrupted build left without it is built again. A checkout that differs + from its pin stops b2 before any build, by the library's own + `check_checkout`. Source: `tools/webcpp-third-party.jam`, `tools/third_party_build.py` (superproject). - **A dated curl export of Mozilla's root certificates (2026-09-25, 121 CAs) @@ -8559,37 +8570,87 @@ each with its decisions as decided. While a proposal is open, its own change that builds it moves its decisions into chapter 14 or 15. Their conflicts with chapters 1 to 13 are in chapter 19. -### crypto, after 0.1 (accepted 2026-10-11; increments 1 and 2 built in 0.1.0 and the memory option built after 0.1, chapter 15) - -The plan (`reference/plan.md`, revised on 2026-11-14) built version 0.1 from -its increments 1 and 2, and OpenSSL's memory option after it; the owner -deferred the rest, kept as written and re-read before it runs. What is built -is in chapter 15; what follows is decided and not built. - -**Constant time (plan Task 20).** +### crypto, after 0.1 (genesis accepted 2026-10-11, foundation accepted 2026-11-14; the foundation's increment 1 built on its branch, not merged) + +The genesis's plan (`reference/plan.md`, revised on 2026-11-14) built version +0.1 from its increments 1 and 2, and OpenSSL's memory option after it. The +foundation (`libraries/crypto/openspec/changes/foundation`) takes the work +on: twelve increments, version 0.2 onward, and the genesis's increments 4 and +5 (ChaCha20-Poly1305, Botan) with them; trystero's migration is dropped. +Its rules are webcpp::hash's: one default backend per family and target with +its reason stated, no profile and no per-family override (design D32), tables +of size and speed only from release builds, and primitives only (D24). What +is built is in chapter 15; what follows is decided and not built, except +increment 1, whose state is first. + +**The foundation's increment 1 (plan Tasks 1 to 16).** + +- **Built on the branch `crypto/foundation-1` of the library and the + superproject, awaiting the owner's merge: libsodium's backend, the families + on it, the capability table, the fixed defaults, the three own lanes and + the page.** `backends::sodium` on `/third_party//sodium`, shared with + webcpp::hash, with crypto's canary; `curves::ed25519` (strict verification + over the twelve edge cases, Ed25519ph, the conversion, RFC 8410's 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 + `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 + backends' own suites), `sizes` (at `variant=release`, on every target) and + `constant-time`. Throughput is measured by hand and dated, and decides + nothing. + Source: `libraries/crypto/openspec/changes/foundation/reference/plan.md` + Tasks 2 to 16 and its revision of 2026-11-17 (proposals); + `libs/crypto/AGENTS.md`. +- **One finding is open: X25519's constant time on wasip2.** dudect measures + `agree` under wasmtime above its threshold (|t| 13 to 260 against 10), where + the native builds pass; no secret branch was found in the WebAssembly or in + wasmtime's code. The cause is measured: Apple silicon's DIT (data-independent + 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 set DIT themselves; the WebAssembly cannot. 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 + page says, as it says that OpenSSL's `open` is left out of memcheck. + Source: `libs/crypto/doc/generated/constant-time.adoc`, + `doc/tables/crypto.json` (libs/crypto). +- **What is not built is in the other increments: libsecp256k1's remaining + modules (2), BearSSL's (3), the browser backend and the asynchronous family + (4), libsodium completed (5), blst (6), Botan as a submodule (7), OpenSSL's + remaining algorithms (8), KZG, BN254, Shamir and HPKE (9 to 12).** The + merges, the CI's run and the proposals' status are the owner's. + Source: `libraries/crypto/openspec/changes/foundation/reference/roadmap.md` + (proposals). + +**Constant time (increment 1, Task 14; built on the branch).** - **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, through the seam - `WEBCPP_CRYPTO_DETAIL_DECLASSIFY`, empty in 0.1.** `equal` compiles in the - user's translation unit, so it is checked at -O2 and -Os; under wasmtime the + method natively and under wasmtime on wasip2, through the seam + `WEBCPP_CRYPTO_DETAIL_DECLASSIFY`.** `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 "measured" columns say "not measured yet" until then. + The page's per-target cells are generated from the lane's own entries, and + a target the lane does not run says "not measured yet". Source: `libraries/crypto/openspec/changes/genesis/reference/spec.md` - sections 3.2 and 8.3 (proposals). + sections 3.2 and 8.3 (proposals); `test/constant_time/Jamfile` (libs/crypto). -**Sizes and throughput (plan Task 22).** +**Sizes and throughput (increment 1, Task 11'; built on the branch).** -- **Sizes are measured at b2's `speed` and `space` on every target, and - throughput by webcpp's own program on ubuntu-24.04, ubuntu-24.04-arm and - macos-15, in the own lanes `sizes` and `throughput` (`runners.yml`); the - page's size and speed cells and the defaults' speed reasons come from - them.** b2 has no -O2 that reaches the libraries a program names - (departures C16 and C17, for the owner). Until then a moved pin updates no - size table (chapter 19). - Source: `libraries/crypto/openspec/changes/genesis/reference/plan.md` - "Departures for the owner (O5)" (proposals). +- **Sizes are measured at `variant=release` on every target by the own lane + `sizes`, through `webcpp.size-table`; throughput by webcpp's own program + (`bench/collect.py`, which refuses a build that is not a release) on the + developer's machine, dated; neither decides a default.** b2 has no -O2 that + reaches the libraries a program names, so the tables are dated references; + the ubuntu-24.04, ubuntu-24.04-arm and macos-15 runs wait for the owner + (`throughput` in `runners.yml` is not built). A moved pin updates no size + table (chapter 19). + Source: `libraries/crypto/openspec/changes/foundation/design.md` D32 and + `reference/plan.md` Task 11' (proposals). **The browser lane (plan Task 23).** @@ -8618,13 +8679,14 @@ is in chapter 15; what follows is decided and not built. Source: `libraries/crypto/openspec/changes/genesis/reference/plan.md` C11 (proposals). -**ChaCha20-Poly1305 (increment 4).** +**ChaCha20-Poly1305 (built in increment 1, Task 8b, on the branch; the genesis's increment 4).** - **`ciphers::chacha20_poly1305` on BearSSL and OpenSSL is one shot only, with an IV 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 `equal` and zeroes `data` on a mismatch; the traits - `chacha_state` and `chacha_engine` join the four of 0.1.** BearSSL's + backend compares with `equal` and zeroes `data` on a mismatch; it is a + family of the one-shot template `ciphers::aead`, not + new traits.** BearSSL's ChaCha20-Poly1305 is one function over the whole message; 12 bytes and the limit are RFC 8439's. Source: `libraries/crypto/openspec/changes/genesis/reference/spec.md` diff --git a/doc/releases/0.1.0.adoc b/doc/releases/0.1.0.adoc index 0e96ec85..69f75536 100644 --- a/doc/releases/0.1.0.adoc +++ b/doc/releases/0.1.0.adoc @@ -334,6 +334,8 @@ table and to give each backend's constant-time sources one bullet. family alone, and a tag outside its namespace's chapter. * Fixed tools/hash/doc_tables.py calling backends::openssl argon2id's and scrypt's second template argument: each sentence reads the Backend's position from the header declaring the template. +* Fixed an interrupted OpenSSL or libdatachannel build leaving a configuration later builds took as +complete: its build record is published last, and one without it is built again. [#webcpp-0-1-0-compilers-tested] == Compilers tested diff --git a/libs/crypto b/libs/crypto index cc2b8010..1fc5140e 160000 --- a/libs/crypto +++ b/libs/crypto @@ -1 +1 @@ -Subproject commit cc2b80105ddad2849eb85a94817d92043cc5243f +Subproject commit 1fc5140e1a2285b996021de1af354a14397fa68c diff --git a/third_party/Jamfile b/third_party/Jamfile index 09643027..81171fad 100644 --- a/third_party/Jamfile +++ b/third_party/Jamfile @@ -136,6 +136,31 @@ alias bips : : @bips-checked-out : : $(.bips-files) ; explicit bips ; +# novifinancial/ed25519-speccheck (Apache-2.0), shallow: test data, never +# compiled. A test that names ed25519-speccheck reads the twelve Ed25519 edge +# cases of "Taming the many EdDSAs", cases.json, from the directory +# WEBCPP_TEST_ED25519_SPECCHECK names, with forward slashes, the directory +# given to wasmtime on WASI (webcpp.data), and runs again when it changes. +path-constant ED25519_SPECCHECK : libs/ed25519-speccheck ; +.ed25519-speccheck = [ regex.replace $(ED25519_SPECCHECK) "\\\\" "/" ] ; +.ed25519-speccheck-files = [ glob libs/ed25519-speccheck/cases.json ] ; + +rule ed25519-speccheck-checked-out ( properties * ) +{ + if ! [ path.exists [ path.native $(ED25519_SPECCHECK)/cases.json ] ] + { + errors.user-error "third_party/libs/ed25519-speccheck is not checked out: it" + "holds no cases.json. Check it out with `git submodule update --init" + "third_party/libs/ed25519-speccheck`." ; + } +} + +alias ed25519-speccheck : : @ed25519-speccheck-checked-out : : + "\"WEBCPP_TEST_ED25519_SPECCHECK=\\\"$(.ed25519-speccheck)\\\"\"" + [ webcpp.data $(ED25519_SPECCHECK) ] + $(.ed25519-speccheck-files) ; +explicit ed25519-speccheck ; + # OpenSSL uses its upstream Configure/Make source manifest. The bridge emits # static archives and matching generated headers in the directory of their # configuration, bin/third_party/openssl/config-, named by the bytes of @@ -670,18 +695,44 @@ rule sodium-test-defines ( properties * ) return $(.sodium-test-common) $(.sodium-test-arc4random) ; } +# libsodium, /third_party//sodium below, is webcpp::hash's target and carries +# webcpp::crypto's canary too: an object of its own, compiled with libsodium's +# defines, which the library's sources gain only when libs/crypto holds it, so +# that a checkout without libs/crypto builds hash's libsodium as before. +# WEBCPP_CRYPTO_HAS_SODIUM then joins the usage requirements. +obj sodium_crypto_canary : $(CRYPTO)/src/canary_sodium.c + : $(.c-library) @sodium-target-defines ; +explicit sodium_crypto_canary ; + +rule sodium-crypto-canary ( properties * ) +{ + if [ path.exists [ path.native $(CRYPTO)/src/canary_sodium.c ] ] + { + return sodium_crypto_canary ; + } +} + +rule sodium-crypto-usage ( properties * ) +{ + if [ path.exists [ path.native $(CRYPTO)/src/canary_sodium.c ] ] + { + return WEBCPP_CRYPTO_HAS_SODIUM=1 ; + } +} + lib sodium : [ glob-tree-ex libs/libsodium/src/libsodium : *.c ] $(HASH)/src/canary_sodium.c : $(.hash-c-library) @sodium-checked-out @sodium-target-defines + @sodium-crypto-canary sodium/version.h sodium/version.h libs/libsodium/src/libsodium/include libs/libsodium/src/libsodium/include/sodium $(.sodium-version) $(.sodium-version)/sodium : : libs/libsodium/src/libsodium/include $(.sodium-version) sodium/version.h SODIUM_STATIC=1 - WEBCPP_HASH_HAS_SODIUM=1 $(.gc) + WEBCPP_HASH_HAS_SODIUM=1 @sodium-crypto-usage $(.gc) emscripten:-sALLOW_MEMORY_GROWTH=1 ; explicit sodium ; diff --git a/third_party/libs/ed25519-speccheck b/third_party/libs/ed25519-speccheck new file mode 160000 index 00000000..65519336 --- /dev/null +++ b/third_party/libs/ed25519-speccheck @@ -0,0 +1 @@ +Subproject commit 65519336fda78a3d016e947df6d82848aca0c9da diff --git a/tools/ci/matrix.py b/tools/ci/matrix.py index bfd47d2c..30351219 100755 --- a/tools/ci/matrix.py +++ b/tools/ci/matrix.py @@ -11,6 +11,7 @@ matrix.py own-lanes [--library NAME] [--user-config FILE] matrix.py declares TARGET [--library NAME] [--user-config FILE] matrix.py external [--library NAME] + matrix.py lint-packages matrix.py lane LANE [--user-config FILE] [--out-dir DIR] [-- B2-ARGUMENT ...] matrix.py own-lane OWN-LANE [--user-config FILE] [--out-dir DIR] [-- B2-ARGUMENT ...] matrix.py register ID [ID ...] [--user-config FILE] @@ -39,10 +40,12 @@ lane's, which runs its programs; a served lane on wasip2 or wasip3 has none; "cc" and "cxx", the compilers of the lane it shares; "external", as a lane's; and "chrome", true for a lane of CHROME_LANES, whose driver meets a browser, which its job gives the pinned chrome-headless-shell as -CHROME. One that names no target runs as `b2 -a toolset=clang-18 D//N ...`, whose exit status is its -verdict: it writes no XML, so it is no column of the report. One that names targets is an entry per -target T, which adds "platform": T and the "id" .. (wasip2.wasi.http), and shares T's own -lane, or the oracle's Clang 18 for native. It runs as that lane runs, with --dump-tests and +CHROME; and "apt", the packages of OWN_LANE_PACKAGES for its library, lane and target, which its +job installs on Linux, [] for every other. One that names no target runs as +`b2 -a toolset=clang-18 D//N ...`, whose exit status is its verdict: it writes no XML, so it is +no column of the report. One that names targets is an entry per target T, which adds +"platform": T and the "id" .. (wasip2.wasi.http), and shares T's own lane, or the +oracle's Clang 18 for native. It runs as that lane runs, with --dump-tests and --out-xml, and its XML, .xml, is a column of the report under its id, which tools/report/report.py checks against the toolset it was built with and the library whose tests it lists. A target the CI has no lane to set up an own lane on fails the listing by name: an own lane @@ -61,6 +64,9 @@ docs job installs those libraries, a page parsing its library's headers and those it uses, and the second as lint-external, on which the lint job, which analyses every library, installs them. +lint-packages prints, on one line, sorted, every package of OWN_LANE_PACKAGES once: the lint job +installs them, since the lint analyses every own lane's programs natively and needs their headers. + lane runs one lane, LANE being one entry of that matrix as JSON: it registers the lane's toolset in the user-config.jam (unless it is there already), then runs the lane command the Jamroot documents, @@ -186,6 +192,17 @@ ('document', 'js'), ('trystero', 'interop'), ('webrtc', 'browser'), ('webrtc', 'interop')} +# 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_LANE_PACKAGES: dict[tuple[str, str, str], tuple[str, ...]] = { + ('crypto', '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 # word of the toolset directory too, and msvc-14.3 and msvc-14.5 are their own abbreviations, @@ -625,7 +642,8 @@ def own_lane_entry(own: OwnLane) -> dict[str, object]: """The own lane as an entry of the own-lanes matrix: its library, its lane and its directories; its target and its id when it names one; and, for every entry, its kind, the name of its job, the image, the setup and the compilers of the lane it shares, and whether its - library needs a library webcpp does not build, which the job reads from here alone.""" + library needs a library webcpp does not build, and the packages it needs from apt + (OWN_LANE_PACKAGES), which the job reads from here alone.""" base = own_lane_profile(own) entry: dict[str, object] = {'library': own.library, 'lane': own.lane, 'directories': list(own.directories)} @@ -638,10 +656,17 @@ def own_lane_entry(own: OwnLane) -> dict[str, object]: node = base.node or own.kind == 'original' entry.update(kind=own.kind, name=own.name, os=base.os, wasm=base.wasm, emsdk=base.emsdk, node=node, cc=base.cc, cxx=base.cxx, external=needs_external(own.library), - chrome=(own.library, own.lane) in CHROME_LANES) + chrome=(own.library, own.lane) in CHROME_LANES, + apt=list(OWN_LANE_PACKAGES.get((own.library, own.lane, own.target or ''), + ()))) return entry +def lint_packages() -> list[str]: + """Every package of OWN_LANE_PACKAGES once, sorted.""" + return sorted({package for packages in OWN_LANE_PACKAGES.values() for package in packages}) + + def own_lanes(user_config: Path, library: str | None) -> list[OwnLane]: """The own lanes the libraries declare, of library alone when it is given, which must be a library of libs/: one that declares no own lane has none, one that does not exist fails. An @@ -967,6 +992,8 @@ def main(arguments: list[str]) -> int: 'external', help='print true when some library needs a library webcpp does not build') externals.add_argument('--library', help='the library the CI runs for, which must exist') + commands.add_parser('lint-packages', + help="print the apt packages the own lanes' programs need, for the lint") running = commands.add_parser( 'lane', help='run one lane of the matrix', epilog='After --, more arguments for b2, such as --build-dir=bin/lane-gcc-15.') @@ -1014,6 +1041,9 @@ def main(arguments: list[str]) -> int: if options.command == 'external': print('true' if has_external(options.library) else 'false') return 0 + if options.command == 'lint-packages': + print(' '.join(lint_packages())) + return 0 if options.command == 'own-lanes': listed = [own_lane_entry(own) for own in own_lanes(options.user_config.resolve(), options.library)] diff --git a/tools/ci/matrix_test.py b/tools/ci/matrix_test.py index 954af306..03c7ece8 100755 --- a/tools/ci/matrix_test.py +++ b/tools/ci/matrix_test.py @@ -311,17 +311,17 @@ def test_own_lanes_of_every_library_and_of_one(root): 'kind': 'programs', 'name': 'Own lane (alpha, browser)', 'os': 'ubuntu-24.04', 'wasm': False, 'emsdk': False, 'node': False, 'cc': 'clang-18', 'cxx': 'clang++-18', 'external': False, - 'chrome': False}, + 'chrome': False, 'apt': []}, {'library': 'alpha', 'lane': 'http', 'directories': ['libs/alpha/test'], 'kind': 'programs', 'name': 'Own lane (alpha, http)', 'os': 'ubuntu-24.04', 'wasm': False, 'emsdk': False, 'node': False, 'cc': 'clang-18', 'cxx': 'clang++-18', 'external': False, - 'chrome': False}] + 'chrome': False, 'apt': []}] beta = [{'library': 'beta', 'lane': 'oracle', 'directories': ['libs/beta/test/oracle'], 'kind': 'original', 'name': 'Own lane (beta, oracle)', 'os': 'ubuntu-24.04', 'wasm': False, 'emsdk': False, 'node': True, 'cc': 'clang-18', 'cxx': 'clang++-18', 'external': False, - 'chrome': False}] + 'chrome': False, 'apt': []}] assert own_lanes(root) == alpha + beta assert own_lanes(root, '--library', 'beta') == beta assert own_lanes(root, '--library', 'demo') == [] @@ -377,30 +377,30 @@ def test_own_lanes_on_targets(root): 'name': 'Own lane (alpha, http, native)', 'os': 'ubuntu-24.04', 'wasm': False, 'emsdk': False, 'node': False, 'cc': 'clang-18', 'cxx': 'clang++-18', 'external': False, - 'chrome': False}, + 'chrome': False, 'apt': []}, {'library': 'alpha', 'lane': 'http', 'directories': ['libs/alpha/example', 'libs/alpha/test'], 'platform': 'wasip2', 'id': 'wasip2.alpha.http', 'kind': 'programs', 'name': 'Own lane (alpha, http, ' 'wasip2)', 'os': 'ubuntu-24.04', 'wasm': True, 'emsdk': False, 'node': False, 'cc': '', 'cxx': '', 'external': False, - 'chrome': False}, + 'chrome': False, 'apt': []}, {'library': 'alpha', 'lane': 'http', 'directories': ['libs/alpha/test'], 'platform': 'wasip3', 'id': 'wasip3.alpha.http', 'kind': 'programs', 'name': 'Own lane (alpha, http, wasip3)', 'os': 'ubuntu-24.04', 'wasm': True, 'emsdk': False, 'node': False, 'cc': '', 'cxx': '', 'external': False, - 'chrome': False}] + 'chrome': False, 'apt': []}] beta = {'library': 'beta', 'lane': 'oracle', 'directories': ['libs/beta/test/oracle'], 'kind': 'original', 'name': 'Own lane (beta, oracle)', 'os': 'ubuntu-24.04', 'wasm': False, 'emsdk': False, 'node': True, 'cc': 'clang-18', 'cxx': 'clang++-18', 'external': False, - 'chrome': False} + 'chrome': False, 'apt': []} assert own_lanes(root) == [*alpha, beta] assert own_lanes(root, '--library', 'alpha') == alpha assert run(root, 'own-lanes', '--library', 'beta').stdout == ( '{"include":[{"library":"beta","lane":"oracle","directories":["libs/beta/test/oracle"],' '"kind":"original","name":"Own lane (beta, oracle)","os":"ubuntu-24.04","wasm":false,' '"emsdk":false,"node":true,"cc":"clang-18","cxx":"clang++-18","external":false,' - '"chrome":false}]}\n') + '"chrome":false,"apt":[]}]}\n') # Each entry is read back as the lane it is, and runs in each of its directories. for entry in alpha: own = matrix.parsed_own_lane(json.dumps(entry)) @@ -423,18 +423,18 @@ def test_own_lanes_on_targets(root): 'platform': 'emscripten', 'id': 'emscripten.gamma.browser', 'kind': 'programs', 'name': 'Own lane (gamma, browser, emscripten)', 'os': 'ubuntu-24.04', 'wasm': False, 'emsdk': True, 'node': True, 'cc': '', 'cxx': '', 'external': False, - 'chrome': False}, + 'chrome': False, 'apt': []}, {'library': 'gamma', 'lane': 'driver', 'directories': ['libs/gamma/test'], 'platform': 'emscripten', 'id': 'emscripten.gamma.driver', 'kind': 'original', 'name': 'Own lane (gamma, driver, emscripten)', 'os': 'ubuntu-24.04', 'wasm': False, 'emsdk': True, 'node': True, 'cc': '', 'cxx': '', 'external': False, - 'chrome': False}, + 'chrome': False, 'apt': []}, {'library': 'gamma', 'lane': 'driver', 'directories': ['libs/gamma/test'], 'platform': 'native', 'id': 'native.gamma.driver', 'kind': 'original', 'name': 'Own lane (gamma, driver, native)', 'os': 'ubuntu-24.04', 'wasm': False, 'emsdk': False, 'node': True, 'cc': 'clang-18', 'cxx': 'clang++-18', 'external': False, - 'chrome': False}] + 'chrome': False, 'apt': []}] assert own_lanes(root) == [*alpha, beta, *gamma] assert own_lanes(root, '--library', 'gamma') == gamma for entry in gamma: @@ -1330,6 +1330,70 @@ def test_a_browser_lane_has_the_pinned_chrome(root): assert set(re.findall(r'\d+\.\d+\.\d+\.\d+', action)) == {pinned.group(1)}, action +APT_RETRIES = '-o Acquire::Retries=5' + + +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. + packages = ('valgrind', 'llvm-18', 'libclang-rt-18-dev') + assert matrix.OWN_LANE_PACKAGES == {('crypto', 'constant-time', 'native'): packages} + boost_only(root) + oracle_library(root, 'beta') + harness.add_library(root, 'crypto', + 'import webcpp ;\n' + 'webcpp.targets native wasip2 ;\n' + 'webcpp.run plain : plain.cpp ;\n' + 'webcpp.lane constant-time : plain : native wasip2 ;\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) + steps = job_steps(workflow_jobs()['own-lanes']) + installs = [step for step in steps if 'matrix.apt' in step] + assert len(installs) == 1, installs + assert "if: runner.os == 'Linux' && join(matrix.apt, ' ') != ''\n" in installs[0], installs + assert ("install --yes --no-install-recommends ${{ join(matrix.apt, ' ') }}" + in installs[0]), installs + assert steps.index(installs[0]) < next(index for index, step in enumerate(steps) + if 'matrix.py own-lane' in step), steps + + +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. + 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 + steps = job_steps(workflow_jobs()['lint']) + installs = [step for step in steps if '$(python3 tools/ci/matrix.py lint-packages)' in step] + assert len(installs) == 1, installs + assert 'install --yes --no-install-recommends' in installs[0], installs + assert steps.index(installs[0]) < next(index for index, step in enumerate(steps) + if 'tools/lint/lint.sh' in step), steps + + +def test_every_apt_get_of_the_workflow_retries(_): + # A runner's apt mirror answers some requests with a transient error, as the container's + # snapshot does (test_container_apt_get_retries_transient_failures): every apt-get of + # library.yml retries a failed download, and its update fails rather than go on with + # partial lists. + workflow = (matrix.ROOT / '.github/workflows/library.yml').read_text() + code = ''.join(line for line in workflow.splitlines(keepends=True) + if not line.lstrip().startswith('#')) + calls = re.findall(r'apt-get[^\n]*', code) + assert len(calls) == 4, calls + for call in calls: + assert APT_RETRIES in call, call + if re.search(r'\bupdate\b', call): + assert '-o APT::Update::Error-Mode=any' in call, call + + def test_host_tls_fixture_is_isolated_to_its_own_lane(root): steps = job_steps(workflow_jobs()['own-lanes']) fixture = [step for step in steps if 'WASI HTTPS host fixture' in step] @@ -1565,6 +1629,9 @@ def test_an_unavailable_container_image_fails_without_a_build(root): test_asio_browser_lane_receives_chrome, test_cobalt_browser_lanes_receive_chrome_and_all_profiles, test_a_browser_lane_has_the_pinned_chrome, + test_an_own_lane_installs_its_packages, + test_the_lint_installs_the_own_lanes_packages, + test_every_apt_get_of_the_workflow_retries, test_host_tls_fixture_is_isolated_to_its_own_lane, test_browser_contract_lanes_build_a_native_beast_peer, test_container_apt_get_retries_transient_failures, diff --git a/tools/compile_diagnostic/check.py b/tools/compile_diagnostic/check.py index 229b3596..8c5d5fc9 100644 --- a/tools/compile_diagnostic/check.py +++ b/tools/compile_diagnostic/check.py @@ -8,15 +8,16 @@ """Fails a webcpp.compile-diagnostic test whose -verify directives clang dropped. Usage: check.py --database FILE --output FILE -The test's compile ran clang's -verify with -verify-ignore-unexpected=error, which tolerates the -cascade of errors that follows a header's #error, and also hides the errors -verify itself reports -on a directive it cannot read: a header it names that cannot be located, a text whose `}}` is not -on its line. -verify then drops that directive, and the test passes on nothing. FILE, the -compilation database entry clang wrote for that compile (-MJ), gives its exact command, which this -runs again with -fsyntax-only and clang's diagnostic log, which records every diagnostic, those --verify ignores included. An error located in a comment, a // or a /* */ one over several lines, -after an `expected-` of that comment, is one of -verify's own: each is printed, and the -check fails. So does a run that reports no error at all, which no test of the rule can mean. +The test's compile ran clang's -verify with -verify-ignore-unexpected=error (unless the test is +`alone`), which tolerates the cascade of errors that follows a header's #error, and also hides the +errors -verify itself reports on a directive it cannot read: a header it names that cannot be +located, a text whose `}}` is not on its line. -verify then drops that directive, and the test +passes on nothing. FILE, the compilation database entry clang wrote for that compile (-MJ), gives +its exact command, which this runs again with -fsyntax-only and clang's diagnostic log, which +records every diagnostic, those -verify ignores included. An error located in a comment, a // or a +/* */ one over several lines, after an `expected-` of that comment, is one of -verify's own: +each is printed, and the check fails. So does a run that reports no error at all, which no test of +the rule can mean. Otherwise it writes --output.""" from __future__ import annotations diff --git a/tools/compile_diagnostic/compile_diagnostic.jam b/tools/compile_diagnostic/compile_diagnostic.jam index 749754e9..06744294 100644 --- a/tools/compile_diagnostic/compile_diagnostic.jam +++ b/tools/compile_diagnostic/compile_diagnostic.jam @@ -7,9 +7,10 @@ # The test type of webcpp.compile-diagnostic, which tools/webcpp.jam offers: # the object compiled with clang's -verify, which succeeds only when every # error its directives state appears, then a check that clang read every -# directive (check.py). -verify ignores the errors it does not expect, so -# that a header's #error may be followed by what the rest of the header then -# fails on; among them are the errors it reports on a directive it cannot +# directive (check.py). -verify ignores the errors it does not expect +# (unless the test is `alone`, see tools/webcpp.jam), so that a header's +# #error may be followed by what the rest of the header then fails on; among +# them are the errors it reports on a directive it cannot # read, a header it names that cannot be located or a text whose `}}` is not # on its line, and it drops that directive. The object's compile writes its # compilation database entry (-MJ), whose exact command check.py runs again diff --git a/tools/libdatachannel/build.py b/tools/libdatachannel/build.py index 46491c30..cf4874f7 100644 --- a/tools/libdatachannel/build.py +++ b/tools/libdatachannel/build.py @@ -67,6 +67,11 @@ def build(args: argparse.Namespace) -> None: windows = args.platform == 'windows' ssl = provider(openssl, windows) output.mkdir(parents=True, exist_ok=True) + # B2 keeps a configuration's outputs once they exist, and builds it again only when one is + # missing (tools/webcpp-libdatachannel.jam): the build record, published last, is what makes + # it complete. Remove it first, with the archives an earlier, interrupted build published. + for name in ('build.json', *archive_names(windows)): + (output / name).unlink(missing_ok=True) driver = shutil.which(args.cxx) if driver is None: raise RuntimeError(f'configured C++ compiler is missing: {args.cxx}') @@ -141,8 +146,7 @@ def build(args: argparse.Namespace) -> None: # Each static archive remains separate. OpenSSL is never inserted in # these archives, so B2 gives the final link one ssl/crypto pair. archives = {} - for library in ('datachannel', 'juice', 'usrsctp', 'srtp2'): - name = library + '.lib' if windows else 'lib' + library + '.a' + for name in archive_names(windows): matches = list((scratch / 'build').rglob(name)) if len(matches) != 1: raise RuntimeError(f'expected one built {name}, found {matches}') @@ -157,11 +161,20 @@ def build(args: argparse.Namespace) -> None: 'openssl_sha256': ssl['sha256'], 'seconds': time.monotonic() - started, 'sha256': {name: hashlib.sha256((output / name).read_bytes()).hexdigest() for name in archives}} - (output / 'build.json').write_text(json.dumps(record, indent=2) + '\n') + # The last output: a configuration with it is complete, and kept. + staged = output / 'build.json.new' + staged.write_text(json.dumps(record, indent=2) + '\n') + staged.replace(output / 'build.json') print(f'libdatachannel {pin["version"]}: static provider built in ' f'{record["seconds"]:.1f}s', flush=True) +def archive_names(windows: bool) -> tuple[str, ...]: + """The four static archives a build publishes, in link order.""" + return tuple(library + '.lib' if windows else 'lib' + library + '.a' + for library in ('datachannel', 'juice', 'usrsctp', 'srtp2')) + + def main() -> None: arguments = sys.argv[1:] if len(arguments) == 1: diff --git a/tools/libdatachannel/build_test.py b/tools/libdatachannel/build_test.py index 5acb54e8..295f2547 100644 --- a/tools/libdatachannel/build_test.py +++ b/tools/libdatachannel/build_test.py @@ -4,11 +4,21 @@ # 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) -"""Check the native dependency build's persistent symbol boundary through CMake.""" +"""Check the native dependency build's persistent symbol boundary through CMake, and the order +in which a build publishes its outputs.""" from pathlib import Path +import argparse +import json import subprocess +import sys import tempfile import unittest +from unittest.mock import patch + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import build # noqa: E402 + +ARCHIVES = ('libdatachannel.a', 'libjuice.a', 'libusrsctp.a', 'libsrtp2.a') class BuildTest(unittest.TestCase): @@ -34,5 +44,84 @@ def test_each_static_library_keeps_its_own_compiler_database(self) -> None: ['webcpp-' + library, str(root / 'persistent symbols')]) +class PublicationTest(unittest.TestCase): + """build() over stand-in commands: what a full build publishes, in which order.""" + + def setUp(self) -> None: + self.directory = tempfile.TemporaryDirectory(prefix='libdatachannel publication ') + self.root = Path(self.directory.name) + self.compiler = self.root / 'compiler/clang++' + self.compiler.parent.mkdir() + for name in ('clang++', 'clang'): + (self.compiler.parent / name).write_text('') + (self.compiler.parent / name).chmod(0o755) + self.openssl = self.root / 'openssl' + (self.openssl / 'include/openssl').mkdir(parents=True) + for name in ('libssl.a', 'libcrypto.a'): + (self.openssl / name).write_bytes(name.encode()) + + def tearDown(self) -> None: + self.directory.cleanup() + + def build(self, output: Path, fail: bool = False) -> list[str]: + """Runs build() for linux, the CMake build raising when fail, and returns the names it + published by replacing, in order.""" + def stage(source: Path, staged: Path, pin: dict) -> None: + (staged / 'include/rtc').mkdir(parents=True) + (staged / 'include/rtc/rtc.hpp').write_text('// rtc\n') + + def command(command: list[str], directory: Path, env: dict, log: Path) -> None: + log.write_text('completed\n') + if command[:2] == ['cmake', '--build']: + if fail: + raise RuntimeError('interrupted build') + (directory / 'build').mkdir(exist_ok=True) + for name in ARCHIVES: + (directory / 'build' / name).write_bytes(name.encode()) + + published = [] + replace = Path.replace + + def publish(path: Path, target: Path) -> Path: + published.append(Path(target).name) + return replace(path, target) + + args = argparse.Namespace(source=self.root / 'source', output=output, + openssl=self.openssl, platform='linux', + cxx=str(self.compiler), variant='release', + headers_only=False, flags=['--cxx-flags']) + with patch.object(build, 'check_checkout'), \ + patch.object(build, 'stage_source', side_effect=stage), \ + patch.object(build, 'provider', return_value={'sha256': {}}), \ + patch.object(build, 'run', side_effect=command), \ + patch.object(Path, 'replace', publish): + build.build(args) + return published + + def test_an_interrupted_build_leaves_no_outputs_of_an_earlier_one(self) -> None: + # B2 keeps a configuration's outputs once they exist (tools/webcpp-third-party.jam): an + # interrupted build must not leave the archives or the record of an earlier one for a + # later build to take as complete. + output = self.root / 'interrupted' + output.mkdir() + for name in (*ARCHIVES, 'build.json'): + (output / name).write_text('published by an earlier build\n') + with self.assertRaisesRegex(RuntimeError, 'interrupted build'): + self.build(output, fail=True) + for name in (*ARCHIVES, 'build.json'): + self.assertFalse((output / name).exists(), name) + + def test_the_build_record_is_published_whole_and_last(self) -> None: + # The build record is what makes a configuration complete: B2 builds one without it + # again (tools/webcpp-libdatachannel.jam), so it is the last output published, replaced + # whole, never written in place. + output = self.root / 'complete' + published = self.build(output) + self.assertEqual(published, [*ARCHIVES, 'build.json']) + record = json.loads((output / 'build.json').read_text()) + self.assertEqual(sorted(record['sha256']), sorted(ARCHIVES)) + self.assertEqual([path.name for path in output.glob('*.new')], []) + + if __name__ == '__main__': unittest.main() diff --git a/tools/lint/lint.sh b/tools/lint/lint.sh index 62ddbcef..d2d11167 100755 --- a/tools/lint/lint.sh +++ b/tools/lint/lint.sh @@ -298,11 +298,22 @@ PYTHON # open-addressing containers include , which it does not have, so it is told to # leave NEON out there and read Boost.Unordered's portable path, on which no analysis of # webcpp's own code depends. + # Nor does it ship the sanitizer interface headers, sanitizer/msan_interface.h and its + # siblings, which a native program built with a sanitizer includes (crypto's + # constant-time lane): when the host compiler's resource directory holds them, it is + # searched after every other directory (-idirafter), so that only what clang-tidy's own + # headers lack, sanitizer/, is read from there. host_target='' host_sysroot='' host_define='' + host_headers='' if [ -n "$(cat "${work_directory}/compiler")" ]; then host_target="$("$(cat "${work_directory}/compiler")" -dumpmachine)" + host_resource="$("$(cat "${work_directory}/compiler")" -print-resource-dir \ + 2>/dev/null || true)" + if [ -n "${host_resource}" ] && [ -d "${host_resource}/include/sanitizer" ]; then + host_headers="${host_resource}/include" + fi if [ "$(uname -s)" = Darwin ] && command -v xcrun >/dev/null 2>&1; then host_sysroot="$(xcrun --show-sdk-path)" fi @@ -329,6 +340,9 @@ PYTHON if [ -n "${host_define}" ]; then arguments+=("--extra-arg=${host_define}") fi + if [ -n "${host_headers}" ]; then + arguments+=(--extra-arg=-idirafter "--extra-arg=${host_headers}") + fi fi local status=0 "${clang_tidy}" --quiet "${arguments[@]}" "${file}" \ @@ -336,7 +350,8 @@ PYTHON printf '%s\n' "${status}" > "${work_directory}/${index}.status" } export -f tidy_one - export clang_tidy host_target host_sysroot host_define work_directory tidy_exclude + export clang_tidy host_target host_sysroot host_define host_headers work_directory \ + tidy_exclude # This shard's slice: the files whose position in the sorted list is K modulo N. # Interleaving keeps the slices alike, since neighbours are alike (the examples of one diff --git a/tools/lint/lint_test.py b/tools/lint/lint_test.py index 5b60cb4c..44fd5d1e 100755 --- a/tools/lint/lint_test.py +++ b/tools/lint/lint_test.py @@ -1070,6 +1070,30 @@ def test_clang_tidy_reads_boost_unordered_on_every_host(root): expect_clean(lint(root)) +def test_clang_tidy_reads_the_host_compiler_s_sanitizer_headers(root): + # A native program that marks memory for MemorySanitizer includes the host compiler's + # sanitizer/ interface headers, which wasi-sdk's clang-tidy does not ship (crypto's + # constant-time lane): the lint finds them in the host compiler's own resource directory, + # after its own headers, and the program analyses clean. + resource = subprocess.run(['clang++', '-print-resource-dir'], capture_output=True, text=True, + check=True).stdout.strip() + assert (Path(resource) / 'include/sanitizer/msan_interface.h').is_file(), resource + prepare(root) + write(root, 'libs/demo/test/marks.cpp', + '// Copyright (c) 2026 WebCpp.org\n//\n' + '// Distributed under the Boost Software License, Version 1.0. (See\n' + '// accompanying file LICENSE_1_0.txt or copy at\n' + '// https://www.boost.org/LICENSE_1_0.txt)\n\n' + '#include \n\n' + '#include \n\n' + 'int main() {\n' + ' std::array value{};\n' + ' __msan_unpoison(value.data(), sizeof value);\n' + ' return value[0];\n}\n') + append(root, 'libs/demo/test/Jamfile', 'webcpp.run marks : marks.cpp : : native ;\n') + expect_clean(lint(root)) + + def test_a_compiled_boost_library_s_sources_are_not_analysed(root): # Boost.URL's sources, which /webcpp//boost_url compiles from Boost's tree outside the tree # the lint reads (.local/boost-source, or a CI runner's prefix), are Boost's: the database @@ -2884,6 +2908,7 @@ def test_wasip3_abi_snapshot_requires_integrity_before_style_exemption(root): test_clang_tidy_reads_a_program_of_javascript_exceptions, test_a_dependency_s_warnings_are_not_ours, test_clang_tidy_reads_boost_unordered_on_every_host, + test_clang_tidy_reads_the_host_compiler_s_sanitizer_headers, test_a_compiled_boost_library_s_sources_are_not_analysed, test_clang_tidy_uses_shipped_cobalt_sources_on_a_clean_tree, test_clang_tidy_refuses_a_throw_on_each_target_without_exceptions, diff --git a/tools/openssl/build.py b/tools/openssl/build.py index 638d9d52..14de342e 100644 --- a/tools/openssl/build.py +++ b/tools/openssl/build.py @@ -143,8 +143,12 @@ def main() -> None: 'WASI uses the separately declared TLS integration tests') source, output = args.source.resolve(), args.output.resolve() output.mkdir(parents=True, exist_ok=True) - for name in ('build.json', 'upstream-tests.json'): - (output / name).unlink(missing_ok=True) + if not args.headers_only: + # B2 keeps a configuration's outputs once they exist, and builds it again only when one + # is missing (tools/webcpp-openssl.jam): the build record, published last, is what makes + # it complete. Remove it first, with what an earlier, interrupted build published. + for name in ('build.json', 'upstream-tests.json', *archive_names(args.platform)): + (output / name).unlink(missing_ok=True) pin = json.loads((HERE / 'pin.json').read_text()) check_checkout(source, pin) # Verify the source before probing or invoking any configured build tool. @@ -307,7 +311,7 @@ def build_source(args: argparse.Namespace, output: Path, pin: dict, scratch: Pat # generated headers and archives, without the unrelated exporters. copy_headers(scratch / 'source', build, install / 'include/openssl', windows) (install / 'lib').mkdir() - for name in ('libssl.lib', 'libcrypto.lib'): + for name in archive_names(args.platform): shutil.copyfile(build / name, install / 'lib' / name) symbols = build / 'ossl_static.pdb' if symbols.is_file(): @@ -320,7 +324,7 @@ def build_source(args: argparse.Namespace, output: Path, pin: dict, scratch: Pat # Publish any changed headers atomically before making archives available. shutil.copytree(install / 'include', output / 'include', dirs_exist_ok=True, copy_function=publish_header) - names = ('libssl.lib', 'libcrypto.lib') if windows else ('libssl.a', 'libcrypto.a') + names = archive_names(args.platform) for name in names: staged = output / (name + '.new') shutil.copyfile(install / 'lib' / name, staged) @@ -328,16 +332,32 @@ def build_source(args: argparse.Namespace, output: Path, pin: dict, scratch: Pat record['seconds'] = time.monotonic() - started record['sha256'] = {name: hashlib.sha256((output / name).read_bytes()).hexdigest() for name in names} - (output / 'build.json').write_text(json.dumps(record, indent=2) + '\n') if suite: suite.update(pin=pin['commit'], configure=record['configure'], sha256=record['sha256']) - (output / 'upstream-tests.json').write_text(json.dumps(suite, indent=2) + '\n') + publish_record(suite, output / 'upstream-tests.json') + # The last output: a configuration with it is complete, and kept. + publish_record(record, output / 'build.json') + if suite: print(f'OpenSSL upstream suite passed: {suite["files"]} recipes, ' f'{suite["tests"]} tests', flush=True) print(f'OpenSSL {pin["version"]}: {args.platform}/{args.threading} built from source ' f'in {record["seconds"]:.1f}s', flush=True) +def archive_names(platform: str) -> tuple[str, str]: + """The archives a build publishes for platform.""" + if platform == 'windows': + return ('libssl.lib', 'libcrypto.lib') + return ('libssl.a', 'libcrypto.a') + + +def publish_record(record: dict, destination: Path) -> None: + """Publish record as JSON at destination whole: an interruption leaves none, never part.""" + staged = destination.with_name(destination.name + '.new') + staged.write_text(json.dumps(record, indent=2) + '\n') + staged.replace(destination) + + def copy_headers(source: Path, build: Path, output: Path, windows: bool) -> list[Path]: """Publish the public headers in upstream install_dev's source/generated order.""" output.mkdir(parents=True, exist_ok=True) diff --git a/tools/openssl/build_test.py b/tools/openssl/build_test.py index 37bf307e..f103be46 100644 --- a/tools/openssl/build_test.py +++ b/tools/openssl/build_test.py @@ -222,7 +222,7 @@ def setUp(self) -> None: (self.source / 'ms').mkdir() (self.source / 'ms/applink.c').write_bytes(data) (self.root / 'msvc.conf').write_text('# configuration fixture\n') - self.pin = {'version': 'fixture', 'source_date_epoch': 1700000000, + self.pin = {'version': 'fixture', 'commit': 'fixture', 'source_date_epoch': 1700000000, 'omitted_submodules': {}, 'executable_files': [], 'source_sha256': inventory_digest([ (name, '100644', hashlib.sha256(data).hexdigest()) @@ -321,6 +321,66 @@ def command(command: list[str], *, cwd: Path, env: dict, log: Path, for name in ('libssl.lib', 'libcrypto.lib', 'build.json', 'upstream-tests.json'): self.assertFalse((output / name).exists(), name) + def build(self, output: Path, fail: str = '') -> list[str]: + """Runs main with --test over stand-in commands, the one named fail raising, and + returns the names it published, in order.""" + def command(command: list[str], *, cwd: Path, env: dict, log: Path, + timeout: float = 600) -> None: + log.write_text('completed\n') + if command[-1] == fail: + raise RuntimeError('interrupted ' + fail) + if command[-1] == 'build_libs': + (cwd / 'include/openssl').mkdir(parents=True) + (cwd / 'include/openssl/configuration.h').write_text('matching headers\n') + (cwd / 'libssl.lib').write_bytes(b'ssl') + (cwd / 'libcrypto.lib').write_bytes(b'crypto') + + published = [] + replace = Path.replace + + def publish(path: Path, target: Path) -> Path: + published.append(Path(target).name) + return replace(path, target) + + args = ['build.py', '--source', str(self.source), '--output', str(output), + '--platform', 'windows', '--threading', 'multi', '--cc', str(self.compiler), + '--test'] + with patch.object(build, 'HERE', self.root), patch.object(sys, 'argv', args), \ + patch.object(build, 'run', side_effect=command), \ + patch.object(build, 'windows_target', return_value='VC-WIN64A'), \ + patch.object(build, 'windows_perl', return_value='native-perl.exe'), \ + patch.object(build, 'suite_result', + return_value={'result': 'passed', 'files': 1, 'tests': 1}), \ + patch.object(Path, 'replace', publish): + build.main() + return published + + def test_an_interrupted_build_leaves_no_outputs_of_an_earlier_one(self) -> None: + # B2 keeps a configuration's outputs once they exist (tools/webcpp-openssl.jam): an + # interrupted build must not leave the archives of an earlier interrupted one, whose + # build record it removed, for a later build to take as complete. + output = self.root / 'interrupted' + output.mkdir() + for name in ('libssl.lib', 'libcrypto.lib', 'build.json', 'upstream-tests.json'): + (output / name).write_text('published by an interrupted build\n') + with self.assertRaisesRegex(RuntimeError, 'interrupted build_libs'): + self.build(output, fail='build_libs') + for name in ('libssl.lib', 'libcrypto.lib', 'build.json', 'upstream-tests.json'): + self.assertFalse((output / name).exists(), name) + + def test_the_build_record_is_published_whole_and_last(self) -> None: + # The build record is what makes a configuration complete: B2 builds one without it + # again, so it is the last output published, replaced whole, never written in place. + output = self.root / 'complete' + published = self.build(output) + self.assertEqual(published[-1], 'build.json', published) + self.assertEqual([name for name in published if name not in ('configuration.h', + 'applink.c')], + ['libssl.lib', 'libcrypto.lib', 'upstream-tests.json', 'build.json']) + self.assertEqual(json.loads((output / 'build.json').read_text())['sha256'], + json.loads((output / 'upstream-tests.json').read_text())['sha256']) + self.assertEqual([path.name for path in output.glob('*.new')], []) + def test_windows_target_uses_the_configured_compilers_architecture(self) -> None: for output, target in (('WEBCPP_OPENSSL_X86', 'VC-WIN32'), ('WEBCPP_OPENSSL_X64', 'VC-WIN64A'), diff --git a/tools/test/crypto_collect_test.py b/tools/test/crypto_collect_test.py new file mode 100644 index 00000000..bff46d4f --- /dev/null +++ b/tools/test/crypto_collect_test.py @@ -0,0 +1,160 @@ +#!/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/crypto/bench/collect.py, which measures bench/throughput 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 +anything runs or is written; one at variant=release is taken (it gets as far as running); a cell +whose operation is not the one doc/tables/crypto.json states for its family is refused; and +`--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 the page always states the load it was +measured under, warning above half the cores. Run with the names of some cases to run only +those.""" + +from __future__ import annotations + +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/crypto/bench/collect.py' +DATA = ROOT / 'libs/crypto/doc/performance.json' +PAGE = ROOT / 'libs/crypto/doc/performance.adoc' + + +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, script: str) -> Path: + """A stand-in of bench/throughput where b2 builds it at variant, running script.""" + path = scratch / 'bin/libs/crypto/bench/clang-darwin-21' / variant / 'cxxstd-20-iso/throughput' + path.parent.mkdir(parents=True) + path.write_text('#!/bin/sh\n' + script) + 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}') + + +FAILS = 'echo "the stand-in ran" >&2\nexit 3\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, FAILS) + done = run('--exe', f'native={exe}', '--data', data, '--page', page) + expect(done, 1, f'native={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/throughput' + stray.parent.mkdir() + stray.write_text('') + done = run('--exe', f'wasip2={stray}', '--data', data, '--page', page) + expect(done, 1, f'wasip2={stray}', 'bench//', 'only from release builds') + + +def test_a_program_built_at_variant_release_is_measured(scratch: Path) -> None: + exe = program(scratch, 'release', FAILS) + done = run('--exe', f'native={exe}', '--data', scratch / 'data.json', '--page', + scratch / 'page.adoc') + # Past the check, collect.py runs it, and stops on its failure. + expect(done, 1, 'native --list: exit 3', 'the stand-in ran') + + +def test_an_operation_crypto_json_does_not_state_is_refused(scratch: Path) -> None: + line = json.dumps({'family': 'x25519', 'backend': 'sodium', 'operation': 'something else', + 'target': 'native', 'compiler': 'clang', 'repetitions': 1, + 'runs_us': [1.0], 'median_us': 1.0}) + exe = program(scratch, 'release', 'if [ "$1" = --list ]; then echo "x25519 sodium"; ' + f"else echo '{line}'; fi\n") + data, page = scratch / 'data.json', scratch / 'page.adoc' + done = run('--exe', f'native={exe}', '--invocations', '1', '--data', data, '--page', page) + expect(done, 1, "native x25519 sodium measures 'something else', and crypto.json states " + "'agreement of a secret key and a public key'") + if data.exists() or page.exists(): + raise AssertionError('a file was written') + + +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', None): + data = dict(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_page_states_the_load_and_warns_above_half_the_cores(scratch: Path) -> None: + # The page always prints the load averages it was measured under, and warns when the larger + # 1-minute load exceeds half the cores: a shared machine's spread, not its figures. + committed = json.loads(DATA.read_text()) + page = scratch / 'page.adoc' + cores = committed['machine']['cores'] + for one_minute, warned in ((cores / 2 + 1, True), (cores / 2 - 1, False)): + data = dict(committed) + data['load_average_before_after'] = [[one_minute, 1.0, 1.0], [1.0, 1.0, 1.0]] + path = scratch / 'data.json' + path.write_text(json.dumps(data)) + expect(run('--render-only', '--data', path, '--page', page), 0) + text = page.read_text() + if 'load averages' not in text or ('WARNING' in text) != warned: + raise AssertionError(f'{one_minute} on {cores} cores:\n{text}') + + +CASES: list[Callable[[Path], None]] = [ + test_a_program_not_built_at_variant_release_is_refused, + test_a_program_built_at_variant_release_is_measured, + test_an_operation_crypto_json_does_not_state_is_refused, + test_render_only_refuses_data_not_built_at_variant_release, + test_the_page_states_the_load_and_warns_above_half_the_cores, +] + + +def main(argv: list[str]) -> int: + unknown = set(argv) - {case.__name__ for case in CASES} + if unknown: + print(f'crypto_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 crypto collect ') as scratch: + case(Path(scratch)) + print(f'{case.__name__}: ok') + print('crypto_collect_test: ok') + return 0 + + +if __name__ == '__main__': + sys.exit(main(sys.argv[1:])) diff --git a/tools/test/crypto_jamfiles_test.py b/tools/test/crypto_jamfiles_test.py index cb478886..3f0e7872 100644 --- a/tools/test/crypto_jamfiles_test.py +++ b/tools/test/crypto_jamfiles_test.py @@ -30,7 +30,7 @@ def main(argv: list[str]) -> int: - return user_jamfiles.main('crypto_jamfiles', CASES, ('config', 'crypto'), NOT_YET, argv) + return user_jamfiles.main('crypto_jamfiles', CASES, ('config', 'crypto', 'hash'), NOT_YET, argv) if __name__ == '__main__': diff --git a/tools/test/fixtures/crypto_jamfiles/aead_not_a_family_on_emscripten/Jamfile b/tools/test/fixtures/crypto_jamfiles/aead_not_a_family_on_emscripten/Jamfile new file mode 100644 index 00000000..014a3e61 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/aead_not_a_family_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/crypto//crypto /third_party//sodium ; +# end::jamfile[] diff --git a/tools/test/fixtures/crypto_jamfiles/aead_not_a_family_on_emscripten/aead_not_a_family_on_emscripten.outcome b/tools/test/fixtures/crypto_jamfiles/aead_not_a_family_on_emscripten/aead_not_a_family_on_emscripten.outcome new file mode 100644 index 00000000..640f96ae --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/aead_not_a_family_on_emscripten/aead_not_a_family_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 static_assert starts with the header's path on the machine, so the +# message is a contains: line. Natively and on wasip2 and wasip3 the same message is a +# compile-diagnostic (test/messages/aead_not_a_family); compile-diagnostic is clang's and skips +# Emscripten, so this fixture is the Emscripten one. +[all] +targets: emscripten +build: fails +# tag::messages[] +contains: webcpp::crypto: ciphers::aead takes an AEAD family: families::chacha20_poly1305, families::chacha20_poly1305_original, families::xchacha20_poly1305, families::secretbox_xsalsa20poly1305 or families::secretbox_xchacha20poly1305. +# end::messages[] diff --git a/tools/test/fixtures/crypto_jamfiles/aead_not_a_family_on_emscripten/app.cpp b/tools/test/fixtures/crypto_jamfiles/aead_not_a_family_on_emscripten/app.cpp new file mode 100644 index 00000000..5a12fa21 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/aead_not_a_family_on_emscripten/app.cpp @@ -0,0 +1,19 @@ +// 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 for Emscripten that gives ciphers::aead a family that is no AEAD's, AES-GCM's. +#include +#include + +#include +#include + +int main() { + namespace crypto = webcpp::crypto; + using aead = crypto::ciphers::aead; + std::array const key{}; + return aead::make(key) ? 0 : 1; +} diff --git a/tools/test/fixtures/crypto_jamfiles/both_bearssl_default/Jamfile b/tools/test/fixtures/crypto_jamfiles/both_bearssl_named/Jamfile similarity index 79% rename from tools/test/fixtures/crypto_jamfiles/both_bearssl_default/Jamfile rename to tools/test/fixtures/crypto_jamfiles/both_bearssl_named/Jamfile index 9f90a9fe..46cc8212 100644 --- a/tools/test/fixtures/crypto_jamfiles/both_bearssl_default/Jamfile +++ b/tools/test/fixtures/crypto_jamfiles/both_bearssl_named/Jamfile @@ -5,6 +5,5 @@ # https://www.boost.org/LICENSE_1_0.txt) # tag::jamfile[] -exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//openssl /third_party//bearssl - : WEBCPP_CRYPTO_DEFAULT_BACKEND_BEARSSL ; +exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//openssl /third_party//bearssl ; # end::jamfile[] diff --git a/tools/test/fixtures/crypto_jamfiles/both_bearssl_named/app.cpp b/tools/test/fixtures/crypto_jamfiles/both_bearssl_named/app.cpp new file mode 100644 index 00000000..64319067 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/both_bearssl_named/app.cpp @@ -0,0 +1,50 @@ +// 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) + +// Seals one zero block under AES-256-GCM on BearSSL, named in the type where OpenSSL, linked +// too, is the default natively, and checks it against the GCM specification's test case 14 (key, +// IV and plaintext all zero), then opens it again, and prints the backend that ran. The zero key +// and IV are the test vector's: a real program draws its key from random_device and never reuses +// an IV under it. +#include +#include +#include +#include + +#include +#include +#include + +namespace crypto = webcpp::crypto; + +// AES-256-GCM on BearSSL, named in the type. +using aead_type = crypto::ciphers::gcm>; + +int main() { + std::array const key{}; + std::array const iv{}; + std::array data{}; + std::array const cipher{ + 0xce, 0xa7, 0x40, 0x3d, 0x4d, 0x60, 0x6b, 0x6e, + 0x07, 0x4e, 0xc5, 0xd3, 0xba, 0xf3, 0x9d, 0x18, + }; + std::array const expected_tag{ + 0xd0, 0xd1, 0xc8, 0xa7, 0x99, 0x99, 0x6b, 0xf0, + 0x26, 0x5b, 0x98, 0xb5, 0xd4, 0x8a, 0xb9, 0x19, + }; + auto aead = aead_type::make(key); + if (!aead) { + return 1; + } + auto const tag = aead->seal(iv, {}, data); + bool const sealed = tag && data == cipher && webcpp::crypto::equal(*tag, expected_tag); + bool const opened = + aead->open(iv, {}, data, expected_tag) && data == std::array{}; + auto const name = aead_type::backend_type::name; + std::printf("aes256_gcm %s backend=%.*s\n", sealed && opened ? "ok" : "FAILED", + static_cast(name.size()), name.data()); + return sealed && opened ? 0 : 1; +} diff --git a/tools/test/fixtures/crypto_jamfiles/both_bearssl_default/both_bearssl_default.outcome b/tools/test/fixtures/crypto_jamfiles/both_bearssl_named/both_bearssl_named.outcome similarity index 91% rename from tools/test/fixtures/crypto_jamfiles/both_bearssl_default/both_bearssl_default.outcome rename to tools/test/fixtures/crypto_jamfiles/both_bearssl_named/both_bearssl_named.outcome index 9caa81fa..65666989 100644 --- a/tools/test/fixtures/crypto_jamfiles/both_bearssl_default/both_bearssl_default.outcome +++ b/tools/test/fixtures/crypto_jamfiles/both_bearssl_named/both_bearssl_named.outcome @@ -6,7 +6,6 @@ [all] targets: native wasip2 wasip3 -same-as: web/app.cpp app.cpp build: succeeds run: app # tag::output[] diff --git a/tools/test/fixtures/crypto_jamfiles/box_default_not_linked_on_emscripten/Jamfile b/tools/test/fixtures/crypto_jamfiles/box_default_not_linked_on_emscripten/Jamfile new file mode 100644 index 00000000..4b12ef4a --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/box_default_not_linked_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/crypto//crypto ; +# end::jamfile[] diff --git a/tools/test/fixtures/crypto_jamfiles/box_default_not_linked_on_emscripten/app.cpp b/tools/test/fixtures/crypto_jamfiles/box_default_not_linked_on_emscripten/app.cpp new file mode 100644 index 00000000..ff84d5d4 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/box_default_not_linked_on_emscripten/app.cpp @@ -0,0 +1,27 @@ +// 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) + +// As test/messages/box_default_not_linked, on Emscripten. + +#include +#include +#include + +#include +#include + +int main() { + namespace crypto = webcpp::crypto; + std::array const key{}; + std::array sealed{}; + return crypto::ciphers::secretbox<>::make(key) && + crypto::ciphers::secretbox_xchacha20poly1305<>::make(key) && + crypto::hybrid::box::make(key, key) && + crypto::hybrid::box_xchacha20poly1305::make(key, key) && + crypto::hybrid::sealed_box::seal(key, {}, sealed) + ? 0 + : 1; +} diff --git a/tools/test/fixtures/crypto_jamfiles/box_default_not_linked_on_emscripten/box_default_not_linked_on_emscripten.outcome b/tools/test/fixtures/crypto_jamfiles/box_default_not_linked_on_emscripten/box_default_not_linked_on_emscripten.outcome new file mode 100644 index 00000000..87e5da19 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/box_default_not_linked_on_emscripten/box_default_not_linked_on_emscripten.outcome @@ -0,0 +1,20 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +# 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/box_default_not_linked); compile-diagnostic is clang's and skips Emscripten, so +# this fixture is the Emscripten one. +[all] +targets: emscripten +build: fails +# tag::messages[] +contains: webcpp::crypto: XSalsa20-Poly1305 secret box's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /webcpp/crypto//secretbox_xsalsa20poly1305-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//secretbox_xsalsa20poly1305-default ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c) +contains: webcpp::crypto: XChaCha20-Poly1305 secret box's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /webcpp/crypto//secretbox_xchacha20poly1305-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//secretbox_xchacha20poly1305-default ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c) +contains: webcpp::crypto: X25519-XSalsa20-Poly1305 box's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /webcpp/crypto//box_xsalsa20poly1305-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//box_xsalsa20poly1305-default ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c) +contains: webcpp::crypto: X25519-XChaCha20-Poly1305 box's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /webcpp/crypto//box_xchacha20poly1305-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//box_xchacha20poly1305-default ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c) +contains: webcpp::crypto: X25519-XSalsa20-Poly1305 sealed box's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /webcpp/crypto//sealed_box-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//sealed_box-default ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c) +# end::messages[] diff --git a/tools/test/fixtures/crypto_jamfiles/box_not_a_family_on_emscripten/Jamfile b/tools/test/fixtures/crypto_jamfiles/box_not_a_family_on_emscripten/Jamfile new file mode 100644 index 00000000..4b12ef4a --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/box_not_a_family_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/crypto//crypto ; +# end::jamfile[] diff --git a/tools/test/fixtures/crypto_jamfiles/box_not_a_family_on_emscripten/app.cpp b/tools/test/fixtures/crypto_jamfiles/box_not_a_family_on_emscripten/app.cpp new file mode 100644 index 00000000..3e263b23 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/box_not_a_family_on_emscripten/app.cpp @@ -0,0 +1,24 @@ +// 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) + +// As test/messages/box_not_a_family, on Emscripten. + +#include + +#include +#include + +namespace { + +/** A type that names no family, and so has no default backend. */ +struct not_a_family {}; + +} // namespace + +int main() { + std::array const key{}; + return webcpp::crypto::hybrid::basic_box::make(key, key) ? 0 : 1; +} diff --git a/tools/test/fixtures/crypto_jamfiles/box_not_a_family_on_emscripten/box_not_a_family_on_emscripten.outcome b/tools/test/fixtures/crypto_jamfiles/box_not_a_family_on_emscripten/box_not_a_family_on_emscripten.outcome new file mode 100644 index 00000000..0f59b244 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/box_not_a_family_on_emscripten/box_not_a_family_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/box_not_a_family); compile-diagnostic is clang's and skips Emscripten, so this +# fixture is the Emscripten one. +[all] +targets: emscripten +build: fails +# tag::messages[] +contains: webcpp::crypto: hybrid::basic_box takes a box family: families::box_xsalsa20poly1305 or families::box_xchacha20poly1305. +# end::messages[] diff --git a/tools/test/fixtures/crypto_jamfiles/box_xchacha20poly1305_default/Jamfile b/tools/test/fixtures/crypto_jamfiles/box_xchacha20poly1305_default/Jamfile new file mode 100644 index 00000000..72fa56a7 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/box_xchacha20poly1305_default/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/crypto//crypto /webcpp/crypto//box_xchacha20poly1305-default ; +# end::jamfile[] diff --git a/tools/test/fixtures/crypto_jamfiles/box_xchacha20poly1305_default/app.cpp b/tools/test/fixtures/crypto_jamfiles/box_xchacha20poly1305_default/app.cpp new file mode 100644 index 00000000..1047963b --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/box_xchacha20poly1305_default/app.cpp @@ -0,0 +1,71 @@ +// 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) + +// Seals NaCl's message from Alice to Bob in the XChaCha20 box on the default backend, +// checks the tag and the ciphertext's first bytes against those libsodium's own test suite +// does not print and an independent implementation computed, opens it with Bob's keys, and +// prints the backend that ran. The keys and nonce are NaCl's test's. +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace { + +// The bytes of a string of lower-case hex digits, two per byte. +template +std::array from_hex(std::string_view hex) { + std::array bytes{}; + for (std::size_t index = 0; index < Size; ++index) { + auto const digit = [&](std::size_t at) { + char const c = hex[at]; + return static_cast(c <= '9' ? c - '0' : c - 'a' + 10); + }; + bytes[index] = static_cast((digit(2 * index) << 4U) | digit((2 * index) + 1)); + } + return bytes; +} + +} // namespace + +int main() { + using box = webcpp::crypto::hybrid::box_xchacha20poly1305; + auto const alice_secret = + from_hex<32>("77076d0a7318a57d3c16c17251b26645df4c2f87ebc0992ab177fba51db92c2a"); + auto const alice_public = + from_hex<32>("8520f0098930a754748b7ddcb43ef75a0dbf3a0d26381af4eba4a98eaa9b4e6a"); + auto const bob_secret = + from_hex<32>("5dab087e624a8a4b79e17f8b83800ee66f3bb1292618b6fd1c2f8b27ff88e0eb"); + auto const bob_public = + from_hex<32>("de9edb7d7b7dc1b4d35b61c2ece435373f8343c85b78674dadfc7e146f882b4f"); + auto const iv = from_hex<24>("69696ee955b62b73cd62bda875fc73d68219e0036b7a0b37"); + auto const plaintext = from_hex<131>( + "be075fc53c81f2d5cf141316ebeb0c7b5228c52a4c62cbd44b66849b64244ffce5ecbaaf33bd751a1ac7" + "28d45e6c61296cdc3c01233561f41db66cce314adb310e3be8250c46f06dceea3a7fa1348057e2f6556a" + "d6b1318a024a838f21af1fde048977eb48f59ffd4924ca1c60902e52f0a089bc76897040e082f9377638" + "48645e0705"); + auto const expected_tag = from_hex<16>("0b4ff00742f3c1aa99a6321e3883b03c"); + auto const expected_head = from_hex<8>("ef2c6061b7bcec0c"); + auto data = plaintext; + auto alice = box::make(alice_secret, bob_public); + auto bob = box::make(bob_secret, alice_public); + bool ok = false; + if (alice && bob) { + auto const sealed = alice->seal(iv, data); + ok = sealed && webcpp::crypto::equal(*sealed, expected_tag) && + std::equal(expected_head.begin(), expected_head.end(), data.begin()) && + bob->open(iv, data, *sealed) && data == plaintext; + } + auto const name = box::backend_type::name; + std::printf("box_xchacha20poly1305 %s backend=%.*s\n", ok ? "ok" : "FAILED", + static_cast(name.size()), name.data()); + return ok ? 0 : 1; +} diff --git a/tools/test/fixtures/crypto_jamfiles/box_xchacha20poly1305_default/box_xchacha20poly1305_default.outcome b/tools/test/fixtures/crypto_jamfiles/box_xchacha20poly1305_default/box_xchacha20poly1305_default.outcome new file mode 100644 index 00000000..85d93358 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/box_xchacha20poly1305_default/box_xchacha20poly1305_default.outcome @@ -0,0 +1,20 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +[all] +targets: native wasip2 wasip3 emscripten +build: succeeds +run: app +# tag::output[] +[native] +box_xchacha20poly1305 ok backend=sodium +[wasip2] +box_xchacha20poly1305 ok backend=sodium +[wasip3] +box_xchacha20poly1305 ok backend=sodium +[emscripten] +box_xchacha20poly1305 ok backend=sodium +# end::output[] diff --git a/tools/test/fixtures/crypto_jamfiles/box_xsalsa20poly1305_default/Jamfile b/tools/test/fixtures/crypto_jamfiles/box_xsalsa20poly1305_default/Jamfile new file mode 100644 index 00000000..772e85f5 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/box_xsalsa20poly1305_default/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/crypto//crypto /webcpp/crypto//box_xsalsa20poly1305-default ; +# end::jamfile[] diff --git a/tools/test/fixtures/crypto_jamfiles/box_xsalsa20poly1305_default/app.cpp b/tools/test/fixtures/crypto_jamfiles/box_xsalsa20poly1305_default/app.cpp new file mode 100644 index 00000000..2d721847 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/box_xsalsa20poly1305_default/app.cpp @@ -0,0 +1,71 @@ +// 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) + +// Seals NaCl's box (libsodium's test/default/box.c) from Alice to Bob on the default +// backend, checks the tag and the ciphertext's first bytes against box.exp, opens it with Bob's +// keys (box2.c), and prints the backend that ran. The keys and nonce are the test's: a real +// program draws its secret key from random_device, and a nonce at random for every message. +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace { + +// The bytes of a string of lower-case hex digits, two per byte. +template +std::array from_hex(std::string_view hex) { + std::array bytes{}; + for (std::size_t index = 0; index < Size; ++index) { + auto const digit = [&](std::size_t at) { + char const c = hex[at]; + return static_cast(c <= '9' ? c - '0' : c - 'a' + 10); + }; + bytes[index] = static_cast((digit(2 * index) << 4U) | digit((2 * index) + 1)); + } + return bytes; +} + +} // namespace + +int main() { + using webcpp::crypto::hybrid::box; + auto const alice_secret = + from_hex<32>("77076d0a7318a57d3c16c17251b26645df4c2f87ebc0992ab177fba51db92c2a"); + auto const alice_public = + from_hex<32>("8520f0098930a754748b7ddcb43ef75a0dbf3a0d26381af4eba4a98eaa9b4e6a"); + auto const bob_secret = + from_hex<32>("5dab087e624a8a4b79e17f8b83800ee66f3bb1292618b6fd1c2f8b27ff88e0eb"); + auto const bob_public = + from_hex<32>("de9edb7d7b7dc1b4d35b61c2ece435373f8343c85b78674dadfc7e146f882b4f"); + auto const iv = from_hex<24>("69696ee955b62b73cd62bda875fc73d68219e0036b7a0b37"); + auto const plaintext = from_hex<131>( + "be075fc53c81f2d5cf141316ebeb0c7b5228c52a4c62cbd44b66849b64244ffce5ecbaaf33bd751a1ac7" + "28d45e6c61296cdc3c01233561f41db66cce314adb310e3be8250c46f06dceea3a7fa1348057e2f6556a" + "d6b1318a024a838f21af1fde048977eb48f59ffd4924ca1c60902e52f0a089bc76897040e082f9377638" + "48645e0705"); + auto const expected_tag = from_hex<16>("f3ffc7703f9400e52a7dfb4b3d3305d9"); + auto const expected_head = from_hex<8>("8e993b9f48681273"); + auto data = plaintext; + auto alice = box::make(alice_secret, bob_public); + auto bob = box::make(bob_secret, alice_public); + bool ok = false; + if (alice && bob) { + auto const sealed = alice->seal(iv, data); + ok = sealed && webcpp::crypto::equal(*sealed, expected_tag) && + std::equal(expected_head.begin(), expected_head.end(), data.begin()) && + bob->open(iv, data, *sealed) && data == plaintext; + } + auto const name = box::backend_type::name; + std::printf("box %s backend=%.*s\n", ok ? "ok" : "FAILED", static_cast(name.size()), + name.data()); + return ok ? 0 : 1; +} diff --git a/tools/test/fixtures/crypto_jamfiles/box_xsalsa20poly1305_default/box_xsalsa20poly1305_default.outcome b/tools/test/fixtures/crypto_jamfiles/box_xsalsa20poly1305_default/box_xsalsa20poly1305_default.outcome new file mode 100644 index 00000000..b99f8925 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/box_xsalsa20poly1305_default/box_xsalsa20poly1305_default.outcome @@ -0,0 +1,20 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +[all] +targets: native wasip2 wasip3 emscripten +build: succeeds +run: app +# tag::output[] +[native] +box ok backend=sodium +[wasip2] +box ok backend=sodium +[wasip3] +box ok backend=sodium +[emscripten] +box ok backend=sodium +# end::output[] diff --git a/tools/test/fixtures/crypto_jamfiles/canary_sodium_other_commit/Jamfile b/tools/test/fixtures/crypto_jamfiles/canary_sodium_other_commit/Jamfile new file mode 100644 index 00000000..e69e225d --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/canary_sodium_other_commit/Jamfile @@ -0,0 +1,11 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +# libsodium linked, the program built for another commit of it. +# tag::jamfile[] +exe app : app.cpp /webcpp/crypto//crypto /third_party//sodium + : WEBCPP_CRYPTO_SODIUM_CANARY_COMMIT=0000000 ; +# end::jamfile[] diff --git a/tools/test/fixtures/crypto_jamfiles/canary_sodium_other_commit/app.cpp b/tools/test/fixtures/crypto_jamfiles/canary_sodium_other_commit/app.cpp new file mode 100644 index 00000000..11588a4e --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/canary_sodium_other_commit/app.cpp @@ -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) + +// Initialises libsodium through the backend's header, which reads libsodium's canary: the program +// names another commit than the library was built for, so that a library built other than by +// webcpp's third_party/Jamfile fails to link. +#include + +int main() { + return webcpp::crypto::detail::sodium_ready() ? 0 : 1; +} diff --git a/tools/test/fixtures/crypto_jamfiles/canary_sodium_other_commit/canary_sodium_other_commit.outcome b/tools/test/fixtures/crypto_jamfiles/canary_sodium_other_commit/canary_sodium_other_commit.outcome new file mode 100644 index 00000000..41cbd927 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/canary_sodium_other_commit/canary_sodium_other_commit.outcome @@ -0,0 +1,27 @@ +# 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) + +[all] +targets: native wasip2 wasip3 emscripten +build: fails +# tag::messages[] +[native-darwin] +contains: Undefined symbols for architecture +contains: _webcpp_crypto_sodium_0000000_portable__add_third_party_sodium_to_your_link +[native-linux] +contains: webcpp_crypto_sodium_0000000_portable__add_third_party_sodium_to_your_link +contains: undefined reference to `webcpp_crypto_sodium_0000000_portable__add_third_party_sodium_to_your_link' +[wasip2] +contains: wasm-ld: error: +contains: undefined symbol: webcpp_crypto_sodium_0000000_portable__add_third_party_sodium_to_your_link +[wasip3] +contains: wasm-ld: error: +contains: undefined symbol: webcpp_crypto_sodium_0000000_portable__add_third_party_sodium_to_your_link +[emscripten] +contains: wasm-ld: error: +contains: undefined symbol: webcpp_crypto_sodium_0000000_portable__add_third_party_sodium_to_your_link +contains: em++: error: +# end::messages[] diff --git a/tools/test/fixtures/crypto_jamfiles/chacha20_poly1305_default/Jamfile b/tools/test/fixtures/crypto_jamfiles/chacha20_poly1305_default/Jamfile new file mode 100644 index 00000000..71d26261 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/chacha20_poly1305_default/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/crypto//crypto /webcpp/crypto//chacha20_poly1305-default ; +# end::jamfile[] diff --git a/tools/test/fixtures/crypto_jamfiles/chacha20_poly1305_default/app.cpp b/tools/test/fixtures/crypto_jamfiles/chacha20_poly1305_default/app.cpp new file mode 100644 index 00000000..35709070 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/chacha20_poly1305_default/app.cpp @@ -0,0 +1,58 @@ +// 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) + +// Seals RFC 8439's ChaCha20-Poly1305 example (section 2.8.2) on the default backend, checks the +// tag and the ciphertext's first bytes against the RFC's, opens it again, and prints the backend +// 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 +#include +#include +#include + +int main() { + using aead = webcpp::crypto::ciphers::chacha20_poly1305<>; + // The key 0x80, 0x81, ..., 0x9f. + std::array key{}; + for (std::size_t index = 0; index < key.size(); ++index) { + key[index] = static_cast(0x80 + index); + } + // NOLINTBEGIN(readability-trailing-comma): it asks a list of one row, wrapped, for the comma + // and refuses it once clang-format puts the brace on a line of its own + std::array const iv{0x07, 0x00, 0x00, 0x00, 0x40, 0x41, + 0x42, 0x43, 0x44, 0x45, 0x46, 0x47}; + std::array const additional_data{0x50, 0x51, 0x52, 0x53, 0xc0, 0xc1, + 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7}; + // NOLINTEND(readability-trailing-comma) + constexpr std::string_view sunscreen = + "Ladies and Gentlemen of the class of '99: If I could offer you only one tip for the " + "future, sunscreen would be it."; + std::array plaintext{}; + std::ranges::copy(sunscreen, plaintext.begin()); + auto data = plaintext; + std::array const expected_tag{ + 0x1a, 0xe1, 0x0b, 0x59, 0x4f, 0x09, 0xe2, 0x6a, + 0x7e, 0x90, 0x2e, 0xcb, 0xd0, 0x60, 0x06, 0x91, + }; + std::array const expected_head{0xd3, 0x1a, 0x8d, 0x34, 0x64, 0x8e, 0x60, 0xdb}; + auto sealer = aead::make(key); + bool ok = false; + if (sealer) { + auto const tag = sealer->seal(iv, additional_data, data); + ok = tag && webcpp::crypto::equal(*tag, expected_tag) && + std::equal(expected_head.begin(), expected_head.end(), data.begin()) && + sealer->open(iv, additional_data, data, expected_tag) && data == plaintext; + } + auto const name = aead::backend_type::name; + std::printf("chacha20_poly1305 %s backend=%.*s\n", ok ? "ok" : "FAILED", + static_cast(name.size()), name.data()); + return ok ? 0 : 1; +} diff --git a/tools/test/fixtures/crypto_jamfiles/chacha20_poly1305_default/chacha20_poly1305_default.outcome b/tools/test/fixtures/crypto_jamfiles/chacha20_poly1305_default/chacha20_poly1305_default.outcome new file mode 100644 index 00000000..7baa64d0 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/chacha20_poly1305_default/chacha20_poly1305_default.outcome @@ -0,0 +1,20 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +[all] +targets: native wasip2 wasip3 emscripten +build: succeeds +run: app +# tag::output[] +[native] +chacha20_poly1305 ok backend=sodium +[wasip2] +chacha20_poly1305 ok backend=sodium +[wasip3] +chacha20_poly1305 ok backend=sodium +[emscripten] +chacha20_poly1305 ok backend=sodium +# end::output[] diff --git a/tools/test/fixtures/crypto_jamfiles/chacha20_poly1305_original_default/Jamfile b/tools/test/fixtures/crypto_jamfiles/chacha20_poly1305_original_default/Jamfile new file mode 100644 index 00000000..1f832c3b --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/chacha20_poly1305_original_default/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/crypto//crypto /webcpp/crypto//chacha20_poly1305_original-default ; +# end::jamfile[] 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 new file mode 100644 index 00000000..9617d93b --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/chacha20_poly1305_original_default/app.cpp @@ -0,0 +1,54 @@ +// 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) + +// Seals libsodium's own case of the original ChaCha20-Poly1305 (its 8-byte nonce, +// test/default/aead_chacha20poly1305.exp) on the default backend, checks the tag and the +// 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 +#include +#include + +int main() { + using aead = webcpp::crypto::ciphers::chacha20_poly1305_original<>; + std::array const key{ + 0x42, 0x90, 0xbc, 0xb1, 0x54, 0x17, 0x35, 0x31, 0xf3, 0x14, 0xaf, + 0x57, 0xf3, 0xbe, 0x3b, 0x50, 0x06, 0xda, 0x37, 0x1e, 0xce, 0x27, + 0x2a, 0xfa, 0x1b, 0x5d, 0xbd, 0xd1, 0x10, 0x0a, 0x10, 0x07, + }; + std::array const iv{0xcd, 0x7c, 0xf6, 0x7b, 0xe3, 0x9c, 0x79, 0x4a}; + // NOLINTBEGIN(readability-trailing-comma): it asks a list of one row, wrapped, for the comma + // and refuses it once clang-format puts the brace on a line of its own + std::array const additional_data{0x87, 0xe2, 0x29, 0xd4, 0x50, + 0x08, 0x45, 0xa0, 0x79, 0xc0}; + std::array const plaintext{0x86, 0xd0, 0x99, 0x74, 0x84, + 0x0b, 0xde, 0xd2, 0xa5, 0xca}; + auto data = plaintext; + std::array const expected_tag{ + 0x67, 0x7d, 0xab, 0xf4, 0xe3, 0xd2, 0x4b, 0x87, + 0x6b, 0xb2, 0x84, 0x75, 0x38, 0x96, 0xe1, 0xd6, + }; + std::array const expected_head{0xe3, 0xe4, 0x46, 0xf7, 0xed, + 0xe9, 0xa1, 0x9b, 0x62, 0xa4}; + // NOLINTEND(readability-trailing-comma) + auto sealer = aead::make(key); + bool ok = false; + if (sealer) { + auto const tag = sealer->seal(iv, additional_data, data); + ok = tag && webcpp::crypto::equal(*tag, expected_tag) && + std::equal(expected_head.begin(), expected_head.end(), data.begin()) && + sealer->open(iv, additional_data, data, expected_tag) && data == plaintext; + } + auto const name = aead::backend_type::name; + std::printf("chacha20_poly1305_original %s backend=%.*s\n", ok ? "ok" : "FAILED", + static_cast(name.size()), name.data()); + return ok ? 0 : 1; +} diff --git a/tools/test/fixtures/crypto_jamfiles/chacha20_poly1305_original_default/chacha20_poly1305_original_default.outcome b/tools/test/fixtures/crypto_jamfiles/chacha20_poly1305_original_default/chacha20_poly1305_original_default.outcome new file mode 100644 index 00000000..fdfff4f3 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/chacha20_poly1305_original_default/chacha20_poly1305_original_default.outcome @@ -0,0 +1,20 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +[all] +targets: native wasip2 wasip3 emscripten +build: succeeds +run: app +# tag::output[] +[native] +chacha20_poly1305_original ok backend=sodium +[wasip2] +chacha20_poly1305_original ok backend=sodium +[wasip3] +chacha20_poly1305_original ok backend=sodium +[emscripten] +chacha20_poly1305_original ok backend=sodium +# end::output[] diff --git a/tools/test/fixtures/crypto_jamfiles/chacha_default_not_linked_on_emscripten/Jamfile b/tools/test/fixtures/crypto_jamfiles/chacha_default_not_linked_on_emscripten/Jamfile new file mode 100644 index 00000000..4b12ef4a --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/chacha_default_not_linked_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/crypto//crypto ; +# end::jamfile[] diff --git a/tools/test/fixtures/crypto_jamfiles/chacha_default_not_linked_on_emscripten/app.cpp b/tools/test/fixtures/crypto_jamfiles/chacha_default_not_linked_on_emscripten/app.cpp new file mode 100644 index 00000000..be09fbaf --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/chacha_default_not_linked_on_emscripten/app.cpp @@ -0,0 +1,22 @@ +// 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) + +// As test/messages/chacha_default_not_linked, on Emscripten. + +#include + +#include +#include + +int main() { + namespace ciphers = webcpp::crypto::ciphers; + std::array const key{}; + return ciphers::chacha20_poly1305<>::make(key) && + ciphers::chacha20_poly1305_original<>::make(key) && + ciphers::xchacha20_poly1305<>::make(key) + ? 0 + : 1; +} diff --git a/tools/test/fixtures/crypto_jamfiles/chacha_default_not_linked_on_emscripten/chacha_default_not_linked_on_emscripten.outcome b/tools/test/fixtures/crypto_jamfiles/chacha_default_not_linked_on_emscripten/chacha_default_not_linked_on_emscripten.outcome new file mode 100644 index 00000000..cf122ef6 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/chacha_default_not_linked_on_emscripten/chacha_default_not_linked_on_emscripten.outcome @@ -0,0 +1,18 @@ +# 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/chacha_default_not_linked); compile-diagnostic is clang's and skips Emscripten, so +# this fixture is the Emscripten one. +[all] +targets: emscripten +build: fails +# tag::messages[] +contains: webcpp::crypto: ChaCha20-Poly1305's default backend on this target is libsodium, which is not linked. Add /webcpp/crypto//chacha20_poly1305-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//chacha20_poly1305-default ; or name another backend in the type, as in ciphers::chacha20_poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten), bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3). (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c) +contains: webcpp::crypto: original ChaCha20-Poly1305's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /webcpp/crypto//chacha20_poly1305_original-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//chacha20_poly1305_original-default ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c) +contains: webcpp::crypto: XChaCha20-Poly1305's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /webcpp/crypto//xchacha20_poly1305-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//xchacha20_poly1305-default ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c) +# end::messages[] diff --git a/tools/test/fixtures/crypto_jamfiles/chacha_header_not_included_on_emscripten/Jamfile b/tools/test/fixtures/crypto_jamfiles/chacha_header_not_included_on_emscripten/Jamfile new file mode 100644 index 00000000..4b12ef4a --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/chacha_header_not_included_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/crypto//crypto ; +# end::jamfile[] diff --git a/tools/test/fixtures/crypto_jamfiles/chacha_header_not_included_on_emscripten/app.cpp b/tools/test/fixtures/crypto_jamfiles/chacha_header_not_included_on_emscripten/app.cpp new file mode 100644 index 00000000..978746f8 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/chacha_header_not_included_on_emscripten/app.cpp @@ -0,0 +1,18 @@ +// 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 BearSSL in ChaCha20-Poly1305's type without including BearSSL's header stops +// where it makes the AEAD, with the header to include and the line that links BearSSL. +#include + +#include +#include + +int main() { + namespace crypto = webcpp::crypto; + std::array const key{}; + return crypto::ciphers::chacha20_poly1305::make(key) ? 0 : 1; +} diff --git a/tools/test/fixtures/crypto_jamfiles/chacha_header_not_included_on_emscripten/chacha_header_not_included_on_emscripten.outcome b/tools/test/fixtures/crypto_jamfiles/chacha_header_not_included_on_emscripten/chacha_header_not_included_on_emscripten.outcome new file mode 100644 index 00000000..cc09ac46 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/chacha_header_not_included_on_emscripten/chacha_header_not_included_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/chacha_header_not_included); compile-diagnostic is clang's and skips Emscripten, so +# this fixture is the Emscripten one. +[all] +targets: emscripten +build: fails +# tag::messages[] +contains: webcpp::crypto: bearssl's ChaCha20-Poly1305 is in , which the program does not include. Include it, and add /third_party//bearssl to the program's Jamfile. +# end::messages[] diff --git a/tools/test/fixtures/crypto_jamfiles/chacha_on_ctaes_on_emscripten/Jamfile b/tools/test/fixtures/crypto_jamfiles/chacha_on_ctaes_on_emscripten/Jamfile new file mode 100644 index 00000000..4e876d46 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/chacha_on_ctaes_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/crypto//crypto /third_party//ctaes ; +# end::jamfile[] diff --git a/tools/test/fixtures/crypto_jamfiles/chacha_on_ctaes_on_emscripten/app.cpp b/tools/test/fixtures/crypto_jamfiles/chacha_on_ctaes_on_emscripten/app.cpp new file mode 100644 index 00000000..6bdc0fa0 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/chacha_on_ctaes_on_emscripten/app.cpp @@ -0,0 +1,19 @@ +// 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 for Emscripten that names ctaes, which exports the AES block cipher alone, in a +// ChaCha20-Poly1305 type. +#include +#include + +#include +#include + +int main() { + namespace crypto = webcpp::crypto; + std::array const key{}; + return crypto::ciphers::chacha20_poly1305::make(key) ? 0 : 1; +} diff --git a/tools/test/fixtures/crypto_jamfiles/chacha_on_ctaes_on_emscripten/chacha_on_ctaes_on_emscripten.outcome b/tools/test/fixtures/crypto_jamfiles/chacha_on_ctaes_on_emscripten/chacha_on_ctaes_on_emscripten.outcome new file mode 100644 index 00000000..b9c96889 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/chacha_on_ctaes_on_emscripten/chacha_on_ctaes_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 static_assert starts with the header's path on the machine, so the +# message is a contains: line. Natively and on wasip2 and wasip3 the same message is a +# compile-diagnostic (test/messages/chacha_on_ctaes); compile-diagnostic is clang's and skips +# Emscripten, so this fixture is the Emscripten one. +[all] +targets: emscripten +build: fails +# tag::messages[] +contains: webcpp::crypto: ctaes has no ChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten), bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3). +# end::messages[] diff --git a/tools/test/fixtures/crypto_jamfiles/chacha_openssl_on_emscripten/Jamfile b/tools/test/fixtures/crypto_jamfiles/chacha_openssl_on_emscripten/Jamfile new file mode 100644 index 00000000..4b12ef4a --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/chacha_openssl_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/crypto//crypto ; +# end::jamfile[] diff --git a/tools/test/fixtures/crypto_jamfiles/chacha_openssl_on_emscripten/app.cpp b/tools/test/fixtures/crypto_jamfiles/chacha_openssl_on_emscripten/app.cpp new file mode 100644 index 00000000..28b98359 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/chacha_openssl_on_emscripten/app.cpp @@ -0,0 +1,18 @@ +// 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 for Emscripten that names OpenSSL, which is not built there, in ChaCha20-Poly1305's +// type. +#include + +#include +#include + +int main() { + namespace crypto = webcpp::crypto; + std::array const key{}; + return crypto::ciphers::chacha20_poly1305::make(key) ? 0 : 1; +} diff --git a/tools/test/fixtures/crypto_jamfiles/chacha_openssl_on_emscripten/chacha_openssl_on_emscripten.outcome b/tools/test/fixtures/crypto_jamfiles/chacha_openssl_on_emscripten/chacha_openssl_on_emscripten.outcome new file mode 100644 index 00000000..ff946766 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/chacha_openssl_on_emscripten/chacha_openssl_on_emscripten.outcome @@ -0,0 +1,15 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +# The compiler's line of the refusal starts with the header's path on the machine, so the message is +# a contains: line. OpenSSL is not built for Emscripten, and the refusal says so on Emscripten +# alone: no message test or MSVC case has it. +[all] +targets: emscripten +build: fails +# tag::messages[] +contains: webcpp::crypto: openssl has no ChaCha20-Poly1305 on emscripten. The backends that have it: sodium (native, wasip2, wasip3, emscripten), bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3). +# end::messages[] diff --git a/tools/test/fixtures/crypto_jamfiles/chacha_unknown_backend_on_emscripten/Jamfile b/tools/test/fixtures/crypto_jamfiles/chacha_unknown_backend_on_emscripten/Jamfile new file mode 100644 index 00000000..4b12ef4a --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/chacha_unknown_backend_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/crypto//crypto ; +# end::jamfile[] diff --git a/tools/test/fixtures/crypto_jamfiles/chacha_unknown_backend_on_emscripten/app.cpp b/tools/test/fixtures/crypto_jamfiles/chacha_unknown_backend_on_emscripten/app.cpp new file mode 100644 index 00000000..470d9c8b --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/chacha_unknown_backend_on_emscripten/app.cpp @@ -0,0 +1,24 @@ +// 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 a type of its own as ChaCha20-Poly1305's backend stops where it makes the +// AEAD, with the backends that have the family. +#include + +#include +#include + +namespace { + +/** A type of the program's own, which is no backend. */ +struct my_backend {}; + +} // namespace + +int main() { + std::array const key{}; + return webcpp::crypto::ciphers::chacha20_poly1305::make(key) ? 0 : 1; +} diff --git a/tools/test/fixtures/crypto_jamfiles/chacha_unknown_backend_on_emscripten/chacha_unknown_backend_on_emscripten.outcome b/tools/test/fixtures/crypto_jamfiles/chacha_unknown_backend_on_emscripten/chacha_unknown_backend_on_emscripten.outcome new file mode 100644 index 00000000..f4ef3560 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/chacha_unknown_backend_on_emscripten/chacha_unknown_backend_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/chacha_unknown_backend); compile-diagnostic is clang's and skips Emscripten, so +# this fixture is the Emscripten one. +[all] +targets: emscripten +build: fails +# tag::messages[] +contains: webcpp::crypto: ChaCha20-Poly1305 has no backend of that name. The backends that have it: sodium (native, wasip2, wasip3, emscripten), bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3). +# end::messages[] diff --git a/tools/test/fixtures/crypto_jamfiles/default_bearssl_on_emscripten/Jamfile b/tools/test/fixtures/crypto_jamfiles/default_bearssl_on_emscripten/Jamfile new file mode 100644 index 00000000..3608cd42 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/default_bearssl_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/crypto//crypto : WEBCPP_CRYPTO_DEFAULT_BACKEND_BEARSSL ; +# end::jamfile[] diff --git a/tools/test/fixtures/crypto_jamfiles/default_bearssl_on_emscripten/app.cpp b/tools/test/fixtures/crypto_jamfiles/default_bearssl_on_emscripten/app.cpp new file mode 100644 index 00000000..6c80fb35 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/default_bearssl_on_emscripten/app.cpp @@ -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) + +#include + +int main() {} diff --git a/tools/test/fixtures/crypto_jamfiles/default_bearssl_on_emscripten/default_bearssl_on_emscripten.outcome b/tools/test/fixtures/crypto_jamfiles/default_bearssl_on_emscripten/default_bearssl_on_emscripten.outcome new file mode 100644 index 00000000..59352863 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/default_bearssl_on_emscripten/default_bearssl_on_emscripten.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 compiler's line of the #error starts with the header's path on the machine, so the +# message is a contains: line. +[all] +targets: emscripten +build: fails +# tag::messages[] +contains: webcpp::crypto: WEBCPP_CRYPTO_DEFAULT_BACKEND_BEARSSL no longer chooses a default. Write the backend in the type where the program wants it, as in ciphers::gcm>. +# end::messages[] diff --git a/tools/test/fixtures/crypto_jamfiles/default_openssl_on_emscripten/default_openssl_on_emscripten.outcome b/tools/test/fixtures/crypto_jamfiles/default_openssl_on_emscripten/default_openssl_on_emscripten.outcome index c4bbaadd..88a0c966 100644 --- a/tools/test/fixtures/crypto_jamfiles/default_openssl_on_emscripten/default_openssl_on_emscripten.outcome +++ b/tools/test/fixtures/crypto_jamfiles/default_openssl_on_emscripten/default_openssl_on_emscripten.outcome @@ -10,5 +10,5 @@ targets: emscripten build: fails # tag::messages[] -contains: webcpp::crypto: WEBCPP_CRYPTO_DEFAULT_BACKEND_OPENSSL selects OpenSSL, which is not built for Emscripten. Remove that define, or make it WEBCPP_CRYPTO_DEFAULT_BACKEND_BEARSSL. +contains: webcpp::crypto: WEBCPP_CRYPTO_DEFAULT_BACKEND_OPENSSL no longer chooses a default. Write the backend in the type where the program wants it, as in ciphers::gcm>. # end::messages[] diff --git a/tools/test/fixtures/crypto_jamfiles/ed25519_default/Jamfile b/tools/test/fixtures/crypto_jamfiles/ed25519_default/Jamfile new file mode 100644 index 00000000..cd276b26 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/ed25519_default/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/crypto//crypto /webcpp/crypto//ed25519-default ; +# end::jamfile[] diff --git a/tools/test/fixtures/crypto_jamfiles/ed25519_default/app.cpp b/tools/test/fixtures/crypto_jamfiles/ed25519_default/app.cpp new file mode 100644 index 00000000..17bda9be --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/ed25519_default/app.cpp @@ -0,0 +1,45 @@ +// 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) + +// 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 + +int main() { + namespace ed25519 = webcpp::crypto::curves::ed25519; + std::array const seed{ + 0x9d, 0x61, 0xb1, 0x9d, 0xef, 0xfd, 0x5a, 0x60, 0xba, 0x84, 0x4a, + 0xf4, 0x92, 0xec, 0x2c, 0xc4, 0x44, 0x49, 0xc5, 0x69, 0x7b, 0x32, + 0x69, 0x19, 0x70, 0x3b, 0xac, 0x03, 0x1c, 0xae, 0x7f, 0x60, + }; + std::array const expected{ + 0xe5, 0x56, 0x43, 0x00, 0xc3, 0x60, 0xac, 0x72, 0x90, 0x86, 0xe2, 0xcc, 0x80, + 0x6e, 0x82, 0x8a, 0x84, 0x87, 0x7f, 0x1e, 0xb8, 0xe5, 0xd9, 0x74, 0xd8, 0x73, + 0xe0, 0x65, 0x22, 0x49, 0x01, 0x55, 0x5f, 0xb8, 0x82, 0x15, 0x90, 0xa3, 0x3b, + 0xac, 0xc6, 0x1e, 0x39, 0x70, 0x1c, 0xf9, 0xb4, 0x6b, 0xd2, 0x5b, 0xf5, 0xf0, + 0x59, 0x5b, 0xbe, 0x24, 0x65, 0x51, 0x41, 0x43, 0x8e, 0x7a, 0x10, 0x0b, + }; + std::span const message{}; + auto const key = ed25519::keypair::make(seed); + bool ok = false; + if (key) { + auto const signature = key->sign(message); + auto const public_key = key->public_key(); + ok = signature && public_key && webcpp::crypto::equal(*signature, expected) && + ed25519::verify(*public_key, message, *signature).has_value(); + } + auto const name = ed25519::keypair::backend_type::name; + std::printf("ed25519 %s backend=%.*s\n", ok ? "ok" : "FAILED", static_cast(name.size()), + name.data()); + return ok ? 0 : 1; +} diff --git a/tools/test/fixtures/crypto_jamfiles/ed25519_default/ed25519_default.outcome b/tools/test/fixtures/crypto_jamfiles/ed25519_default/ed25519_default.outcome new file mode 100644 index 00000000..8e150b0a --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/ed25519_default/ed25519_default.outcome @@ -0,0 +1,20 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +[all] +targets: native wasip2 wasip3 emscripten +build: succeeds +run: app +# tag::output[] +[native] +ed25519 ok backend=sodium +[wasip2] +ed25519 ok backend=sodium +[wasip3] +ed25519 ok backend=sodium +[emscripten] +ed25519 ok backend=sodium +# end::output[] diff --git a/tools/test/fixtures/crypto_jamfiles/ed25519_default_not_linked_on_emscripten/Jamfile b/tools/test/fixtures/crypto_jamfiles/ed25519_default_not_linked_on_emscripten/Jamfile new file mode 100644 index 00000000..4b12ef4a --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/ed25519_default_not_linked_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/crypto//crypto ; +# end::jamfile[] diff --git a/tools/test/fixtures/crypto_jamfiles/ed25519_default_not_linked_on_emscripten/app.cpp b/tools/test/fixtures/crypto_jamfiles/ed25519_default_not_linked_on_emscripten/app.cpp new file mode 100644 index 00000000..09bda19e --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/ed25519_default_not_linked_on_emscripten/app.cpp @@ -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) + +// A program that makes an Ed25519 key pair on its default backend, libsodium, and links none. +#include + +#include +#include + +int main() { + std::array const seed{}; + return webcpp::crypto::curves::ed25519::keypair::make(seed) ? 0 : 1; +} diff --git a/tools/test/fixtures/crypto_jamfiles/ed25519_default_not_linked_on_emscripten/ed25519_default_not_linked_on_emscripten.outcome b/tools/test/fixtures/crypto_jamfiles/ed25519_default_not_linked_on_emscripten/ed25519_default_not_linked_on_emscripten.outcome new file mode 100644 index 00000000..0973fd46 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/ed25519_default_not_linked_on_emscripten/ed25519_default_not_linked_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/ed25519_default_not_linked); compile-diagnostic is clang's and skips Emscripten, so +# this fixture is the Emscripten one. +[all] +targets: emscripten +build: fails +# tag::messages[] +contains: webcpp::crypto: Ed25519's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /webcpp/crypto//ed25519-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//ed25519-default ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c) +# end::messages[] diff --git a/tools/test/fixtures/crypto_jamfiles/ed25519_on_bearssl_on_emscripten/Jamfile b/tools/test/fixtures/crypto_jamfiles/ed25519_on_bearssl_on_emscripten/Jamfile new file mode 100644 index 00000000..014a3e61 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/ed25519_on_bearssl_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/crypto//crypto /third_party//sodium ; +# end::jamfile[] diff --git a/tools/test/fixtures/crypto_jamfiles/ed25519_on_bearssl_on_emscripten/app.cpp b/tools/test/fixtures/crypto_jamfiles/ed25519_on_bearssl_on_emscripten/app.cpp new file mode 100644 index 00000000..87d21620 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/ed25519_on_bearssl_on_emscripten/app.cpp @@ -0,0 +1,19 @@ +// 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 BearSSL, which has no Ed25519, in an Ed25519 key pair's type. +#include + +#include +#include + +int main() { + std::array const seed{}; + return webcpp::crypto::curves::ed25519::basic_keypair::make( + seed) + ? 0 + : 1; +} diff --git a/tools/test/fixtures/crypto_jamfiles/ed25519_on_bearssl_on_emscripten/ed25519_on_bearssl_on_emscripten.outcome b/tools/test/fixtures/crypto_jamfiles/ed25519_on_bearssl_on_emscripten/ed25519_on_bearssl_on_emscripten.outcome new file mode 100644 index 00000000..c405de3d --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/ed25519_on_bearssl_on_emscripten/ed25519_on_bearssl_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/ed25519_on_bearssl); compile-diagnostic is clang's and skips Emscripten, so this +# fixture is the Emscripten one. +[all] +targets: emscripten +build: fails +# tag::messages[] +contains: webcpp::crypto: bearssl has no Ed25519. The backends that have it: sodium (native, wasip2, wasip3, emscripten). +# end::messages[] diff --git a/tools/test/fixtures/crypto_jamfiles/ed25519_unknown_policy_on_emscripten/Jamfile b/tools/test/fixtures/crypto_jamfiles/ed25519_unknown_policy_on_emscripten/Jamfile new file mode 100644 index 00000000..cd276b26 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/ed25519_unknown_policy_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/crypto//crypto /webcpp/crypto//ed25519-default ; +# end::jamfile[] diff --git a/tools/test/fixtures/crypto_jamfiles/ed25519_unknown_policy_on_emscripten/app.cpp b/tools/test/fixtures/crypto_jamfiles/ed25519_unknown_policy_on_emscripten/app.cpp new file mode 100644 index 00000000..fc97fcc3 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/ed25519_unknown_policy_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) + +// A program that names a policy of its own in Ed25519's verify, on its default backend linked, +// stops where it calls it, with the one policy there is. +#include + +#include +#include + +namespace { + +/** A verification policy of the program's own. */ +struct lenient {}; + +} // namespace + +int main() { + std::array const public_key{}; + std::array const signature{}; + return webcpp::crypto::curves::ed25519::verify(public_key, {}, signature) ? 0 : 1; +} diff --git a/tools/test/fixtures/crypto_jamfiles/ed25519_unknown_policy_on_emscripten/ed25519_unknown_policy_on_emscripten.outcome b/tools/test/fixtures/crypto_jamfiles/ed25519_unknown_policy_on_emscripten/ed25519_unknown_policy_on_emscripten.outcome new file mode 100644 index 00000000..929fb299 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/ed25519_unknown_policy_on_emscripten/ed25519_unknown_policy_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/ed25519_unknown_policy); compile-diagnostic is clang's and skips Emscripten, so +# this fixture is the Emscripten one. +[all] +targets: emscripten +build: fails +# tag::messages[] +contains: webcpp::crypto: Ed25519's only verification policy is curves::ed25519::strict. +# end::messages[] diff --git a/tools/test/fixtures/crypto_jamfiles/ed25519ph_sha256_on_emscripten/Jamfile b/tools/test/fixtures/crypto_jamfiles/ed25519ph_sha256_on_emscripten/Jamfile new file mode 100644 index 00000000..014a3e61 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/ed25519ph_sha256_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/crypto//crypto /third_party//sodium ; +# end::jamfile[] diff --git a/tools/test/fixtures/crypto_jamfiles/ed25519ph_sha256_on_emscripten/app.cpp b/tools/test/fixtures/crypto_jamfiles/ed25519ph_sha256_on_emscripten/app.cpp new file mode 100644 index 00000000..3439f1c2 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/ed25519ph_sha256_on_emscripten/app.cpp @@ -0,0 +1,13 @@ +// 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 SHA-256 in Ed25519ph's type, which RFC 8032 defines over SHA-512. +#include +#include + +int main() { + return webcpp::crypto::curves::ed25519::ph::begin() ? 0 : 1; +} diff --git a/tools/test/fixtures/crypto_jamfiles/ed25519ph_sha256_on_emscripten/ed25519ph_sha256_on_emscripten.outcome b/tools/test/fixtures/crypto_jamfiles/ed25519ph_sha256_on_emscripten/ed25519ph_sha256_on_emscripten.outcome new file mode 100644 index 00000000..64ae41e0 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/ed25519ph_sha256_on_emscripten/ed25519ph_sha256_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 static_assert 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/ed25519ph_sha256); compile-diagnostic is clang's and skips Emscripten, so this +# fixture is the Emscripten one. +[all] +targets: emscripten +build: fails +# tag::messages[] +contains: webcpp::crypto: Ed25519ph is defined over SHA-512 (RFC 8032 section 5.1); name curves::ed25519::ph. +# end::messages[] diff --git a/tools/test/fixtures/crypto_jamfiles/encrypt_and_sign/Jamfile b/tools/test/fixtures/crypto_jamfiles/encrypt_and_sign/Jamfile index 474ac68f..9be73e34 100644 --- a/tools/test/fixtures/crypto_jamfiles/encrypt_and_sign/Jamfile +++ b/tools/test/fixtures/crypto_jamfiles/encrypt_and_sign/Jamfile @@ -5,5 +5,5 @@ # https://www.boost.org/LICENSE_1_0.txt) # tag::jamfile[] -exe app : app.cpp /webcpp/crypto//crypto /third_party//bearssl /third_party//secp256k1 ; +exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//gcm-default /third_party//secp256k1 ; # end::jamfile[] diff --git a/tools/test/fixtures/crypto_jamfiles/encrypt_and_sign/encrypt_and_sign.outcome b/tools/test/fixtures/crypto_jamfiles/encrypt_and_sign/encrypt_and_sign.outcome index 67a3be74..ce542743 100644 --- a/tools/test/fixtures/crypto_jamfiles/encrypt_and_sign/encrypt_and_sign.outcome +++ b/tools/test/fixtures/crypto_jamfiles/encrypt_and_sign/encrypt_and_sign.outcome @@ -9,6 +9,16 @@ targets: native wasip2 wasip3 emscripten build: succeeds run: app # tag::output[] +[native] +aes256_gcm ok backend=openssl +schnorr ok +[wasip2] +aes256_gcm ok backend=bearssl +schnorr ok +[wasip3] +aes256_gcm ok backend=bearssl +schnorr ok +[emscripten] aes256_gcm ok backend=bearssl schnorr ok # end::output[] diff --git a/tools/test/fixtures/crypto_jamfiles/gcm_default/Jamfile b/tools/test/fixtures/crypto_jamfiles/gcm_default/Jamfile new file mode 100644 index 00000000..3b0a63d2 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/gcm_default/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/crypto//crypto /webcpp/crypto//gcm-default ; +# end::jamfile[] diff --git a/tools/test/fixtures/crypto_jamfiles/both_bearssl_default/app.cpp b/tools/test/fixtures/crypto_jamfiles/gcm_default/app.cpp similarity index 100% rename from tools/test/fixtures/crypto_jamfiles/both_bearssl_default/app.cpp rename to tools/test/fixtures/crypto_jamfiles/gcm_default/app.cpp diff --git a/tools/test/fixtures/crypto_jamfiles/gcm_default/gcm_default.outcome b/tools/test/fixtures/crypto_jamfiles/gcm_default/gcm_default.outcome new file mode 100644 index 00000000..4a1802e1 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/gcm_default/gcm_default.outcome @@ -0,0 +1,21 @@ +# 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) + +[all] +targets: native wasip2 wasip3 emscripten +same-as: web/app.cpp app.cpp +build: succeeds +run: app +# tag::output[] +[native] +aes256_gcm ok backend=openssl +[wasip2] +aes256_gcm ok backend=bearssl +[wasip3] +aes256_gcm ok backend=bearssl +[emscripten] +aes256_gcm ok backend=bearssl +# end::output[] diff --git a/tools/test/fixtures/crypto_jamfiles/heavy_without_threads_on_emscripten/Jamfile b/tools/test/fixtures/crypto_jamfiles/heavy_without_threads_on_emscripten/Jamfile new file mode 100644 index 00000000..4b12ef4a --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/heavy_without_threads_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/crypto//crypto ; +# end::jamfile[] diff --git a/tools/test/fixtures/crypto_jamfiles/heavy_without_threads_on_emscripten/app.cpp b/tools/test/fixtures/crypto_jamfiles/heavy_without_threads_on_emscripten/app.cpp new file mode 100644 index 00000000..dbef3e49 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/heavy_without_threads_on_emscripten/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 heavy operation's async_ variant called in a build for Emscripten without -pthread. +#include + +#include + +namespace { + +int slow(int value) noexcept { + return value + 1; +} + +template +auto async_slow(Executor executor, int value, CompletionToken&& token) { + WEBCPP_CRYPTO_DETAIL_REQUIRE_THREADS("async_slow", "slow"); + return webcpp::crypto::detail::run_heavy( + std::move(executor), [value]() noexcept { return slow(value); }, + std::forward(token)); +} + +struct executor {}; + +struct token {}; + +} // namespace + +int main() { + async_slow(executor{}, 41, token{}); + return slow(0) == 1 ? 0 : 1; +} diff --git a/tools/test/fixtures/crypto_jamfiles/heavy_without_threads_on_emscripten/heavy_without_threads_on_emscripten.outcome b/tools/test/fixtures/crypto_jamfiles/heavy_without_threads_on_emscripten/heavy_without_threads_on_emscripten.outcome new file mode 100644 index 00000000..907435bb --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/heavy_without_threads_on_emscripten/heavy_without_threads_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 source'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/heavy_without_threads); compile-diagnostic is clang's and skips Emscripten, so +# this fixture is the Emscripten one, built without -pthread. +[all] +targets: emscripten +build: fails +# tag::messages[] +contains: webcpp::crypto: async_slow runs on another thread and needs a build with threads (natively without WEBCPP_CRYPTO_NO_THREADS; on Emscripten -pthread). Without threads, call slow. +# end::messages[] diff --git a/tools/test/fixtures/crypto_jamfiles/kx_default/Jamfile b/tools/test/fixtures/crypto_jamfiles/kx_default/Jamfile new file mode 100644 index 00000000..4734c174 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/kx_default/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/crypto//crypto /webcpp/crypto//kx-default ; +# end::jamfile[] diff --git a/tools/test/fixtures/crypto_jamfiles/kx_default/app.cpp b/tools/test/fixtures/crypto_jamfiles/kx_default/app.cpp new file mode 100644 index 00000000..8f9fbd54 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/kx_default/app.cpp @@ -0,0 +1,50 @@ +// 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) + +// Makes libsodium's kx.exp client and server key pairs from their seeds on the default backend, +// 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 +#include + +int main() { + namespace x25519 = webcpp::crypto::curves::x25519; + std::array client_seed{}; + for (std::size_t i = 0; i < client_seed.size(); ++i) { + client_seed[i] = static_cast(i); + } + std::array server_seed = client_seed; + server_seed[0] = 1; + std::array const expected{ + 0x62, 0xc8, 0xf4, 0xfa, 0x81, 0x80, 0x0a, 0xbd, 0x05, 0x77, 0xd9, + 0x99, 0x18, 0xd1, 0x29, 0xb6, 0x5d, 0xeb, 0x78, 0x9a, 0xf8, 0xc8, + 0x35, 0x1f, 0x39, 0x1f, 0xeb, 0x0c, 0xbf, 0x23, 0x86, 0x04, + }; + auto const client = x25519::kx_keypair<>::make(client_seed); + auto const server = x25519::kx_keypair<>::make(server_seed); + bool ok = false; + if (client && server) { + auto const client_public = client->public_key(); + auto const server_public = server->public_key(); + if (client_public && server_public) { + 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::equal(client_keys->transmit.bytes(), expected) && + webcpp::crypto::equal(server_keys->receive.bytes(), expected); + } + } + auto const name = x25519::kx_keypair<>::backend_type::name; + std::printf("kx %s backend=%.*s\n", ok ? "ok" : "FAILED", static_cast(name.size()), + name.data()); + return ok ? 0 : 1; +} diff --git a/tools/test/fixtures/crypto_jamfiles/kx_default/kx_default.outcome b/tools/test/fixtures/crypto_jamfiles/kx_default/kx_default.outcome new file mode 100644 index 00000000..dcb43060 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/kx_default/kx_default.outcome @@ -0,0 +1,20 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +[all] +targets: native wasip2 wasip3 emscripten +build: succeeds +run: app +# tag::output[] +[native] +kx ok backend=sodium +[wasip2] +kx ok backend=sodium +[wasip3] +kx ok backend=sodium +[emscripten] +kx ok backend=sodium +# end::output[] diff --git a/tools/test/fixtures/crypto_jamfiles/kx_default_not_linked_on_emscripten/Jamfile b/tools/test/fixtures/crypto_jamfiles/kx_default_not_linked_on_emscripten/Jamfile new file mode 100644 index 00000000..4b12ef4a --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/kx_default_not_linked_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/crypto//crypto ; +# end::jamfile[] diff --git a/tools/test/fixtures/crypto_jamfiles/kx_default_not_linked_on_emscripten/app.cpp b/tools/test/fixtures/crypto_jamfiles/kx_default_not_linked_on_emscripten/app.cpp new file mode 100644 index 00000000..8794e496 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/kx_default_not_linked_on_emscripten/app.cpp @@ -0,0 +1,17 @@ +// 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) + +// As test/messages/kx_default_not_linked, on Emscripten. + +#include + +#include +#include + +int main() { + std::array const seed{}; + return webcpp::crypto::curves::x25519::kx_keypair<>::make(seed) ? 0 : 1; +} diff --git a/tools/test/fixtures/crypto_jamfiles/kx_default_not_linked_on_emscripten/kx_default_not_linked_on_emscripten.outcome b/tools/test/fixtures/crypto_jamfiles/kx_default_not_linked_on_emscripten/kx_default_not_linked_on_emscripten.outcome new file mode 100644 index 00000000..b2c26d9d --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/kx_default_not_linked_on_emscripten/kx_default_not_linked_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/kx_default_not_linked); compile-diagnostic is clang's and skips Emscripten, so this +# fixture is the Emscripten one. +[all] +targets: emscripten +build: fails +# tag::messages[] +contains: webcpp::crypto: crypto_kx's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /webcpp/crypto//kx-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//kx-default ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c) +# end::messages[] diff --git a/tools/test/fixtures/crypto_jamfiles/no_backend_on_emscripten/no_backend_on_emscripten.outcome b/tools/test/fixtures/crypto_jamfiles/no_backend_on_emscripten/no_backend_on_emscripten.outcome index 8860220f..b0197f55 100644 --- a/tools/test/fixtures/crypto_jamfiles/no_backend_on_emscripten/no_backend_on_emscripten.outcome +++ b/tools/test/fixtures/crypto_jamfiles/no_backend_on_emscripten/no_backend_on_emscripten.outcome @@ -4,13 +4,13 @@ # accompanying file LICENSE_1_0.txt or copy at # https://www.boost.org/LICENSE_1_0.txt) -# The compiler's line of the #error 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/no_backend_wasm); compile-diagnostic is clang's and skips Emscripten, so this -# fixture is the Emscripten one. +# The compiler's line of the refusal starts with the header's path on the machine, so the +# message is a contains: line. On wasip2 and wasip3, where OpenSSL has AES-GCM too, the message +# names it as well (test/messages/no_backend_wasm); compile-diagnostic is clang's and skips +# Emscripten, so this fixture is the Emscripten one. [all] targets: emscripten build: fails # tag::messages[] -contains: webcpp::crypto: no backend is linked. On WebAssembly the backend is BearSSL: in the program's Jamfile, add /third_party//bearssl beside /webcpp/crypto//crypto, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//bearssl ; (without b2: define WEBCPP_CRYPTO_HAS_BEARSSL=1 and link BearSSL built with webcpp's src/canary_bearssl.c) +contains: webcpp::crypto: AES-GCM's default backend on this target is BearSSL, which is not linked, and the one backend that has it there. Add /webcpp/crypto//gcm-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//gcm-default ; (without b2: define WEBCPP_CRYPTO_HAS_BEARSSL=1 and link BearSSL built with webcpp's src/canary_bearssl.c) # end::messages[] diff --git a/tools/test/fixtures/crypto_jamfiles/pem_default/Jamfile b/tools/test/fixtures/crypto_jamfiles/pem_default/Jamfile new file mode 100644 index 00000000..dfe9afdb --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/pem_default/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/crypto//crypto /webcpp/crypto//pem-default ; +# end::jamfile[] diff --git a/tools/test/fixtures/crypto_jamfiles/pem_default/app.cpp b/tools/test/fixtures/crypto_jamfiles/pem_default/app.cpp new file mode 100644 index 00000000..3d28b7c5 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/pem_default/app.cpp @@ -0,0 +1,32 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// Reads RFC 8410's Ed25519 public key in PEM (section 10.1) on PEM's default backend, armours its +// DER again, checks that the text is the same, and prints the backend that ran. +#include + +#include +#include +#include +#include + +int main() { + namespace pem = webcpp::crypto::pem; + constexpr std::string_view text = + "-----BEGIN PUBLIC KEY-----\n" + "MCowBQYDK2VwAyEAGb9ECWmEzf6FQbrBZ9w7lshQhqowtrbLDFw4rXAxZuE=\n" + "-----END PUBLIC KEY-----\n"; + std::array der{}; + auto const read = pem::unarmour(pem::public_key_label, text, der); + std::array again{}; + auto const written = pem::armour(pem::public_key_label, der, again); + bool const ok = + read && *read == der.size() && written && std::string_view(again.data(), *written) == text; + auto const name = pem::algorithm<>::backend_type::name; + std::printf("pem %s backend=%.*s\n", ok ? "ok" : "FAILED", static_cast(name.size()), + name.data()); + return ok ? 0 : 1; +} diff --git a/tools/test/fixtures/crypto_jamfiles/pem_default/pem_default.outcome b/tools/test/fixtures/crypto_jamfiles/pem_default/pem_default.outcome new file mode 100644 index 00000000..8684e53b --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/pem_default/pem_default.outcome @@ -0,0 +1,20 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +[all] +targets: native wasip2 wasip3 emscripten +build: succeeds +run: app +# tag::output[] +[native] +pem ok backend=sodium +[wasip2] +pem ok backend=sodium +[wasip3] +pem ok backend=sodium +[emscripten] +pem ok backend=sodium +# end::output[] diff --git a/tools/test/fixtures/crypto_jamfiles/pem_default_not_linked_on_emscripten/Jamfile b/tools/test/fixtures/crypto_jamfiles/pem_default_not_linked_on_emscripten/Jamfile new file mode 100644 index 00000000..4b12ef4a --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/pem_default_not_linked_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/crypto//crypto ; +# end::jamfile[] diff --git a/tools/test/fixtures/crypto_jamfiles/pem_default_not_linked_on_emscripten/app.cpp b/tools/test/fixtures/crypto_jamfiles/pem_default_not_linked_on_emscripten/app.cpp new file mode 100644 index 00000000..f19bc162 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/pem_default_not_linked_on_emscripten/app.cpp @@ -0,0 +1,19 @@ +// 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 armours DER as PEM on its default backend, libsodium on every target, without +// linking it, stops where it calls it, with the line that links libsodium, the one backend that has +// it (design D32). +#include + +#include +#include + +int main() { + std::array const der{}; + std::array out{}; + return webcpp::crypto::pem::armour("A", der, out) ? 0 : 1; +} diff --git a/tools/test/fixtures/crypto_jamfiles/pem_default_not_linked_on_emscripten/pem_default_not_linked_on_emscripten.outcome b/tools/test/fixtures/crypto_jamfiles/pem_default_not_linked_on_emscripten/pem_default_not_linked_on_emscripten.outcome new file mode 100644 index 00000000..75a70e25 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/pem_default_not_linked_on_emscripten/pem_default_not_linked_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/pem_default_not_linked); compile-diagnostic is clang's and skips Emscripten, so +# this fixture is the Emscripten one. +[all] +targets: emscripten +build: fails +# tag::messages[] +contains: webcpp::crypto: PEM's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /webcpp/crypto//pem-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//pem-default ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c) +# end::messages[] diff --git a/tools/test/fixtures/crypto_jamfiles/sealed_box_default/Jamfile b/tools/test/fixtures/crypto_jamfiles/sealed_box_default/Jamfile new file mode 100644 index 00000000..72b4fcea --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/sealed_box_default/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/crypto//crypto /webcpp/crypto//sealed_box-default ; +# end::jamfile[] diff --git a/tools/test/fixtures/crypto_jamfiles/sealed_box_default/app.cpp b/tools/test/fixtures/crypto_jamfiles/sealed_box_default/app.cpp new file mode 100644 index 00000000..f7fb125c --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/sealed_box_default/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) + +// Seals a message to Bob's public key on the default backend, opens it with Bob's key pair, +// checks that it opened as it was sealed, and prints the backend that ran. Bob's secret key is +// fixed here: a real program draws it from random_device. +#include +#include + +#include +#include +#include +#include +#include + +int main() { + using webcpp::crypto::hybrid::sealed_box; + std::array bob_secret{}; + bob_secret.fill(0x11); + auto const bob_public = webcpp::crypto::curves::x25519::public_key(bob_secret); + constexpr std::string_view feedback = "The coffee machine on the third floor is broken."; + std::array message{}; + std::ranges::copy(feedback, message.begin()); + std::array sealed{}; + std::array opened{}; + bool const ok = bob_public && sealed_box::seal(*bob_public, message, sealed) && + sealed_box::open(*bob_public, bob_secret, sealed, opened) && opened == message; + auto const name = sealed_box::backend_type::name; + std::printf("sealed_box %s backend=%.*s\n", ok ? "ok" : "FAILED", static_cast(name.size()), + name.data()); + return ok ? 0 : 1; +} diff --git a/tools/test/fixtures/crypto_jamfiles/sealed_box_default/sealed_box_default.outcome b/tools/test/fixtures/crypto_jamfiles/sealed_box_default/sealed_box_default.outcome new file mode 100644 index 00000000..0fda6902 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/sealed_box_default/sealed_box_default.outcome @@ -0,0 +1,20 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +[all] +targets: native wasip2 wasip3 emscripten +build: succeeds +run: app +# tag::output[] +[native] +sealed_box ok backend=sodium +[wasip2] +sealed_box ok backend=sodium +[wasip3] +sealed_box ok backend=sodium +[emscripten] +sealed_box ok backend=sodium +# end::output[] diff --git a/tools/test/fixtures/crypto_jamfiles/secp256k1_default/Jamfile b/tools/test/fixtures/crypto_jamfiles/secp256k1_default/Jamfile new file mode 100644 index 00000000..42e6d2ac --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/secp256k1_default/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/crypto//crypto /webcpp/crypto//secp256k1-default ; +# end::jamfile[] diff --git a/tools/test/fixtures/crypto_jamfiles/secp256k1_default/app.cpp b/tools/test/fixtures/crypto_jamfiles/secp256k1_default/app.cpp new file mode 100644 index 00000000..84d7baca --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/secp256k1_default/app.cpp @@ -0,0 +1,42 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// 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 + +int main() { + namespace secp256k1 = webcpp::crypto::curves::secp256k1; + std::array secret{}; + secret[31] = 3; + std::array const message{}; + std::array const aux{}; + std::array const expected{ + 0xe9, 0x07, 0x83, 0x1f, 0x80, 0x84, 0x8d, 0x10, 0x69, 0xa5, 0x37, 0x1b, 0x40, + 0x24, 0x10, 0x36, 0x4b, 0xdf, 0x1c, 0x5f, 0x83, 0x07, 0xb0, 0x08, 0x4c, 0x55, + 0xf1, 0xce, 0x2d, 0xca, 0x82, 0x15, 0x25, 0xf6, 0x6a, 0x4a, 0x85, 0xea, 0x8b, + 0x71, 0xe4, 0x82, 0xa7, 0x4f, 0x38, 0x2d, 0x2c, 0xe5, 0xeb, 0xee, 0xe8, 0xfd, + 0xb2, 0x17, 0x2f, 0x47, 0x7d, 0xf4, 0x90, 0x0d, 0x31, 0x05, 0x36, 0xc0, + }; + auto const key = secp256k1::keypair::make(secret); + bool ok = false; + if (key) { + auto const signature = key->sign_schnorr(message, aux); + auto const public_key = key->xonly_public_key(); + ok = signature && public_key && webcpp::crypto::equal(*signature, expected) && + secp256k1::verify_schnorr(*signature, message, *public_key); + } + auto const name = secp256k1::keypair::backend_type::name; + std::printf("schnorr %s backend=%.*s\n", ok ? "ok" : "FAILED", static_cast(name.size()), + name.data()); + return ok ? 0 : 1; +} diff --git a/tools/test/fixtures/crypto_jamfiles/secp256k1_default/secp256k1_default.outcome b/tools/test/fixtures/crypto_jamfiles/secp256k1_default/secp256k1_default.outcome new file mode 100644 index 00000000..6e04827c --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/secp256k1_default/secp256k1_default.outcome @@ -0,0 +1,20 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +[all] +targets: native wasip2 wasip3 emscripten +build: succeeds +run: app +# tag::output[] +[native] +schnorr ok backend=secp256k1 +[wasip2] +schnorr ok backend=secp256k1 +[wasip3] +schnorr ok backend=secp256k1 +[emscripten] +schnorr ok backend=secp256k1 +# end::output[] diff --git a/tools/test/fixtures/crypto_jamfiles/secret_of_no_bytes_on_emscripten/Jamfile b/tools/test/fixtures/crypto_jamfiles/secret_of_no_bytes_on_emscripten/Jamfile new file mode 100644 index 00000000..4b12ef4a --- /dev/null +++ b/tools/test/fixtures/crypto_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/crypto//crypto ; +# end::jamfile[] diff --git a/tools/test/fixtures/crypto_jamfiles/secret_of_no_bytes_on_emscripten/app.cpp b/tools/test/fixtures/crypto_jamfiles/secret_of_no_bytes_on_emscripten/app.cpp new file mode 100644 index 00000000..6112fe31 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/secret_of_no_bytes_on_emscripten/app.cpp @@ -0,0 +1,12 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// A program that names a secret of no bytes stops where it names it. +#include + +int main() { + return static_cast(webcpp::crypto::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/crypto_jamfiles/secret_of_no_bytes_on_emscripten/secret_of_no_bytes_on_emscripten.outcome new file mode 100644 index 00000000..7454a2fd --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/secret_of_no_bytes_on_emscripten/secret_of_no_bytes_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/secret_of_no_bytes); compile-diagnostic is clang's and skips Emscripten, so this +# fixture is the Emscripten one. +[all] +targets: emscripten +build: fails +# tag::messages[] +contains: webcpp::crypto: a secret of no bytes holds nothing. +# end::messages[] diff --git a/tools/test/fixtures/crypto_jamfiles/secretbox_xchacha20poly1305_default/Jamfile b/tools/test/fixtures/crypto_jamfiles/secretbox_xchacha20poly1305_default/Jamfile new file mode 100644 index 00000000..2653a726 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/secretbox_xchacha20poly1305_default/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/crypto//crypto /webcpp/crypto//secretbox_xchacha20poly1305-default ; +# end::jamfile[] diff --git a/tools/test/fixtures/crypto_jamfiles/secretbox_xchacha20poly1305_default/app.cpp b/tools/test/fixtures/crypto_jamfiles/secretbox_xchacha20poly1305_default/app.cpp new file mode 100644 index 00000000..6500b768 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/secretbox_xchacha20poly1305_default/app.cpp @@ -0,0 +1,58 @@ +// 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) + +// Seals a case of libsodium's XChaCha20 secret boxes (test/default/xchacha20.c) on the default +// 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 +#include +#include + +namespace { + +// The bytes of a string of lower-case hex digits, two per byte. +template +std::array from_hex(std::string_view hex) { + std::array bytes{}; + for (std::size_t index = 0; index < Size; ++index) { + auto const digit = [&](std::size_t at) { + char const c = hex[at]; + return static_cast(c <= '9' ? c - '0' : c - 'a' + 10); + }; + bytes[index] = static_cast((digit(2 * index) << 4U) | digit((2 * index) + 1)); + } + return bytes; +} + +} // namespace + +int main() { + using secretbox = webcpp::crypto::ciphers::secretbox_xchacha20poly1305<>; + auto const key = + from_hex<32>("10c0ad4054b48d7d1de1d9ab6f782ca883d886573e9d18c1d47b6ee6b5208189"); + auto const iv = from_hex<24>("977edf57428d0e0247a3c88c9a9ec321bbaae1a4da8353b5"); + auto const plaintext = from_hex<21>("518e4a27949812424b2a381c3efea6055ee5e75eff"); + auto const expected_tag = from_hex<16>("0c801a037c2ed0500d6ef68e8d195ece"); + auto const expected = from_hex<21>("b05a15f8edb68b35773e81ac2aca18e9be53416f9a"); + auto data = plaintext; + auto sealer = secretbox::make(key); + bool ok = false; + if (sealer) { + auto const tag = sealer->seal(iv, {}, data); + ok = tag && webcpp::crypto::equal(*tag, expected_tag) && data == expected && + sealer->open(iv, {}, data, expected_tag) && data == plaintext; + } + auto const name = secretbox::backend_type::name; + std::printf("secretbox_xchacha20poly1305 %s backend=%.*s\n", ok ? "ok" : "FAILED", + static_cast(name.size()), name.data()); + return ok ? 0 : 1; +} diff --git a/tools/test/fixtures/crypto_jamfiles/secretbox_xchacha20poly1305_default/secretbox_xchacha20poly1305_default.outcome b/tools/test/fixtures/crypto_jamfiles/secretbox_xchacha20poly1305_default/secretbox_xchacha20poly1305_default.outcome new file mode 100644 index 00000000..dbaf6846 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/secretbox_xchacha20poly1305_default/secretbox_xchacha20poly1305_default.outcome @@ -0,0 +1,20 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +[all] +targets: native wasip2 wasip3 emscripten +build: succeeds +run: app +# tag::output[] +[native] +secretbox_xchacha20poly1305 ok backend=sodium +[wasip2] +secretbox_xchacha20poly1305 ok backend=sodium +[wasip3] +secretbox_xchacha20poly1305 ok backend=sodium +[emscripten] +secretbox_xchacha20poly1305 ok backend=sodium +# end::output[] diff --git a/tools/test/fixtures/crypto_jamfiles/secretbox_xsalsa20poly1305_default/Jamfile b/tools/test/fixtures/crypto_jamfiles/secretbox_xsalsa20poly1305_default/Jamfile new file mode 100644 index 00000000..4251a365 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/secretbox_xsalsa20poly1305_default/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/crypto//crypto /webcpp/crypto//secretbox_xsalsa20poly1305-default ; +# end::jamfile[] diff --git a/tools/test/fixtures/crypto_jamfiles/secretbox_xsalsa20poly1305_default/app.cpp b/tools/test/fixtures/crypto_jamfiles/secretbox_xsalsa20poly1305_default/app.cpp new file mode 100644 index 00000000..736a015a --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/secretbox_xsalsa20poly1305_default/app.cpp @@ -0,0 +1,64 @@ +// 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) + +// Seals NaCl's secret box (libsodium's test/default/secretbox.c) on the default backend, checks +// 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 +#include +#include +#include + +namespace { + +// The bytes of a string of lower-case hex digits, two per byte. +template +std::array from_hex(std::string_view hex) { + std::array bytes{}; + for (std::size_t index = 0; index < Size; ++index) { + auto const digit = [&](std::size_t at) { + char const c = hex[at]; + return static_cast(c <= '9' ? c - '0' : c - 'a' + 10); + }; + bytes[index] = static_cast((digit(2 * index) << 4U) | digit((2 * index) + 1)); + } + return bytes; +} + +} // namespace + +int main() { + using secretbox = webcpp::crypto::ciphers::secretbox<>; + auto const key = + from_hex<32>("1b27556473e985d462cd51197a9a46c76009549eac6474f206c4ee0844f68389"); + auto const iv = from_hex<24>("69696ee955b62b73cd62bda875fc73d68219e0036b7a0b37"); + auto const plaintext = from_hex<131>( + "be075fc53c81f2d5cf141316ebeb0c7b5228c52a4c62cbd44b66849b64244ffce5ecbaaf33bd751a1ac7" + "28d45e6c61296cdc3c01233561f41db66cce314adb310e3be8250c46f06dceea3a7fa1348057e2f6556a" + "d6b1318a024a838f21af1fde048977eb48f59ffd4924ca1c60902e52f0a089bc76897040e082f9377638" + "48645e0705"); + auto const expected_tag = from_hex<16>("f3ffc7703f9400e52a7dfb4b3d3305d9"); + auto const expected_head = from_hex<8>("8e993b9f48681273"); + auto data = plaintext; + auto sealer = secretbox::make(key); + bool ok = false; + if (sealer) { + auto const tag = sealer->seal(iv, {}, data); + ok = tag && webcpp::crypto::equal(*tag, expected_tag) && + std::equal(expected_head.begin(), expected_head.end(), data.begin()) && + sealer->open(iv, {}, data, expected_tag) && data == plaintext; + } + auto const name = secretbox::backend_type::name; + std::printf("secretbox %s backend=%.*s\n", ok ? "ok" : "FAILED", static_cast(name.size()), + name.data()); + return ok ? 0 : 1; +} diff --git a/tools/test/fixtures/crypto_jamfiles/secretbox_xsalsa20poly1305_default/secretbox_xsalsa20poly1305_default.outcome b/tools/test/fixtures/crypto_jamfiles/secretbox_xsalsa20poly1305_default/secretbox_xsalsa20poly1305_default.outcome new file mode 100644 index 00000000..abd9f4ae --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/secretbox_xsalsa20poly1305_default/secretbox_xsalsa20poly1305_default.outcome @@ -0,0 +1,20 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +[all] +targets: native wasip2 wasip3 emscripten +build: succeeds +run: app +# tag::output[] +[native] +secretbox ok backend=sodium +[wasip2] +secretbox ok backend=sodium +[wasip3] +secretbox ok backend=sodium +[emscripten] +secretbox ok backend=sodium +# end::output[] diff --git a/tools/test/fixtures/crypto_jamfiles/sodium_not_linked_on_emscripten/Jamfile b/tools/test/fixtures/crypto_jamfiles/sodium_not_linked_on_emscripten/Jamfile new file mode 100644 index 00000000..4b12ef4a --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/sodium_not_linked_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/crypto//crypto ; +# end::jamfile[] diff --git a/tools/test/fixtures/crypto_jamfiles/sodium_not_linked_on_emscripten/app.cpp b/tools/test/fixtures/crypto_jamfiles/sodium_not_linked_on_emscripten/app.cpp new file mode 100644 index 00000000..75c5936e --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/sodium_not_linked_on_emscripten/app.cpp @@ -0,0 +1,12 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// A program that names libsodium and links none. +#include + +int main() { + return 0; +} diff --git a/tools/test/fixtures/crypto_jamfiles/sodium_not_linked_on_emscripten/sodium_not_linked_on_emscripten.outcome b/tools/test/fixtures/crypto_jamfiles/sodium_not_linked_on_emscripten/sodium_not_linked_on_emscripten.outcome new file mode 100644 index 00000000..2891d621 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/sodium_not_linked_on_emscripten/sodium_not_linked_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 #error 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/sodium_not_linked); compile-diagnostic is clang's and skips Emscripten, so this +# fixture is the Emscripten one. +[all] +targets: emscripten +build: fails +# tag::messages[] +contains: webcpp::crypto: the backend libsodium is used and not linked. In the program's Jamfile, add /third_party//sodium beside /webcpp/crypto//crypto, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//sodium ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c) +# end::messages[] diff --git a/tools/test/fixtures/crypto_jamfiles/threads_on_emscripten/Jamfile b/tools/test/fixtures/crypto_jamfiles/threads_on_emscripten/Jamfile new file mode 100644 index 00000000..a8a48e7d --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/threads_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/crypto//crypto : multi ; +# end::jamfile[] diff --git a/tools/test/fixtures/crypto_jamfiles/threads_on_emscripten/app.cpp b/tools/test/fixtures/crypto_jamfiles/threads_on_emscripten/app.cpp new file mode 100644 index 00000000..7bb15c54 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/threads_on_emscripten/app.cpp @@ -0,0 +1,22 @@ +// 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 for Emscripten built with -pthread (b2's threading=multi) has threads: +// WEBCPP_CRYPTO_HAS_THREADS is defined, and the heavy operations' async_ variants exist. +#include + +#include + +#ifndef __EMSCRIPTEN_PTHREADS__ +#error "the fixture's Jamfile builds this program with threading=multi, which is -pthread" +#endif +#ifndef WEBCPP_CRYPTO_HAS_THREADS +#error "WEBCPP_CRYPTO_HAS_THREADS is not defined with -pthread on Emscripten" +#endif + +int main() { + std::cout << "webcpp::crypto has threads\n"; +} diff --git a/tools/test/fixtures/crypto_jamfiles/threads_on_emscripten/threads_on_emscripten.outcome b/tools/test/fixtures/crypto_jamfiles/threads_on_emscripten/threads_on_emscripten.outcome new file mode 100644 index 00000000..a646fafb --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/threads_on_emscripten/threads_on_emscripten.outcome @@ -0,0 +1,15 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +# The Emscripten build with -pthread of test/threads_config_test.cpp's rule (design D23): b2's +# threading=multi gives -pthread, and WEBCPP_CRYPTO_HAS_THREADS is defined. +[all] +targets: emscripten +build: succeeds +run: app +# tag::output[] +webcpp::crypto has threads +# end::output[] diff --git a/tools/test/fixtures/crypto_jamfiles/web/web.outcome b/tools/test/fixtures/crypto_jamfiles/web/web.outcome index c9e860a3..dc1d5ffb 100644 --- a/tools/test/fixtures/crypto_jamfiles/web/web.outcome +++ b/tools/test/fixtures/crypto_jamfiles/web/web.outcome @@ -5,7 +5,7 @@ # https://www.boost.org/LICENSE_1_0.txt) [all] -targets: native wasip2 wasip3 emscripten +targets: wasip2 wasip3 emscripten build: succeeds run: app # tag::output[] diff --git a/tools/test/fixtures/crypto_jamfiles/x25519_default/Jamfile b/tools/test/fixtures/crypto_jamfiles/x25519_default/Jamfile new file mode 100644 index 00000000..1a7d8535 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/x25519_default/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/crypto//crypto /webcpp/crypto//x25519-default ; +# end::jamfile[] diff --git a/tools/test/fixtures/crypto_jamfiles/x25519_default/app.cpp b/tools/test/fixtures/crypto_jamfiles/x25519_default/app.cpp new file mode 100644 index 00000000..99d4f072 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/x25519_default/app.cpp @@ -0,0 +1,40 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// Agrees RFC 7748's shared secret (section 6.1) from Alice's secret key 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 + +int main() { + namespace x25519 = webcpp::crypto::curves::x25519; + std::array const alice_secret{ + 0x77, 0x07, 0x6d, 0x0a, 0x73, 0x18, 0xa5, 0x7d, 0x3c, 0x16, 0xc1, + 0x72, 0x51, 0xb2, 0x66, 0x45, 0xdf, 0x4c, 0x2f, 0x87, 0xeb, 0xc0, + 0x99, 0x2a, 0xb1, 0x77, 0xfb, 0xa5, 0x1d, 0xb9, 0x2c, 0x2a, + }; + std::array const bob_public{ + 0xde, 0x9e, 0xdb, 0x7d, 0x7b, 0x7d, 0xc1, 0xb4, 0xd3, 0x5b, 0x61, + 0xc2, 0xec, 0xe4, 0x35, 0x37, 0x3f, 0x83, 0x43, 0xc8, 0x5b, 0x78, + 0x67, 0x4d, 0xad, 0xfc, 0x7e, 0x14, 0x6f, 0x88, 0x2b, 0x4f, + }; + std::array const expected{ + 0x4a, 0x5d, 0x9d, 0x5b, 0xa4, 0xce, 0x2d, 0xe1, 0x72, 0x8e, 0x3b, + 0xf4, 0x80, 0x35, 0x0f, 0x25, 0xe0, 0x7e, 0x21, 0xc9, 0x47, 0xd1, + 0x9e, 0x33, 0x76, 0xf0, 0x9b, 0x3c, 0x1e, 0x16, 0x17, 0x42, + }; + auto const shared = x25519::agree(alice_secret, bob_public); + bool const ok = shared && webcpp::crypto::equal(shared->bytes(), expected); + auto const name = x25519::algorithm<>::backend_type::name; + std::printf("x25519 %s backend=%.*s\n", ok ? "ok" : "FAILED", static_cast(name.size()), + name.data()); + return ok ? 0 : 1; +} diff --git a/tools/test/fixtures/crypto_jamfiles/x25519_default/x25519_default.outcome b/tools/test/fixtures/crypto_jamfiles/x25519_default/x25519_default.outcome new file mode 100644 index 00000000..924f3ae7 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/x25519_default/x25519_default.outcome @@ -0,0 +1,20 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +[all] +targets: native wasip2 wasip3 emscripten +build: succeeds +run: app +# tag::output[] +[native] +x25519 ok backend=sodium +[wasip2] +x25519 ok backend=sodium +[wasip3] +x25519 ok backend=sodium +[emscripten] +x25519 ok backend=sodium +# end::output[] diff --git a/tools/test/fixtures/crypto_jamfiles/x25519_default_not_linked_on_emscripten/Jamfile b/tools/test/fixtures/crypto_jamfiles/x25519_default_not_linked_on_emscripten/Jamfile new file mode 100644 index 00000000..4b12ef4a --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/x25519_default_not_linked_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/crypto//crypto ; +# end::jamfile[] diff --git a/tools/test/fixtures/crypto_jamfiles/x25519_default_not_linked_on_emscripten/app.cpp b/tools/test/fixtures/crypto_jamfiles/x25519_default_not_linked_on_emscripten/app.cpp new file mode 100644 index 00000000..b5b44d97 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/x25519_default_not_linked_on_emscripten/app.cpp @@ -0,0 +1,18 @@ +// 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 agrees an X25519 shared secret on its default backend, libsodium on every target, +// without linking it, stops where it calls it, with the line that links libsodium, the one backend +// that has it (design D32). +#include + +#include +#include + +int main() { + std::array const key{}; + return webcpp::crypto::curves::x25519::agree(key, key) ? 0 : 1; +} diff --git a/tools/test/fixtures/crypto_jamfiles/x25519_default_not_linked_on_emscripten/x25519_default_not_linked_on_emscripten.outcome b/tools/test/fixtures/crypto_jamfiles/x25519_default_not_linked_on_emscripten/x25519_default_not_linked_on_emscripten.outcome new file mode 100644 index 00000000..f3f7cba6 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/x25519_default_not_linked_on_emscripten/x25519_default_not_linked_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/x25519_default_not_linked); compile-diagnostic is clang's and skips Emscripten, so +# this fixture is the Emscripten one. +[all] +targets: emscripten +build: fails +# tag::messages[] +contains: webcpp::crypto: X25519's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /webcpp/crypto//x25519-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//x25519-default ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c) +# end::messages[] diff --git a/tools/test/fixtures/crypto_jamfiles/xchacha20_poly1305_default/Jamfile b/tools/test/fixtures/crypto_jamfiles/xchacha20_poly1305_default/Jamfile new file mode 100644 index 00000000..13b8d402 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/xchacha20_poly1305_default/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/crypto//crypto /webcpp/crypto//xchacha20_poly1305-default ; +# end::jamfile[] diff --git a/tools/test/fixtures/crypto_jamfiles/xchacha20_poly1305_default/app.cpp b/tools/test/fixtures/crypto_jamfiles/xchacha20_poly1305_default/app.cpp new file mode 100644 index 00000000..82106ade --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/xchacha20_poly1305_default/app.cpp @@ -0,0 +1,61 @@ +// 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) + +// Seals the XChaCha20-Poly1305 draft's example (appendix A.3.1) on the default backend, checks +// the tag and the ciphertext's first bytes against the draft's, opens it again, and prints the +// 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 +#include +#include +#include + +int main() { + using aead = webcpp::crypto::ciphers::xchacha20_poly1305<>; + // The key 0x80, 0x81, ..., 0x9f. + std::array key{}; + for (std::size_t index = 0; index < key.size(); ++index) { + key[index] = static_cast(0x80 + index); + } + // The nonce 0x40, 0x41, ..., 0x57. + std::array iv{}; + for (std::size_t index = 0; index < iv.size(); ++index) { + iv[index] = static_cast(0x40 + index); + } + // NOLINTBEGIN(readability-trailing-comma): it asks a list of one row, wrapped, for the comma + // and refuses it once clang-format puts the brace on a line of its own + std::array const additional_data{0x50, 0x51, 0x52, 0x53, 0xc0, 0xc1, + 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7}; + // NOLINTEND(readability-trailing-comma) + constexpr std::string_view sunscreen = + "Ladies and Gentlemen of the class of '99: If I could offer you only one tip for the " + "future, sunscreen would be it."; + std::array plaintext{}; + std::ranges::copy(sunscreen, plaintext.begin()); + auto data = plaintext; + std::array const expected_tag{ + 0xc0, 0x87, 0x59, 0x24, 0xc1, 0xc7, 0x98, 0x79, + 0x47, 0xde, 0xaf, 0xd8, 0x78, 0x0a, 0xcf, 0x49, + }; + std::array const expected_head{0xbd, 0x6d, 0x17, 0x9d, 0x3e, 0x83, 0xd4, 0x3b}; + auto sealer = aead::make(key); + bool ok = false; + if (sealer) { + auto const tag = sealer->seal(iv, additional_data, data); + ok = tag && webcpp::crypto::equal(*tag, expected_tag) && + std::equal(expected_head.begin(), expected_head.end(), data.begin()) && + sealer->open(iv, additional_data, data, expected_tag) && data == plaintext; + } + auto const name = aead::backend_type::name; + std::printf("xchacha20_poly1305 %s backend=%.*s\n", ok ? "ok" : "FAILED", + static_cast(name.size()), name.data()); + return ok ? 0 : 1; +} diff --git a/tools/test/fixtures/crypto_jamfiles/xchacha20_poly1305_default/xchacha20_poly1305_default.outcome b/tools/test/fixtures/crypto_jamfiles/xchacha20_poly1305_default/xchacha20_poly1305_default.outcome new file mode 100644 index 00000000..154edb96 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/xchacha20_poly1305_default/xchacha20_poly1305_default.outcome @@ -0,0 +1,20 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +[all] +targets: native wasip2 wasip3 emscripten +build: succeeds +run: app +# tag::output[] +[native] +xchacha20_poly1305 ok backend=sodium +[wasip2] +xchacha20_poly1305 ok backend=sodium +[wasip3] +xchacha20_poly1305 ok backend=sodium +[emscripten] +xchacha20_poly1305 ok backend=sodium +# end::output[] diff --git a/tools/test/libdatachannel_test.py b/tools/test/libdatachannel_test.py index 6d69e72e..9c04a7f5 100644 --- a/tools/test/libdatachannel_test.py +++ b/tools/test/libdatachannel_test.py @@ -142,6 +142,49 @@ def provider_header_plan(root: Path, properties: list[str]) -> None: assert not list((root / 'bin').rglob(artifact)), artifact +def test_an_interrupted_configuration_is_built_again(root: Path) -> None: + # A configuration is complete when its build record is: the archives and headers an + # interrupted build published before it, without the record, are built again, b2 -a or + # not, and a complete configuration is kept. Planted files stand for the outputs, OpenSSL's + # complete. + (root / 'Jamroot').write_text( + 'import webcpp-openssl ;\nimport webcpp-libdatachannel ;\n' + 'project : build-dir bin ;\n' + f'webcpp-openssl.declare "{root.as_posix()}" : ssl.h configuration.h\n' + ' : tools/openssl/build.py ;\n' + f'webcpp-libdatachannel.declare "{root.as_posix()}" : datachannel.hpp\n' + ' : tools/libdatachannel/build.py ;\n' + 'exe consumer : provider.cpp libdatachannel openssl ;\n') + (root / 'provider.cpp').write_text(SOURCE) + request = ('consumer', 'toolset=clang', 'variant=release', 'threading=multi') + env = {'BOOST_BUILD_PATH': str(root / 'tools')} + planned = harness.run_b2(root, '-n', *request, env_extra=env) + harness.expect(planned, True, 'webcpp-openssl.build', 'webcpp-libdatachannel.build') + openssl = root / re.findall(r'^webcpp-openssl\.build (.+[/\\])libssl\.a$', + planned.stdout, re.M)[0] + datachannel = root / re.findall( + r'^webcpp-libdatachannel\.build (.+[/\\])libdatachannel\.a$', planned.stdout, re.M)[0] + for name in ('libssl.a', 'libcrypto.a', 'build.json', 'include/openssl/ssl.h', + 'include/openssl/configuration.h'): + (openssl / name).parent.mkdir(parents=True, exist_ok=True) + (openssl / name).write_text('a complete OpenSSL configuration\n') + for name in ('libdatachannel.a', 'libjuice.a', 'libusrsctp.a', 'libsrtp2.a', + 'include/rtc/datachannel.hpp'): + (datachannel / name).parent.mkdir(parents=True, exist_ok=True) + (datachannel / name).write_text('published before the interruption\n') + for flags in ((), ('-a',)): + planned = harness.run_b2(root, '-n', *flags, *request, env_extra=env) + harness.expect(planned, True) + assert re.search(r'^webcpp-libdatachannel\.build ', planned.stdout, re.M), planned.stdout + assert 'webcpp-libdatachannel.prepare-headers' not in planned.stdout, planned.stdout + assert 'webcpp-openssl.' not in planned.stdout, planned.stdout + (datachannel / 'build.json').write_text('{}\n') + for flags in ((), ('-a',)): + planned = harness.run_b2(root, '-n', *flags, *request, env_extra=env) + harness.expect(planned, True) + assert 'webcpp-libdatachannel.' not in planned.stdout, planned.stdout + + def test_headers_only_do_not_build_upstream_proof(root: Path) -> None: provider_header_plan(root, ['toolset=clang', 'threading=multi', 'webcpp-openssl-tests=on']) @@ -195,6 +238,7 @@ def test_msvc_runtime_and_custom_cpp_flags_reach_both_dependencies(root: Path) - CASES = [test_one_native_provider_in_a_path_with_spaces, + test_an_interrupted_configuration_is_built_again, test_headers_only_do_not_build_upstream_proof, test_headers_only_do_not_build_msvc_symbols, test_msvc_runtime_and_custom_cpp_flags_reach_both_dependencies, diff --git a/tools/test/openssl_test.py b/tools/test/openssl_test.py index 4e1c4268..e89992bd 100644 --- a/tools/test/openssl_test.py +++ b/tools/test/openssl_test.py @@ -200,6 +200,39 @@ def test_a_built_configuration_is_kept_and_selected(root: Path) -> None: assert '**passed**' not in result.stdout, result.stdout +def test_an_interrupted_configuration_is_built_again(root: Path) -> None: + # A configuration is complete when its build record is: the archives and headers an + # interrupted build published before it, without the record, are built again, b2 -a or + # not, and a complete configuration is kept. Planted files stand for the outputs. + (root / 'Jamroot').write_text( + 'import webcpp-openssl ;\n' + 'project : build-dir bin ;\n' + f'webcpp-openssl.declare "{root.as_posix()}" : ssl.h configuration.h\n' + ' : tools/openssl/build.py ;\n' + 'exe consumer : uses_openssl.cpp openssl ;\n') + (root / 'uses_openssl.cpp').write_text(SOURCE) + request = ('consumer', 'toolset=clang', 'variant=release', 'threading=single') + env = {'BOOST_BUILD_PATH': str(root / 'tools')} + planned = harness.run_b2(root, '-n', *request, env_extra=env) + harness.expect(planned, True, 'webcpp-openssl.build') + directory = root / re.findall(r'^webcpp-openssl\.build (.+[/\\])libssl\.a$', + planned.stdout, re.M)[0] + for name in ('libssl.a', 'libcrypto.a', 'include/openssl/ssl.h', + 'include/openssl/configuration.h'): + (directory / name).parent.mkdir(parents=True, exist_ok=True) + (directory / name).write_text('published before the interruption\n') + for flags in ((), ('-a',)): + planned = harness.run_b2(root, '-n', *flags, *request, env_extra=env) + harness.expect(planned, True) + assert re.search(r'^webcpp-openssl\.build ', planned.stdout, re.M), planned.stdout + assert 'webcpp-openssl.generate-headers' not in planned.stdout, planned.stdout + (directory / 'build.json').write_text('{}\n') + for flags in ((), ('-a',)): + planned = harness.run_b2(root, '-n', *flags, *request, env_extra=env) + harness.expect(planned, True) + assert 'webcpp-openssl.' not in planned.stdout, planned.stdout + + def test_wasip2_source_dependency(root: Path) -> None: jam = JAM.replace('import webcpp ;', 'import webcpp ;\nwebcpp.targets wasip2 ;') harness.add_library(root, 'openssl_user', jam, {'uses_openssl.cpp': SOURCE}) @@ -521,6 +554,7 @@ def test_source_archive_tampering_fails_before_configuration(root: Path) -> None test_upstream_failure_prevents_archive_publication, test_native_source_dependency, test_one_c_configuration_is_built_once, test_a_built_configuration_is_kept_and_selected, + test_an_interrupted_configuration_is_built_again, test_wasip2_source_dependency, test_symlinked_compiler_without_c_sibling, test_msvc_build_commands_preserve_the_consumers_configuration, diff --git a/tools/test/third_party_test.py b/tools/test/third_party_test.py index a1f8ab06..d0fe8a38 100755 --- a/tools/test/third_party_test.py +++ b/tools/test/third_party_test.py @@ -20,11 +20,11 @@ webcpp::hash's adapter and canary, and an XKCP or a libs/hash that is not checked out stops it, naming the command. libsodium, pinned, is built file by file with the defines its own configure finds on each target and -webcpp::hash's canary, its version.h copied into the build directory and its checkout left as it -was. BLAKE3's C implementation, pinned, is built file by file with webcpp::hash's canary: natively -with the intrinsics files of the machine's instruction sets, each with its own flag, and on -WebAssembly with the portable code alone. BLAKE2's test vectors are pinned. Run with the names of -some cases to run only those.""" +webcpp::hash's canary, and webcpp::crypto's when libs/crypto is checked out, its version.h copied +into the build directory and its checkout left as it was. BLAKE3's C implementation, pinned, is +built file by file with webcpp::hash's canary: natively with the intrinsics files of the machine's +instruction sets, each with its own flag, and on WebAssembly with the portable code alone. BLAKE2's +test vectors are pinned. Run with the names of some cases to run only those.""" from __future__ import annotations @@ -95,6 +95,12 @@ # /third_party//blake2_vectors). BLAKE2_COMMIT = 'ed1974ea83433eba7b2d95c5dcd9ac33cb847913' +ED25519_SPECCHECK = 'third_party/libs/ed25519-speccheck' + +# The commit novifinancial/ed25519-speccheck is pinned at: the twelve Ed25519 edge cases of +# "Taming the many EdDSAs", its cases.json (libs/crypto/test/ed25519_speccheck_test.cpp). +ED25519_SPECCHECK_COMMIT = '65519336fda78a3d016e947df6d82848aca0c9da' + SECP256K1 = 'third_party/libs/secp256k1' # libsecp256k1 v0.8.0, the commit it is pinned at. @@ -148,6 +154,9 @@ # from libsodium's configure. SODIUM_CANARY = ('webcpp_hash_sodium_77e1ce5_configured__add_third_party_sodium_to_your_link') +# webcpp::crypto's canary on the same target: its configuration is portable under the same defines. +SODIUM_CRYPTO_CANARY = 'webcpp_crypto_sodium_77e1ce5_portable__add_third_party_sodium_to_your_link' + # The defines of every target: webcpp's three, then those libsodium's configure finds on every # target and its C files read. SODIUM_COMMON = {'CONFIGURED=1', 'SODIUM_STATIC=1', 'NATIVE_LITTLE_ENDIAN=1', 'HAVE_ALLOCA=1', @@ -318,6 +327,12 @@ def test_bips_is_pinned(_: Path) -> None: assert listed.stdout.split()[:2] == ['160000', BIPS_COMMIT], listed.stdout +def test_ed25519_speccheck_is_pinned(_: Path) -> None: + listed = subprocess.run(['git', '-C', str(harness.ROOT), 'ls-files', '-s', ED25519_SPECCHECK], + capture_output=True, text=True, check=True) + assert listed.stdout.split()[:2] == ['160000', ED25519_SPECCHECK_COMMIT], listed.stdout + + def test_bearssl_is_pinned(_: Path) -> None: listed = subprocess.run(['git', '-C', str(harness.ROOT), 'ls-files', '-s', BEARSSL], capture_output=True, text=True, check=True) @@ -433,6 +448,19 @@ def test_a_suite_not_checked_out_is_refused(root: Path) -> None: harness.expect(harness.run_b2(root, 'libs/demo/test//pass'), True) +def test_ed25519_speccheck_not_checked_out_is_refused(root: Path) -> None: + harness.third_party_of_its_own(root, 'ed25519-speccheck', checked_out=False) + harness.add_library(root, 'speccheck_reader', ( + 'import webcpp ;\n\nwebcpp.run reads_cases : reads_cases.cpp\n' + ' : /webcpp/third_party//ed25519-speccheck ;\n'), + {'reads_cases.cpp': 'int main() { return 0; }\n'}) + result = harness.run_b2(root, 'libs/speccheck_reader/test') + harness.expect(result, False, 'third_party/libs/ed25519-speccheck is not checked out', + 'git submodule update --init third_party/libs/ed25519-speccheck') + # A build that needs no cases never looks for them. + harness.expect(harness.run_b2(root, 'libs/demo/test//pass'), True) + + def test_ctaes_not_checked_out_is_refused(root: Path) -> None: harness.copy_integration_libraries(root, 'config', 'crypto') harness.third_party_of_its_own(root, 'bitcoin', checked_out=False) @@ -594,6 +622,25 @@ def test_sodium_is_built_file_by_file(root: Path) -> None: assert f'{prefix}{SODIUM_CANARY}' in symbols.stdout.split(), symbols.stdout[-2000:] +def test_sodium_carries_cryptos_canary_too(root: Path) -> None: + # With libs/crypto beside libs/hash, libsodium gains webcpp::crypto's canary, compiled with + # libsodium's defines: one more file, a second symbol, and the define its header asks for. + harness.copy_integration_libraries(root, 'config', 'crypto', 'hash') + result = harness.run_b2(root, '-a', '-d+2', 'third_party//sodium') + harness.expect(result, True) + lines = compiled_sodium(result) + # The 141 C files of libsodium's src/libsodium and the canaries of webcpp::hash and crypto. + assert len(lines) == 143, (len(lines), result.stdout[-4000:]) + expect_sodium_defines(lines, None) + archive = sorted((root / 'bin').rglob('libsodium.a')) + assert len(archive) == 1, archive + symbols = subprocess.run(['nm', str(archive[0])], capture_output=True, text=True, check=True) + prefix = '_' if sys.platform == 'darwin' else '' + names = symbols.stdout.split() + assert f'{prefix}{SODIUM_CANARY}' in names, symbols.stdout[-2000:] + assert f'{prefix}{SODIUM_CRYPTO_CANARY}' in names, symbols.stdout[-2000:] + + def test_sodium_defines_on_each_webassembly_target(root: Path) -> None: # -n prints each command without running it: the defines, not the build, are the case's. harness.link_emsdk(root) @@ -832,7 +879,9 @@ def test_hash_not_checked_out_stops_blake3(root: Path) -> None: test_the_suite_reaches_a_test_on_wasi, test_a_changed_suite_file_runs_the_test_again, test_a_suite_not_checked_out_is_refused, + test_ed25519_speccheck_not_checked_out_is_refused, test_bips_is_pinned, + test_ed25519_speccheck_is_pinned, test_bearssl_is_pinned, test_bearssl_is_built_file_by_file, test_bearssl_without_hash_has_cryptos_canary_alone, @@ -853,6 +902,7 @@ def test_hash_not_checked_out_stops_blake3(root: Path) -> None: test_hash_not_checked_out_is_refused, test_sodium_is_pinned, test_sodium_is_built_file_by_file, + test_sodium_carries_cryptos_canary_too, test_sodium_defines_on_each_webassembly_target, test_sodium_test_config_reaches_the_private_headers, test_sodium_msvc_inline_reaches_c_alone, diff --git a/tools/test/webcpp_jam_test.py b/tools/test/webcpp_jam_test.py index 74039523..985753fc 100755 --- a/tools/test/webcpp_jam_test.py +++ b/tools/test/webcpp_jam_test.py @@ -14,8 +14,9 @@ output, its standard input its .input file or nothing; every public header compiles alone, each call of webcpp.headers-alone taking the headers its globs match, with requirements and targets of its own, and a header two calls take or a glob that matches none refused; a compile-diagnostic test -passes only on the error it states, fails on a directive clang's -verify drops (a header it names -that cannot be located), and is skipped on a toolset that is not clang; +passes only on the error it states, with `alone` fails on any other error, fails on a directive +clang's -verify drops (a header it names that cannot be located), and is skipped on a toolset that +is not clang; `b2 declared-targets` lists what each library declares; a lane of a library's own is listed once per target it runs on, which must be one its Jamfile declares, with its kind, whether it runs the original's language; what it names leaves the ordinary lanes, a build of it for another target stops @@ -28,11 +29,14 @@ when its sources built with a library and without it give byte-identical programs, the same name in two directories, linked with the same flags, the linker's removal of unused sections included, with exceptions on or off, and fails naming both files and their sizes when the library's code is -called. Each case builds a scratch -superproject with the fixture library demo. Run with the names of some cases to run only those.""" +called; and webcpp.program-sizes sizes webcpp.link's programs against a baseline from release +builds alone, whatever variant is asked for, and refuses a program it cannot size on each of its +targets. Each case builds a scratch superproject with the fixture library demo. Run with the +names of some cases to run only those.""" from __future__ import annotations +import json import os import re import shutil @@ -379,6 +383,50 @@ def test_compile_diagnostic_fails_on_a_directive_clang_drops(root): harness.expect(harness.run_b2(root, *kept), False, 'the check changed') +def test_compile_diagnostic_alone_fails_on_any_other_error(root): + # With `alone`, the errors a test states are its compile's only ones: a refusal that must be + # the first and only error fails its test when another error follows it, which the rule's + # tolerance of a header's cascade of errors would otherwise hide. An expected note is still + # tolerated, as is a note that comes with the stated error. Another word than `alone` is + # refused. + guard = '#error "the guard says no"\n' + stated = ('// expected-error@guard.hpp:* {{the guard says no}}\n' + '#include "guard.hpp"\n' + 'int main() { return 0; }\n') + harness.add_library( + root, 'alone', + 'import webcpp ;\n' + '\n' + 'webcpp.targets native wasip2 ;\n' + '\n' + 'webcpp.compile-diagnostic only : only.cpp : : : alone ;\n' + 'webcpp.compile-diagnostic noted : noted.cpp : : : alone ;\n' + 'webcpp.compile-diagnostic followed : followed.cpp : : : alone ;\n' + 'webcpp.compile-diagnostic tolerated : followed.cpp ;\n', + {'guard.hpp': guard, 'only.cpp': stated, + 'noted.cpp': ('template void needs_int(T) requires(sizeof(T) == 4) {}\n' + 'void call() {\n' + ' // expected-error@+1 {{no matching function}}\n' + ' needs_int(1.0);\n' + '}\n'), + # The stated error, then another. + 'followed.cpp': stated.replace('return 0;', 'return undeclared;')}) + result = harness.run_b2(root, *(f'libs/alone/test//{name}' + for name in ('only', 'noted', 'tolerated'))) + harness.expect(result, True) + assert passed(result) == {'only', 'noted', 'tolerated'}, (passed(result), + result.stdout[-4000:]) + for arguments in ((), WASIP2): + result = harness.run_b2(root, *arguments, 'libs/alone/test//followed') + harness.expect(result, False, 'seen but not expected', 'undeclared') + assert not passed(result), result.stdout[-4000:] + (root / 'libs/alone/test/Jamfile').write_text( + 'import webcpp ;\n\nwebcpp.compile-diagnostic only : only.cpp : : : first ;\n') + result = harness.run_b2(root, 'libs/alone/test') + harness.expect(result, False, 'webcpp.compile-diagnostic only: first is not alone') + assert 'libs/alone/test/Jamfile:' in result.stdout, result.stdout[-4000:] + + def test_filter_maps_each_toolset_to_its_target(root): # webcpp.filter called directly, with a toolset's properties and a program's targets: it # returns no when the toolset builds for none of them. Only clang's version names a @@ -714,6 +762,82 @@ def test_programs_of_records_link_and_drive(root): ], result.stdout +SIZED = ('import webcpp ;\n' + '\n' + 'webcpp.targets native wasip2 wasip3 ;\n' + 'webcpp.link baseline : baseline.cpp ;\n' + 'webcpp.link larger : larger.cpp ;\n' + 'webcpp.run plain : plain.cpp ;\n' + 'webcpp.link native_only : baseline.cpp : : native ;\n') + +SIZED_SOURCES = { + 'baseline.cpp': '#include \nint main() { std::puts("baseline"); }\n', + 'larger.cpp': ('#include \n#include \n' + 'int main(int argc, char**) {\n' + ' std::string text(static_cast(argc) * 40, \'x\');\n' + ' std::printf("%s %zu\\n", text.c_str(), std::hash{}(text));\n' + '}\n'), + 'plain.cpp': PLAIN_SOURCE, +} + + +def test_program_sizes_are_those_of_release_builds(root): + # webcpp.program-sizes sizes the programs webcpp.link declares against a baseline, on each + # target of its table, from release builds alone: asked for a debug build, it still builds + # its programs, its JSON and its table at variant=release. Natively the executable is + # stripped; on WASI the .wasm is read. Its lane is listed once per target. + harness.add_library(root, 'sized', SIZED + + 'webcpp.program-sizes sized : baseline : larger ;\n' + + 'webcpp.lane sizes : sized.sizes.md : native wasip2 ;\n', + SIZED_SOURCES) + result = harness.run_b2(root, '-d0', 'declared-lanes') + harness.expect(result, True) + assert 'sized sizes libs/sized/test native programs\n' in result.stdout, result.stdout + for target, request in (('native', ()), ('wasip2', WASIP2)): + result = harness.run_b2(root, '-a', f'--build-dir=bin/{target}', *request, + 'variant=debug', 'libs/sized/test//sizes') + harness.expect(result, True, '| larger |') + found = sorted((root / f'bin/{target}').rglob('sized.sizes.json')) + tables = sorted((root / f'bin/{target}').rglob('sized.sizes.md')) + assert len(found) == 1 and len(tables) == 1, (found, tables) + assert 'release' in found[0].parts and 'debug' not in found[0].parts, found + sized = json.loads(found[0].read_text()) + assert (sized['variant'], sized['target'], sized['baseline']) == ( + 'release', target, 'baseline'), sized + rows = {row['program']: row for row in sized['programs']} + assert sorted(rows) == ['baseline', 'larger'], rows + kind = 'executable' if target == 'native' else 'wasm' + assert rows['larger']['file'] == kind and rows['larger']['over_baseline'] > 0, rows + assert rows['baseline']['over_baseline'] == 0, rows + assert tables[0].read_text().startswith(f'Linked programs on {target} ('), tables + programs = [p for p in (root / f'bin/{target}').rglob('larger-program*') + if p.suffix in ('', '.wasm')] + assert programs and all('release' in p.parts for p in programs), programs + + +def test_program_sizes_refuse_what_they_cannot_size(root): + # Each program is one webcpp.link declares before the table, built on every target of the + # table: b2 would skip a make one of whose sources it skips, silently. + for line, message in ( + ('webcpp.program-sizes sized : baseline : plain ;\n', + 'webcpp.program-sizes sized in libs/sized/test/Jamfile: plain is not a program ' + 'webcpp.link declares before it in its Jamfile'), + ('webcpp.program-sizes sized : baseline : native_only ;\n', + 'webcpp.program-sizes sized in libs/sized/test/Jamfile: native_only is not built for ' + 'wasip2 wasip3'), + ('webcpp.program-sizes sized : baseline : larger : wasm ;\n', + 'webcpp.program-sizes sized in libs/sized/test/Jamfile: wasm is not a target'), + ): + shutil.rmtree(root / 'libs/sized', ignore_errors=True) + harness.add_library(root, 'sized', SIZED + line, SIZED_SOURCES) + harness.expect(harness.run_b2(root, '-d0', 'declared-lanes'), False, message) + shutil.rmtree(root / 'libs/sized') + harness.add_library(root, 'sized', + SIZED + 'webcpp.program-sizes sized : baseline : native_only : native ;\n', + SIZED_SOURCES) + harness.expect(harness.run_b2(root, '-d0', 'declared-lanes'), True) + + def test_example_mismatch_fails_naming_the_program(root): (root / 'libs/demo/example/hello.expected').write_text('The answer is 41.\n') result = harness.run_b2(root, 'libs/demo/example') @@ -1455,6 +1579,7 @@ def test_the_pair_is_found_by_its_directory_on_every_path_separator(root): test_a_compile_finds_the_test_support, test_compile_diagnostic_passes_only_on_its_diagnostic, test_compile_diagnostic_fails_on_a_directive_clang_drops, + test_compile_diagnostic_alone_fails_on_any_other_error, test_filter_maps_each_toolset_to_its_target, test_undeclared_jamfile_is_native_only, test_emscripten_builds_only_what_declares_it, @@ -1492,6 +1617,8 @@ def test_the_pair_is_found_by_its_directory_on_every_path_separator(root): test_the_pair_is_found_by_its_directory_on_every_path_separator, test_a_pair_built_without_exceptions_links_the_handler_and_compares_equal, test_a_shared_library_is_compared_as_a_static_one, + test_program_sizes_are_those_of_release_builds, + test_program_sizes_refuse_what_they_cannot_size, ] diff --git a/tools/variants/variants.py b/tools/variants/variants.py index cfcbe015..e6f3c607 100755 --- a/tools/variants/variants.py +++ b/tools/variants/variants.py @@ -5,10 +5,14 @@ # accompanying file LICENSE_1_0.txt or copy at # https://www.boost.org/LICENSE_1_0.txt) -"""Writes the manifest of a page program's suspension variants, and the table of their sizes. +"""Writes the manifest of a page program's suspension variants, the table of their sizes, and the +sizes of linked programs on any target. Usage: variants.py manifest --out FILE --jspi SCRIPT --asyncify SCRIPT variants.py table --variant VARIANT --out FILE MANIFEST... + variants.py programs --variant VARIANT --target TARGET --toolset TOOLSET + --baseline NAME --names NAME... --out FILE -- PROGRAM... + variants.py programs-table --out FILE JSON manifest writes FILE, .variants.json, which a page's loader reads: for each variant, the script, its JavaScript glue, relative to FILE's directory and written with /, and the size in bytes @@ -22,15 +26,32 @@ (webcpp.size-table, which requires release, gives it), other than release is refused before anything is written. +programs writes FILE, .sizes.json (webcpp.program-sizes), the sizes of the programs NAME, each +a -program file of webcpp.link among PROGRAM (other files, a project's library objects that b2 +appends to the make, are not programs): per file, its raw bytes, its gzip -9n bytes and their +excess over the baseline's same file, dated by the build, with the host it ran on and the format +of the program (natively ELF, PE or Mach-O, read from its file; else WebAssembly). The file is +natively the executable, stripped with strip (a copy: the program is left as it is); on wasip2 +and wasip3 the .wasm; on emscripten the .wasm and its .js glue, two rows. A name without its +program, a baseline not among the names, and a build at another VARIANT than release are refused +before anything is written. programs-table writes FILE, the Markdown table of such a JSON, and +prints it; it refuses a JSON not built at release. + A failure is a line on the standard error and status 1; a usage error is status 2. """ from __future__ import annotations import argparse +import datetime +import gzip import json import os +import platform +import shutil +import subprocess import sys +import tempfile from pathlib import Path, PurePath from typing import Any @@ -38,6 +59,9 @@ SUFFIX = '.variants.json' # The only b2 variant a size table is built from. RELEASE = 'release' +RELEASE_ONLY = 'a size table is built only from release builds, not variant={variant}: ' +# The suffix webcpp.link gives a program's explicit executable. +PROGRAM = '-program' class Refused(Exception): @@ -92,8 +116,8 @@ def table(out: Path, manifests: list[Path], variant: str) -> str: """Writes out, the Markdown table of the manifests' sizes, and returns it; refuses a build at another variant than release, and a manifest that is not one, before it writes anything.""" if variant != RELEASE: - raise Refused(f'a size table is built only from release builds, not variant={variant}: ' - 'webcpp.size-table requires release') + raise Refused(RELEASE_ONLY.format(variant=variant) + + 'webcpp.size-table requires release') rows = sorted((program(path), *sizes(path)) for path in manifests) lines = ['| program | jspi | asyncify | asyncify / jspi |', '| --- | ---: | ---: | ---: |'] lines += [f'| {name} | {jspi:,} | {asyncify:,} | {asyncify / jspi:.2f} |' @@ -103,6 +127,112 @@ def table(out: Path, manifests: list[Path], variant: str) -> str: return text +def gzipped(data: bytes) -> int: + """The bytes gzip -9n gives: no name and no time stamp in its header.""" + return len(gzip.compress(data, compresslevel=9, mtime=0)) + + +def stripped(path: Path) -> bytes: + """The bytes of path stripped by strip, from a copy: path is left as it is.""" + strip = shutil.which('strip') + if strip is None: + raise Refused('strip is not on PATH: a native program is sized stripped') + with tempfile.TemporaryDirectory(prefix='webcpp sizes ') as scratch: + copy = Path(scratch) / path.name + shutil.copyfile(path, copy) + done = subprocess.run([strip, str(copy)], capture_output=True, text=True, check=False) + if done.returncode != 0: + raise Refused(f'strip {path}: exit {done.returncode}: {done.stderr.strip()}') + return copy.read_bytes() + + +def files_of(path: Path, target: str) -> list[tuple[str, bytes]]: + """The files a program's size is read from, by kind, with their bytes: natively the executable + stripped; on WebAssembly the .wasm, and on emscripten the .js glue beside it.""" + if target == 'native': + return [('executable', stripped(path))] + wasm = path.with_suffix('.wasm') + files = [] + if path.suffix == '.js': + files.append(('js', path.read_bytes())) + if not wasm.is_file(): + raise Refused(f'{wasm} does not exist') + files.append(('wasm', wasm.read_bytes())) + return sorted(files) + + +# A native executable's format, by the first bytes of its file. +FORMATS = ((b'\x7fELF', 'ELF'), (b'MZ', 'PE'), (b'\xcf\xfa\xed\xfe', 'Mach-O'), + (b'\xca\xfe\xba\xbe', 'Mach-O')) + + +def format_of(path: Path, target: str) -> str: + """The format of a program's file: WebAssembly off native, else read from its magic.""" + if target != 'native': + return 'WebAssembly' + head = path.read_bytes()[:4] + for magic, name in FORMATS: + if head.startswith(magic): + return name + raise Refused(f'{path}: not an executable of a known format (ELF, PE, Mach-O)') + + +def name_of(path: Path) -> str: + """The webcpp.link program a file is of: its name less its suffix and -program.""" + stem = path.name if path.suffix not in ('.js', '.wasm', '.exe') else path.stem + return stem[:-len(PROGRAM)] if stem.endswith(PROGRAM) else stem + + +def programs(variant: str, target: str, toolset: str, baseline: str, names: list[str], + paths: list[Path]) -> dict[str, Any]: + """The sizes of the programs names, found among paths, against baseline's; refuses a build at + another variant than release, a baseline not among names, and a name without its program.""" + if variant != RELEASE: + raise Refused(RELEASE_ONLY.format(variant=variant) + + 'webcpp.program-sizes requires release') + if baseline not in names: + raise Refused(f'the baseline {baseline} is not among the programs named, ' + f'{" ".join(names)}') + found = {name_of(path): path for path in paths} + for name in names: + if name not in found: + raise Refused(f'{name} is not among the programs given') + measured = {name: files_of(found[name], target) for name in dict.fromkeys(names)} + base = {kind: (len(data), gzipped(data)) for kind, data in measured[baseline]} + rows = [] + for name in sorted(measured): + for kind, data in measured[name]: + raw, packed = len(data), gzipped(data) + rows.append({'program': name, 'file': kind, 'bytes': raw, 'gzip': packed, + 'over_baseline': raw - base[kind][0], + 'gzip_over_baseline': packed - base[kind][1]}) + return {'variant': variant, 'target': target, 'toolset': toolset, 'baseline': baseline, + 'date': datetime.date.today().isoformat(), + 'host': f'{platform.system()} {platform.machine()}', + 'format': format_of(found[baseline], target), 'programs': rows} + + +def programs_table(path: Path) -> str: + """The Markdown table of the sizes path holds; refuses data not built at release.""" + try: + read = json.loads(path.read_text()) + except (OSError, ValueError) as error: + raise Refused(f'{path}: cannot be read as JSON: {error}') from error + variant = read.get('variant') if isinstance(read, dict) else None + if variant != RELEASE: + raise Refused(f'{path}: ' + RELEASE_ONLY.format(variant=variant) + + 'webcpp.program-sizes requires release') + lines = [f'Linked programs on {read["target"]} ({read["format"]}), built with ' + f'{read["toolset"]} at variant={variant} on {read["date"]}, against the baseline ' + f'{read["baseline"]}.', '', + '| program | file | bytes | gzip -9n | over baseline | gzip -9n over baseline |', + '| --- | --- | ---: | ---: | ---: | ---: |'] + lines += [f'| {r["program"]} | {r["file"]} | {r["bytes"]:,} | {r["gzip"]:,} ' + f'| {r["over_baseline"]:,} | {r["gzip_over_baseline"]:,} |' + for r in read['programs']] + return '\n'.join(lines) + '\n' + + def parser() -> argparse.ArgumentParser: """The command line: the subcommands manifest and table.""" parsed = argparse.ArgumentParser( @@ -117,6 +247,18 @@ def parser() -> argparse.ArgumentParser: help='the b2 variant the manifests were built at: only release is taken') sized.add_argument('--out', type=Path, required=True) sized.add_argument('manifests', type=Path, nargs='+') + linked = commands.add_parser('programs', help='write the sizes of linked programs') + linked.add_argument('--variant', required=True, + help='the b2 variant the programs were built at: only release is taken') + linked.add_argument('--target', required=True) + linked.add_argument('--toolset', required=True) + linked.add_argument('--baseline', required=True) + linked.add_argument('--names', nargs='+', required=True) + linked.add_argument('--out', type=Path, required=True) + linked.add_argument('programs', type=Path, nargs='+') + tabled = commands.add_parser('programs-table', help='write the table of programs\' sizes') + tabled.add_argument('--out', type=Path, required=True) + tabled.add_argument('sizes', type=Path) return parsed @@ -127,6 +269,14 @@ def main(argv: list[str]) -> int: if arguments.command == 'manifest': manifest(arguments.out, {variant: getattr(arguments, variant) for variant in VARIANTS}) + elif arguments.command == 'programs': + sized = programs(arguments.variant, arguments.target, arguments.toolset, + arguments.baseline, arguments.names, arguments.programs) + arguments.out.write_text(json.dumps(sized, indent=4) + '\n') + elif arguments.command == 'programs-table': + text = programs_table(arguments.sizes) + arguments.out.write_text(text) + sys.stdout.write(text) else: sys.stdout.write(table(arguments.out, arguments.manifests, arguments.variant)) except Refused as refused: diff --git a/tools/variants/variants_test.py b/tools/variants/variants_test.py index 525228a1..e6864b46 100755 --- a/tools/variants/variants_test.py +++ b/tools/variants/variants_test.py @@ -10,11 +10,20 @@ is refused before anything is written; a table lists each program with its sizes and their ratio, in the file and on the standard output; a manifest that is not one is refused, naming it; and a table is written only from release builds: given another variant, or none, it is refused before -anything is written. Run with the names of some cases to run only those.""" +anything is written. The sizes of linked programs (webcpp.program-sizes) are each program's raw and +gzip -9n bytes and their excess over the baseline's: a native executable stripped, a WASI program's +.wasm, an Emscripten program's .wasm and its .js; a program not among the files given, a baseline +not among the programs, and a build at another variant than release are refused before anything is +written; their Markdown table is the JSON's, and it too refuses data not built at release. Run with +the names of some cases to run only those.""" from __future__ import annotations +import datetime +import gzip import json +import platform +import shutil import subprocess import sys import tempfile @@ -110,6 +119,146 @@ def test_table_refuses_a_build_that_is_not_release(root: Path) -> None: assert not out.exists() +def gzipped(data: bytes) -> int: + """What gzip -9n gives: no name and no time stamp in its header.""" + return len(gzip.compress(data, compresslevel=9, mtime=0)) + + +def linked(root: Path, target: str, sizes: dict[str, int]) -> list[Path]: + """Programs as webcpp.link's -program files on target, each of the bytes given: on WASI + its .wasm, on emscripten its .js and the .wasm beside it; natively a copy of the Python + interpreter, an executable strip can shorten, whatever the size given.""" + paths = [] + for name, size in sizes.items(): + if target == 'native': + path = root / f'{name}-program' + shutil.copyfile(sys.executable, path) + elif target == 'emscripten': + path = root / f'{name}-program.js' + path.write_bytes(b'// glue\n' * (size // 8)) + path.with_suffix('.wasm').write_bytes(bytes(range(256)) * (size // 256)) + else: + path = root / f'{name}-program.wasm' + path.write_bytes(bytes(range(256)) * (size // 256)) + paths.append(path) + return paths + + +def program_sizes(root: Path, target: str, *programs: Path, variant: str = 'release', + names: tuple[str, ...] = ('baseline', 'sealed'), + baseline: str = 'baseline') -> subprocess.CompletedProcess[str]: + """variants.py programs run as webcpp.program-sizes runs it.""" + return variants('programs', '--variant', variant, '--target', target, '--toolset', 'clang', + '--baseline', baseline, '--names', *names, '--out', root / 'p.sizes.json', + '--', *programs) + + +def test_programs_size_each_wasm_against_the_baseline(root: Path) -> None: + programs = linked(root, 'wasip2', {'baseline': 2560, 'sealed': 25600}) + # A library object a project's requirements append to the make is not a program. + stray = root / 'libsodium.a' + stray.write_bytes(b'x' * 100) + result = program_sizes(root, 'wasip2', *programs, stray) + assert result.returncode == 0, result.stderr + read = json.loads((root / 'p.sizes.json').read_text()) + base, sealed = (p.read_bytes() for p in programs) + # The JSON is dated by the build that wrote it, and names the host and the program's format. + assert read.pop('date') == datetime.date.today().isoformat(), read + assert read.pop('host') == f'{platform.system()} {platform.machine()}', read + assert read == { + 'variant': 'release', 'target': 'wasip2', 'toolset': 'clang', 'baseline': 'baseline', + 'format': 'WebAssembly', + 'programs': [ + {'program': 'baseline', 'file': 'wasm', 'bytes': 2560, 'gzip': gzipped(base), + 'over_baseline': 0, 'gzip_over_baseline': 0}, + {'program': 'sealed', 'file': 'wasm', 'bytes': 25600, 'gzip': gzipped(sealed), + 'over_baseline': 23040, 'gzip_over_baseline': gzipped(sealed) - gzipped(base)}]}, read + + +def test_programs_size_emscripten_s_wasm_and_its_glue(root: Path) -> None: + programs = linked(root, 'emscripten', {'baseline': 2560, 'sealed': 5120}) + result = program_sizes(root, 'emscripten', *programs) + assert result.returncode == 0, result.stderr + rows = json.loads((root / 'p.sizes.json').read_text())['programs'] + assert [(r['program'], r['file'], r['bytes'], r['over_baseline']) for r in rows] == [ + ('baseline', 'js', 2560, 0), ('baseline', 'wasm', 2560, 0), + ('sealed', 'js', 5120, 2560), ('sealed', 'wasm', 5120, 2560)], rows + + +def test_programs_strip_a_native_executable(root: Path) -> None: + if not shutil.which('strip'): + raise AssertionError('strip is not on PATH: a native size is that of a stripped program') + programs = linked(root, 'native', {'baseline': 0, 'sealed': 0}) + result = program_sizes(root, 'native', *programs) + assert result.returncode == 0, result.stderr + rows = json.loads((root / 'p.sizes.json').read_text())['programs'] + copy = root / 'stripped' + shutil.copyfile(programs[0], copy) + subprocess.run(['strip', str(copy)], check=True, capture_output=True) + stripped = copy.read_bytes() + native_format = {'Darwin': 'Mach-O', 'Linux': 'ELF'}.get(platform.system()) + assert json.loads((root / 'p.sizes.json').read_text())['format'] == native_format + assert [(r['file'], r['bytes'], r['gzip'], r['over_baseline']) for r in rows] == [ + ('executable', len(stripped), gzipped(stripped), 0), + ('executable', len(stripped), gzipped(stripped), 0)], rows + # The program itself is never changed. + assert programs[0].read_bytes() == Path(sys.executable).read_bytes() + + +def test_programs_refuse_a_program_not_given(root: Path) -> None: + programs = linked(root, 'wasip2', {'baseline': 256}) + result = program_sizes(root, 'wasip2', *programs) + assert result.returncode == 1, result.returncode + assert 'variants.py: sealed is not among the programs given' in result.stderr, result.stderr + assert not (root / 'p.sizes.json').exists() + result = program_sizes(root, 'wasip2', *programs, names=('sealed',)) + assert result.returncode == 1, result.returncode + assert 'the baseline baseline is not among the programs named' in result.stderr, result.stderr + + +def test_programs_are_sized_only_from_release_builds(root: Path) -> None: + programs = linked(root, 'wasip2', {'baseline': 256, 'sealed': 512}) + for variant in ('debug', 'profile'): + result = program_sizes(root, 'wasip2', *programs, variant=variant) + assert result.returncode == 1, (variant, result.returncode) + assert (f'variants.py: a size table is built only from release builds, not ' + f'variant={variant}') in result.stderr, result.stderr + assert not (root / 'p.sizes.json').exists(), variant + + +def test_programs_table_is_the_json_s(root: Path) -> None: + programs = linked(root, 'wasip2', {'baseline': 2560, 'sealed': 25600}) + program_sizes(root, 'wasip2', *programs) + out = root / 'p.sizes.md' + result = variants('programs-table', '--out', out, root / 'p.sizes.json') + assert result.returncode == 0, result.stderr + read = json.loads((root / 'p.sizes.json').read_text())['programs'] + table = (f'Linked programs on wasip2 (WebAssembly), built with clang at variant=release on ' + f'{datetime.date.today().isoformat()}, against the baseline baseline.\n\n' + '| program | file | bytes | gzip -9n | over baseline | gzip -9n over baseline |\n' + '| --- | --- | ---: | ---: | ---: | ---: |\n' + f'| baseline | wasm | 2,560 | {read[0]["gzip"]:,} | 0 | 0 |\n' + f'| sealed | wasm | 25,600 | {read[1]["gzip"]:,} | 23,040 | ' + f'{read[1]["gzip_over_baseline"]:,} |\n') + assert out.read_text() == table and result.stdout == table, (out.read_text(), result.stdout) + + +def test_programs_table_refuses_data_not_built_at_release(root: Path) -> None: + programs = linked(root, 'wasip2', {'baseline': 256, 'sealed': 512}) + program_sizes(root, 'wasip2', *programs) + data = json.loads((root / 'p.sizes.json').read_text()) + for variant in ('debug', None): + if variant is None: + del data['variant'] + else: + data['variant'] = variant + (root / 'p.sizes.json').write_text(json.dumps(data)) + result = variants('programs-table', '--out', root / 'p.sizes.md', root / 'p.sizes.json') + assert result.returncode == 1, (variant, result.returncode) + assert 'a size table is built only from release builds' in result.stderr, result.stderr + assert not (root / 'p.sizes.md').exists(), variant + + CASES: list[Callable[[Path], None]] = [ test_manifest_names_each_artifact_from_its_own_directory, test_manifest_refuses_an_artifact_without_its_wasm, @@ -117,6 +266,13 @@ def test_table_refuses_a_build_that_is_not_release(root: Path) -> None: test_table_lists_each_program_with_its_ratio, test_table_refuses_a_manifest_that_is_not_one, test_table_refuses_a_build_that_is_not_release, + test_programs_size_each_wasm_against_the_baseline, + test_programs_size_emscripten_s_wasm_and_its_glue, + test_programs_strip_a_native_executable, + test_programs_refuse_a_program_not_given, + test_programs_are_sized_only_from_release_builds, + test_programs_table_is_the_json_s, + test_programs_table_refuses_data_not_built_at_release, ] diff --git a/tools/webcpp-libdatachannel.jam b/tools/webcpp-libdatachannel.jam index 2ac541d9..8ce0de7d 100644 --- a/tools/webcpp-libdatachannel.jam +++ b/tools/webcpp-libdatachannel.jam @@ -13,11 +13,13 @@ import project ; import property-set ; import targets ; import toolset ; +import type ; import virtual-target ; import webcpp-lint-headers ; import webcpp-third-party ; feature.feature webcpp-libdatachannel-openssl : : free incidental ; +type.register WEBCPP_LIBDATACHANNEL_RECORD ; class libdatachannel-target : basic-target { @@ -150,6 +152,13 @@ class libdatachannel-target : basic-target $(archive).set-path $(directory) ; archives += [ virtual-target.register $(archive) ] ; } + # The build record, which build.py publishes last, is what makes the + # configuration complete: one whose archives an interrupted build + # published without it is built again. + local record = [ new file-target build.json exact + : WEBCPP_LIBDATACHANNEL_RECORD : $(self.project) : $(action) ] ; + $(record).set-path $(directory) ; + headers += [ virtual-target.register $(record) ] ; if $(os) = windows && [ $(properties).get ] = "on" && [ $(properties).get ] = database { diff --git a/tools/webcpp-openssl.jam b/tools/webcpp-openssl.jam index 15f93be8..6322a001 100644 --- a/tools/webcpp-openssl.jam +++ b/tools/webcpp-openssl.jam @@ -21,6 +21,7 @@ import webcpp-wasi ; feature.feature webcpp-openssl-tests : on : optional propagated ; type.register WEBCPP_OPENSSL_TESTS ; +type.register WEBCPP_OPENSSL_RECORD ; class openssl-target : basic-target { @@ -117,6 +118,13 @@ class openssl-target : basic-target local crypto = [ new file-target libcrypto.$(extension) exact : STATIC_LIB : $(self.project) : $(action) ] ; $(crypto).set-path $(directory) ; crypto = [ virtual-target.register $(crypto) ] ; + # The build record, which build.py publishes last, is what makes the + # configuration complete: one whose archives an interrupted build + # published without it is built again. + local record = [ new file-target build.json exact + : WEBCPP_OPENSSL_RECORD : $(self.project) : $(action) ] ; + $(record).set-path $(directory) ; + headers += [ virtual-target.register $(record) ] ; if [ $(properties).get ] = "on" { local proof = [ new file-target upstream-tests.json exact diff --git a/tools/webcpp-third-party.jam b/tools/webcpp-third-party.jam index 22b3ed31..ac0d1f14 100644 --- a/tools/webcpp-third-party.jam +++ b/tools/webcpp-third-party.jam @@ -14,8 +14,11 @@ # directory that exists holds the build of exactly those inputs and that # command: its outputs are NOUPDATE, built when missing and never again, b2 -a # included, which the CI's lanes run, and a directory the CI restores from its -# cache is used as it is. Consumers whose properties differ only in what the -# command leaves out, as exception-handling for OpenSSL's C, share one build. +# cache is used as it is. A build publishes its completion marker last +# (build.json, OpenSSL's and libdatachannel's), an output too, so that a +# directory an interrupted build left without it is built again. Consumers +# whose properties differ only in what the command leaves out, as +# exception-handling for OpenSSL's C, share one build. # # A consumer depends on -config-.selected in its own variant # directory, which tools/third_party_build.py select writes when the consumer's diff --git a/tools/webcpp.jam b/tools/webcpp.jam index 8f6c8f65..89e204e0 100644 --- a/tools/webcpp.jam +++ b/tools/webcpp.jam @@ -13,7 +13,8 @@ # webcpp.run-fail name : sources + : requirements * : targets * ; # webcpp.compile name : sources + : requirements * : targets * ; # webcpp.compile-fail name : sources + : requirements * : targets * ; -# webcpp.compile-diagnostic name : sources + : requirements * : targets * ; +# webcpp.compile-diagnostic name : sources + : requirements * : targets * +# : alone ? ; # webcpp.boost-test name : sources + : requirements * ; # webcpp.example source : requirements * : targets * ; # webcpp.headers-alone library : include-root : only * : requirements * @@ -29,6 +30,11 @@ # webcpp.variants name : sources + : requirements * ; # webcpp.size-table name : variants + ; # +# the rule of the sizes of programs webcpp.link declares, on any target, +# against a baseline among them, from release builds: +# +# webcpp.program-sizes name : baseline : programs + : targets * ; +# # the rule with which any test or example Jamfile of a library declares one # of its own lanes, which `b2 declared-lanes` lists, once per target it # runs on: @@ -118,6 +124,10 @@ feature.feature webcpp-lane : : free incidental ; # variants-request reads. feature.feature webcpp-variants : : free incidental ; +# The table of webcpp.program-sizes a make is of, /, which +# write-program-sizes reads. +feature.feature webcpp-program-sizes : : free incidental ; + # webcpp-require-external=on: a library webcpp does not build that is not # found stops the build (external-found), as the CI asks, rather than leave # the library that needs it out. Incidental, so that it plays no part in a @@ -365,6 +375,11 @@ local rule program ( kind : names + : targets * ) targets ?= $(.targets.$(jamfile)) ; targets ?= native ; .programs.$(jamfile) = true ; + for local name in $(names) + { + .kind-of.$(jamfile).$(name) = $(kind) ; + .built-on.$(jamfile).$(name) = $(targets) ; + } local library = [ library-of ] ; .declared += "$(library) $(targets)" ; .recorded.$(library) += "$(kind) $(names) $(targets:J= )" ; @@ -634,6 +649,100 @@ actions write-size-table bind MANIFESTS "$(PYTHON)" "$(SCRIPT)" table --variant "$(VARIANT)" --out "$(<)" "$(MANIFESTS)" } +# The sizes of the programs webcpp.link declares in this Jamfile under the +# names programs, against the program baseline, on targets, else on the +# Jamfile's: the explicit .sizes.json (tools/variants/variants.py's +# programs: per program and file, its raw and gzip -9n bytes and their excess +# over the baseline's; natively the executable stripped, on WebAssembly the +# .wasm, and on emscripten its .js too) and the explicit .sizes.md, its +# Markdown table, which the build prints and the CI keeps from an own lane's +# job (.github/workflows/library.yml, the artifact sizes-). Published +# sizes are those of release builds alone: both require release, +# which the programs inherit whatever variant the command asks for, and +# variants.py refuses a table of any other variant. b2 skips a make whole, +# and silently, when one of its sources is skipped on a target, so each +# program must be built on every target of the table, or the declaration +# stops, naming it. +rule program-sizes ( name : baseline : programs + : targets * ) +{ + local found = [ where ] ; + local jamfile = [ jamfile ] ; + local shown = "webcpp.program-sizes $(name) in $(found[4])" ; + check $(shown) : $(targets) ; + targets ?= $(.targets.$(jamfile)) ; + targets ?= native ; + local names = [ sequence.unique $(baseline) $(programs) ] ; + for local program in $(names) + { + if $(.kind-of.$(jamfile).$(program)) != link + { + errors.user-error "$(shown): $(program) is not a program webcpp.link declares" + "before it in its Jamfile" ; + } + local missing = [ set.difference $(targets) : $(.built-on.$(jamfile).$(program)) ] ; + if $(missing) + { + errors.user-error "$(shown): $(program) is not built for $(missing:J= ), which" + "would skip the table there without a word: give the table the targets" + "$(.built-on.$(jamfile).$(program):J= ) at most, or build $(program) for" + "$(missing:J= )" ; + } + } + local key = $(found[3])/$(name) ; + .program-sizes-baseline.$(key) = $(baseline) ; + .program-sizes-names.$(key) = $(names) ; + local only = release $(targets) @webcpp%filter ; + make $(name).sizes.json : $(names)-program : @webcpp%write-program-sizes + : $(only) $(key) ; + make $(name).sizes.md : $(name).sizes.json : @webcpp%write-program-table : $(only) ; + $(found[1]).mark-target-as-explicit $(name).sizes.json $(name).sizes.md ; +} + +rule write-program-sizes ( targets * : sources * : properties * ) +{ + PYTHON on $(targets) = $(.python) ; + SCRIPT on $(targets) = $(.variants-script) ; + local key = [ feature.get-values : $(properties) ] ; + BASELINE on $(targets) = $(.program-sizes-baseline.$(key)) ; + NAMES on $(targets) = $(.program-sizes-names.$(key)) ; + VARIANT on $(targets) = [ feature.get-values : $(properties) ] ; + TARGET on $(targets) = [ webcpp-target.target-of $(properties) ] ; + local toolset = [ feature.get-values : $(properties) ] ; + local version = [ feature.get-values : $(properties) ] ; + if $(version) + { + toolset = $(toolset)-$(version[1]) ; + } + TOOLSET on $(targets) = $(toolset) ; +} + +actions write-program-sizes +{ + "$(PYTHON)" "$(SCRIPT)" programs --variant "$(VARIANT)" --target "$(TARGET)" --toolset "$(TOOLSET)" --baseline "$(BASELINE)" --names $(NAMES) --out "$(<)" -- "$(>)" +} + +rule write-program-table ( targets * : sources * : properties * ) +{ + PYTHON on $(targets) = $(.python) ; + SCRIPT on $(targets) = $(.variants-script) ; + # A project's libraries can append source objects to this make target. + # Only the sizes are the table's input. + local sizes ; + for local source in $(sources) + { + if $(source:S) = .json + { + sizes += $(source) ; + } + } + SIZES on $(targets) = $(sizes) ; +} + +actions write-program-table bind SIZES +{ + "$(PYTHON)" "$(SCRIPT)" programs-table --out "$(<)" "$(SIZES)" +} + # A test that passes when sources compile, which builds no program. rule compile ( name : sources + : requirements * : targets * ) { @@ -669,11 +778,24 @@ rule compile-fail ( name : sources + : requirements * : targets * ) # b2's clang (native clang, clang-wasip2, clang-wasip3), the test is # skipped, as a program is for a target it does not declare, rather than # refused, which would turn red every lane of gcc or msvc for a declaration -# that holds; the report shows it there as not built. -rule compile-diagnostic ( name : sources + : requirements * : targets * ) -{ +# that holds; the report shows it there as not built. With `alone` last, the +# stated errors are the compile's only ones (-verify-ignore-unexpected=note): +# a refusal meant to be the first and only error fails its test when any +# other error follows it. +rule compile-diagnostic ( name : sources + : requirements * : targets * : alone ? ) +{ + local ignored = error,note ; + if $(alone) + { + if $(alone) != alone + { + errors.user-error "webcpp.compile-diagnostic $(name): $(alone) is not alone, the" + "only word its fifth argument takes" ; + } + ignored = note ; + } webcpp-compile-diagnostic.compile-diagnostic $(name) : $(sources) - : $(requirements) "-Xclang -verify -Xclang -verify-ignore-unexpected=error,note" + : $(requirements) "-Xclang -verify -Xclang -verify-ignore-unexpected=$(ignored)" @webcpp%clang-only [ program compile-diagnostic : $(name) : $(targets) ] $(.node-test) ; }