diff --git a/.github/workflows/library.yml b/.github/workflows/library.yml index b41a8b6f..72017b6b 100644 --- a/.github/workflows/library.yml +++ b/.github/workflows/library.yml @@ -24,9 +24,9 @@ # library's targets by hand, and a target without a lane fails the plan. It also # runs b2 declared-lanes and writes the matrix of own lanes, those a library # declares with webcpp.lane, such as its oracle's, and says whether a library -# needs libraries that webcpp does not build yet (external), trystero's -# libsecp256k1, installed by its action. B2 builds OpenSSL and -# libdatachannel from pinned sources with one provider per program. +# needs libraries that webcpp does not build yet (external), which none does +# today: B2 builds OpenSSL, libdatachannel and libsecp256k1 from pinned sources +# with one provider per program. # lanes one job per lane, which runs the lane command, b2 -a --dump-tests # --out-xml=.xml for one toolset, and uploads the XML. With --out-xml, b2 # exits 0 even when a test fails: the report gives the verdict. A wasip2 or @@ -247,15 +247,6 @@ jobs: if: matrix.node uses: ./tools/ci/actions/node - # libsecp256k1 remains external. OpenSSL and libdatachannel are source-built - # by B2 with the consuming target's toolchain and threading properties. - - &secp256k1 - if: matrix.external - uses: ./tools/ci/actions/secp256k1 - with: - cc: ${{ matrix.cc }} - emscripten: ${{ matrix.emsdk }} - # Only a container lane obtains the separately prepared immutable image. # No ordinary lane builds images or waits for an image-building job. - if: matrix.container @@ -314,7 +305,6 @@ jobs: - *wasi-wit - *emsdk - *node - - *secp256k1 # The pinned chrome-headless-shell, as CHROME, for a lane whose driver meets a browser # (its entry's chrome), as trystero's interop does. @@ -435,14 +425,6 @@ jobs: with: libraries: 'false' - # The libraries the library, or one it uses, needs and webcpp does not build yet (the - # plan's external), whose headers its reference parses with the native backend's: with Clang 18, - # the compiler that parses them. - - if: needs.plan.outputs.external == 'true' - uses: ./tools/ci/actions/secp256k1 - with: - cc: clang-18 - # clang++ reads the headers for tools/doc/doc_comments.py; the Boost check compiles with # the same Clang. The index links each library's page where the site serves it. # A page whose library needs external libraries requires them, as a lane does, and is @@ -459,11 +441,6 @@ jobs: fi if [ "$EXTERNAL" = true ]; then request=(webcpp-require-external=on "${request[@]}") - for variable in SECP256K1_ROOT SECP256K1_EMSCRIPTEN_ROOT; do - if [ -n "${!variable-}" ]; then - request=("-s$variable=${!variable}" "${request[@]}") - fi - done fi env -u CPATH -u CPLUS_INCLUDE_PATH -u C_INCLUDE_PATH \ b2 --user-config=.local/user-config.jam -a -sCLANG=/usr/bin/clang++-18 \ @@ -549,16 +526,6 @@ jobs: with: libraries: 'false' - # The libraries a library needs and webcpp does not build yet, when any does (the plan's - # lint-external), which the dry runs name and clang-tidy reads, built with Clang 18; and - # libsecp256k1's emscripten build too when a library declares emscripten, for the commands - # of that target. - - if: needs.plan.outputs.lint-external == 'true' - uses: ./tools/ci/actions/secp256k1 - with: - cc: clang-18 - emscripten: ${{ needs.plan.outputs.has-emscripten }} - # 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 3762d051..20c0dc58 100644 --- a/.gitmodules +++ b/.gitmodules @@ -49,3 +49,24 @@ [submodule "libs/cobalt"] path = libs/cobalt url = ../cobalt.git +[submodule "third_party/libs/wycheproof"] + path = third_party/libs/wycheproof + url = https://github.com/C2SP/wycheproof.git + shallow = true +[submodule "third_party/libs/bearssl"] + path = third_party/libs/bearssl + url = ../bearssl.git +[submodule "third_party/libs/bitcoin"] + path = third_party/libs/bitcoin + url = https://github.com/bitcoin/bitcoin.git + shallow = true +[submodule "third_party/libs/secp256k1"] + path = third_party/libs/secp256k1 + url = https://github.com/bitcoin-core/secp256k1.git +[submodule "third_party/libs/bips"] + path = third_party/libs/bips + url = https://github.com/bitcoin/bips.git + shallow = true +[submodule "libs/crypto"] + path = libs/crypto + url = ../crypto.git diff --git a/AGENTS.md b/AGENTS.md index 5906959e..2a14e444 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -77,6 +77,7 @@ for web developers and for AI developers (`CODING-GUIDELINES.md` chapter 16). | beast | HTTP and WebSocket applications using native/WASIp3 sockets, browser WebSocket/fetch, WASI host HTTP or supplied streams | native, emscripten, wasip2, wasip3, by backend | a submodule at `libs/beast`; all 53 upstream applications remain in its compatibility matrix | | cobalt | Boost.Cobalt coroutine applications with shipped Wasm adaptations and optional corrected SSL | native, emscripten, wasip2, wasip3, by capability | a submodule at `libs/cobalt`; see its feature and application matrices for variants | | config | webcpp's configuration, which every library includes first: the target, exceptions and webcpp's version, as Boost.Config is Boost's; webcpp's own | native, wasip2, wasip3, emscripten | a submodule at `libs/config` | +| crypto | AES-GCM, the AES block cipher, random_device, a constant-time equal and secp256k1 over C libraries built from source (BearSSL, OpenSSL, libsecp256k1, ctaes), webcpp's own | native, wasip2, wasip3, emscripten (OpenSSL not on emscripten); its own lane c-suites | a submodule at libs/crypto | | xactor | a deterministic actor system, webcpp's own | native, wasip2, wasip3 (`xactor_asio` native only) | a submodule at `libs/xactor`; the model for every port | | xstate | a port of XState 5.33.2's state machines and actors; depends on xactor and Boost.JSON | native, wasip2, wasip3; its oracle lane | a submodule at `libs/xstate`; the first user of the shared oracle (`CODING-GUIDELINES.md` chapter 12) | | pratt | a Pratt parser engine, generic through concepts, with a calculator built on it, webcpp's own | native, emscripten, wasip2, wasip3 | a submodule at `libs/pratt`; born with the allocation rule (`CODING-GUIDELINES.md` chapter 4) | @@ -102,12 +103,16 @@ webcpp/ extend (below) .clang-tidy clang-tidy's checks, every repository's pyrightconfig.json Pyright's settings for every Python file - libs// a library: a repository of its own, a submodule here (asio, config, xactor, - xstate, pratt, wasi, trystero, document, idna, lexical) + libs// a library: a repository of its own, a submodule here (asio, beast, cobalt, + config, crypto, xactor, xstate, pratt, wasi, trystero, document, idna, + lexical) third_party/ third-party code the libraries and their tests use, not webcpp's: each a submodule under third_party/libs/, pinned at a commit and keeping its - own licence, and the Jamfile that declares it as - /webcpp/third_party// (guidelines chapter 10) + own licence (openssl, libdatachannel, bearssl, secp256k1, bitcoin for + ctaes, and the test data wycheproof, bips, JSON-Schema-Test-Suite and + nativejson-benchmark), and the Jamfile that declares it as + /webcpp/third_party// and /third_party// (guidelines + chapter 10) doc/ the index page (index.adoc, Jamfile) releases/ each version's release notes, which the index page shows site/ the site, a repository of its own, webcpporg/webcpporg.github.io, a @@ -161,7 +166,7 @@ webcpp/ and emsdk.jam (the lines that register the WASI and emscripten toolsets), container/Dockerfile (the image of the container lanes), and actions/{boost,wasi-sdk,wasmtime,wit-bindgen,wasi-wit,emsdk, - secp256k1,chrome,container,mrdocs,node}/ + chrome,container,mrdocs,node}/ (chapter 4) site/ site.jam, the rules of b2 site and b2 site-serve, catalogue.py (the site's libraries.json), redirect.py (the old address's two pages) and @@ -197,6 +202,7 @@ libs// meta/include-boundaries.json the include boundaries the lint checks, when it has any (guidelines chapter 9) + meta/lint.json the lint's rules the library asks for, when it asks for any README.md AGENTS.md only what is specific to this library LICENSE_1_0.txt @@ -244,18 +250,22 @@ Jamroot is its build configuration, and `libs/` is its repository. toolsets compile; - for emscripten: Emscripten 6.0.11, from emsdk, and Node, which runs its programs; the tests of the build need it too; -- for trystero: libsecp256k1 0.8.0, static, with `schnorrsig` and - `extrakeys`, built natively and, for browser programs, with Emscripten. - Only this dependency remains externally provisioned. B2 reads - `-sSECP256K1_ROOT=` and `-sSECP256K1_EMSCRIPTEN_ROOT=` from its - command line, never the environment; otherwise it searches - `.local/secp256k1-native` and `.local/secp256k1-emscripten`, then the native - system include paths outside Windows. A missing dependency leaves trystero - out with a diagnostic, or fails when `webcpp-require-external=on`, as in CI; +- for trystero: nothing installed, with the pinned submodules initialised: + libsecp256k1 0.8.0 is `/third_party//secp256k1`, built by `b2` from the + pinned `third_party/libs/secp256k1` (small tables on + emscripten, large natively; `` asks otherwise). No + library of `libs/` needs an externally provisioned dependency today, though + `webcpp.external` and `webcpp-require-external=on` stay for a later one; +- 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; - for native Trystero: CMake and Make (nmake on Windows), and the pinned `third_party/libs/libdatachannel` checkout with its required nested sources. - Initialize it with `git submodule update --init --recursive - third_party/libs/libdatachannel`. B2 builds static libdatachannel and its + Initialize it, and the libsecp256k1 every room links, with `git submodule + update --init --recursive third_party/libs/libdatachannel + third_party/libs/secp256k1`. B2 builds static libdatachannel and its nested dependencies with the consumer's compiler and runtime settings. Every consumer of `/webcpp/third_party//libdatachannel` requires `threading=multi`: a single-thread request is refused, since libdatachannel @@ -400,12 +410,9 @@ verified, rather than assuming a newer Boost release fixes the issue. needs: `.local/user-config.jam`, `.local/wasi-sdk/`, `.local/mrdocs/`, `.local/wit-bindgen/` and `.local/wasi-wit/p2` and `p3`, `.local/emsdk` (an install of emsdk, or a link to one) with Emscripten's cache in -`.local/emscripten-cache`, and trystero's external libsecp256k1 installs in -`.local/secp256k1-native` and `.local/secp256k1-emscripten`. The CI action -uses those same paths. B2 finds them without `-s`; another prefix is named -with `-sSECP256K1_ROOT=` or `-sSECP256K1_EMSCRIPTEN_ROOT=` on its -command line. Source-built OpenSSL and libdatachannel instead live under the -B2 build directory, separated by the effective compiler configuration. +`.local/emscripten-cache`. Source-built libsecp256k1, OpenSSL and +libdatachannel live under the B2 build directory, separated by the effective +compiler configuration. A tool the build looks up itself is taken from the path its `-s` option gives, else from `.local/`, else from `PATH`: MrDocs (`-sMRDOCS`), wit-bindgen and the WIT (above); wasi-sdk is @@ -813,7 +820,7 @@ every build, so that no count drifts from the tree: - from the programs b2 records as it loads the library's test and example Jamfiles: `{n-examples}` and `{n-examples-}`, `{n-tests}` and `{n-tests-}` (each header compiled alone is one test, and so is - each served component, each linked program and each driven test), + each served component, each linked program, each driven test and each same-program pair), `{n-served}` and `{n-served-}`, the served components alone, `{n-linked}` and `{n-linked-}`, the programs `webcpp.link` links and never runs, `{n-driven}` and `{n-driven-}`, the tests @@ -1055,7 +1062,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; 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; 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`); 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) | @@ -1226,6 +1233,19 @@ webcpp.generated : diff --git a/tools/doc/extensions_test.py b/tools/doc/extensions_test.py index 5783c430..fb22b588 100755 --- a/tools/doc/extensions_test.py +++ b/tools/doc/extensions_test.py @@ -43,6 +43,8 @@ # breaks the line as would and is never copied (postprocess.mjs). SCOPE = '' PART = '' +# The break after a / of a path, a part too, which a table breaks at as it does after a ::. +PATH = '' def installed() -> None: @@ -52,16 +54,18 @@ def installed() -> None: check=True) -def convert(text: str) -> str: +def convert(text: str, *attributes: str) -> str: """The HTML Asciidoctor.js writes for the AsciiDoc text, with the extensions and the options - of webcpp.doc.""" + of webcpp.doc, and the attributes given, each name=value.""" with tempfile.TemporaryDirectory(prefix='doc extensions ') as scratch: source = Path(scratch) / 'page.adoc' source.write_text(HEADER + text) output = Path(scratch) / 'page.html' command = ['node', str(ASCIIDOCTOR), '-r', str(HERE / 'highlighter.mjs'), '-r', str(HERE / 'postprocess.mjs'), '-v', '--failure-level', 'INFO', '-S', 'unsafe', - '-a', 'source-highlighter=hljs-static', '-o', str(output), str(source)] + '-a', 'source-highlighter=hljs-static', + *[part for attribute in attributes for part in ('-a', attribute)], + '-o', str(output), str(source)] completed = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, check=False) assert completed.returncode == 0, completed.stdout @@ -161,28 +165,31 @@ def test_short_inline_code_stays_whole(_: None) -> None: html = body(convert(f'Read `#xactor-invariant-13`, `{long}`, `{angles}`,\n' f'`one {long}` and link:#x[`linked-name`].\n')) assert '#xactor-invariant-13' in html, html - assert f'{long}' in html, html + broken = parts('webcpp-|xactor-|invariant-|36') + assert f'{broken}' in html, html assert f'{angles}' in html, html - assert (f'one {long}' + assert (f'one {broken}' in html), html assert 'linked-name' in html, html def test_a_flag_keeps_its_leading_hyphen(_: None) -> None: - # A word too long for a phone's line may break at one of its hyphens, but never right after - # the hyphens that open a flag, which would end a line with them alone, read as a dash: they - # stay with the flag's first character, which the style keeps on one line. A hyphen inside a - # word, and a word short enough to stay whole, are left as they were. + # A word too long for a phone's line may break after one of its hyphens, a part of its name, + # but never right after the hyphens that open a flag, which would end a line with them alone, + # read as a dash: they stay with the flag's first character, which the style keeps on one + # line. A word short enough to stay whole is left as it was. html = body(convert('Link with `-mexec-model=reactor`, compile with ' '`-mllvm -wasm-use-legacy-eh=false`, give `--a-flag-wider-than-a-line`, ' 'but `-short` and `a-name-with-hyphens-past-24` stay as they are.\n')) - assert '<linkflags>-mexec-model=reactor' in html, ( - html) - assert ('-mllvm ' - '-wasm-use-legacy-eh=false' in html), html - assert '--a-flag-wider-than-a-line' in html, html + assert parts('<linkflags>-mexec-|model=reactor') \ + in html, html + assert parts('-mllvm ' + '-wasm-|use-|legacy-|eh=false') \ + in html, html + flag = parts('--a-|flag-|wider-|than-|a-|line') + assert flag in html, html assert '-short' in html, html - assert 'a-name-with-hyphens-past-24' in html, html + assert parts('a-|name-|with-|hyphens-|past-|24') in html, html lead = [(media, declarations) for media, selectors, declarations in page_style() for selector in selectors if selector.endswith('.lead')] assert lead == [(None, {'white-space': 'nowrap'})], lead @@ -205,6 +212,26 @@ def test_wide_table_labels_its_cells(_: None) -> None: assert 'data-label' not in tables[1], tables[1] +def test_a_header_column_scopes_its_header_cells(_: None) -> None: + # A table whose first column is a header column (cols="1h,...") has header cells in its body + # too, so each header cell says what it heads, as WCAG's technique H63 asks: the head's its + # column, the body's its row. A table without a header column is left as it was. + html = body(convert('[cols="1h,2,2",options="header"]\n|===\n| Name | `a` | `b`\n\n' + '| Header\n| ``\n| ``\n\n' + '| Errors\n| none\n| its values\n|===\n\n' + '[cols="1,1,2",options="header"]\n|===\n| Status | Value | What\n\n' + '| `active`\n| 1\n| Its mailbox.\n|===\n')) + tables = re.findall(r'', html, flags=re.S) + assert len(tables) == 2, html + head = ''.join(re.findall(r'.*?', tables[0], flags=re.S)) + rows = ''.join(re.findall(r'.*?', tables[0], flags=re.S)) + assert re.findall(r']*>', head) and all( + ' scope="col"' in cell for cell in re.findall(r']*>', head)), head + assert len(re.findall(r']*>', rows)) == 2 and all( + ' scope="row"' in cell for cell in re.findall(r']*>', rows)), rows + assert 'scope=' not in tables[1], tables[1] + + def test_dashes_stay_as_written_when_escaped(_: None) -> None: # Asciidoctor writes -- as an em dash, in inline code as in prose, which the check of the # rendered page refuses; \-- keeps the two hyphens, and so does a passthrough. @@ -266,8 +293,9 @@ def test_urls_in_code_stay_as_written_when_escaped(_: None) -> None: def parts(html: str) -> str: """The html with each | written as the break between two parts of a name that only a phone's - style keeps, and each as the break after a ::, which every style keeps.""" - return html.replace('', SCOPE).replace('|', PART) + style keeps, a path's after its /, and each as the break after a ::, which every style + keeps.""" + return html.replace('', SCOPE).replace('/|', '/' + PATH).replace('|', PART) def test_reference_headings_break_after_scopes(_: None) -> None: @@ -282,9 +310,9 @@ def test_reference_headings_break_after_scopes(_: None) -> None: def test_long_names_break_between_their_parts(_: None) -> None: # A name of code too long for a phone's line may break after a ::, a _, a / or a . between - # letters, before the ( or the < that ends a name, and between the words of a name in camel - # case, never between two letters of a word; prose, a listing, an attribute and a word short - # enough to stay whole are left as they are. + # letters, after a - inside a word, before the ( or the < that ends a name, and between the + # words of a name in camel case, never between two letters of a word; prose, a listing, an + # attribute and a word short enough to stay whole are left as they are. name = 'a_very_long_snake_case_name' broken = parts('a_|very_|long_|snake_|case_|name') header = 'webcpp/demo/long_header_name.hpp' @@ -308,7 +336,7 @@ def test_long_names_break_between_their_parts(_: None) -> None: for code in (f'{broken}{PART}(value)', parts(f'webcpp::demo::{broken}'), parts('std::optional|<boost::json::value>'), - parts('libs/|xstate/|test/|oracle//|update-expected'), + parts('libs/|xstate/|test/|oracle//|update-|expected'), parts('xstate.|done.|state.|coffee.|preparation'), 'short_name', parts('get_|initial_|microsteps|(machine, ' @@ -533,8 +561,8 @@ def test_admonitions_wrap_their_row_in_tbody(_: None) -> None: def css_rules(text: str) -> list[tuple[str | None, list[str], dict[str, str]]]: - """The rules of a stylesheet, each as its media query (None outside one), its selectors and - its declarations.""" + """The rules of a stylesheet, each as its media query (None outside one), or its container + query with its @container, its selectors and its declarations.""" text = re.sub(r'/\*.*?\*/', '', text, flags=re.S) rules: list[tuple[str | None, list[str], dict[str, str]]] = [] @@ -545,12 +573,14 @@ def read(block: str, media: str | None) -> None: if opening < 0: return prelude = block[position:opening].strip() - if prelude.startswith('@media'): + if prelude.startswith(('@media', '@container')): depth, end = 1, opening + 1 while depth: depth += {'{': 1, '}': -1}.get(block[end], 0) end += 1 - read(block[opening + 1:end - 1], prelude[len('@media'):].strip()) + # A media query as itself, a container query with its @container. + query = prelude.removeprefix('@media').strip() + read(block[opening + 1:end - 1], ' '.join(query.split())) position = end continue closing = block.index('}', opening) @@ -592,14 +622,16 @@ def test_style_breaks_a_word_only_when_it_must(_: None) -> None: def test_style_keeps_part_breaks_to_a_phone(_: None) -> None: # From 600px a break between two parts of a name is no box, in a heading, a URL and inline # code alike, and below it every break is live; a break after a :: of a heading is live at - # every width. + # every width. In a table, a break of code is live only where the table's box says so (the + # page's script), at every width. hidden = [(media, selector) for media, selectors, declarations in page_style() if declarations.get('display') == 'none' for selector in selectors if 'wbr' in selector] - assert sorted(hidden) == sorted([ + assert sorted(hidden, key=str) == sorted([ ('screen and (min-width: 37.5em)', 'span.wbr.part'), ('screen and (min-width: 37.5em)', '#content :not(pre):not([class^=L])>code span.wbr'), - ]), hidden + (None, '#content table.tableblock code span.wbr'), + ], key=str), hidden def test_breaks_are_never_wbr_and_never_copied(_: None) -> None: @@ -672,6 +704,214 @@ def test_style_gives_the_content_a_right_gutter_from_the_toc(_: None) -> None: assert ems(toc['width']) == ems(body['padding-left']), (media, toc, body) +def test_a_word_longer_than_any_line_breaks_at_every_width(_: None) -> None: + # A word of code longer than any line from 600px holds, 60 characters, such as a linker's + # symbol, is marked long, and the style keeps its breaks and lets it wrap at every width: + # kept whole, it would make the page wider than the screen at 900px. A word of 60 stays as a + # word a phone breaks. + symbol = 'webcpp_crypto_bearssl_7bea48e_getentropy__add_third_party_bearssl_to_your_link' + sixty = 'a' * 20 + '_' + 'b' * 19 + '_' + 'c' * 19 + html = body(convert(f'The link says `+{symbol}+`, `+undefined symbol: {symbol}+` and\n' + f'`{sixty}`.\n')) + broken = parts('webcpp_|crypto_|bearssl_|7bea48e_|getentropy__|add_|third_|party_|' + 'bearssl_|to_|your_|link') + assert f'{broken}' in html, html + assert (f'undefined ' + f'symbol: {broken}') in html, html + assert f'{parts("a" * 20 + "_|" + "b" * 19 + "_|" + "c" * 19)}' in html, html + rules = [(media or '', selector, declarations) + for media, selectors, declarations in page_style() + for selector in selectors if '.long' in selector] + assert sorted(rules, key=str) == sorted([ + ('', '#content code.long', {'white-space': 'normal'}), + ('', '#content code.words>span.long', {'white-space': 'normal'}), + ('screen and (min-width: 37.5em)', '#content code.long span.wbr', {'display': 'inline'}), + ('screen and (min-width: 37.5em)', '#content code.words>span.long span.wbr', + {'display': 'inline'}), + ], key=str), rules + + +def test_style_breaks_names_in_a_table_in_steps(_: None) -> None: + # In a table, inline code stays on one line between the breaks postprocess.mjs marks, at + # every width: never at a _ or a - by itself, as CSS would wrap it. A table that fits keeps + # its names whole. One too wide for its box with them whole, which the page's script marks + # names, breaks them only after a :: and a path's /, and between two names; one too wide even + # so, marked parts, between their other parts too: a column then as narrow as the longest + # part of its names. A table of the role wrap-names keeps its breaks after a :: and a / live + # at every width. A table laid out as stacked rows and still too wide, marked loose, lets its + # code wrap where it must. + rules = {(media, selector): declarations for media, selectors, declarations in page_style() + for selector in selectors} + table = '#content table.tableblock' + for selector in (f'{table} :not(pre):not([class^=L])>code', f'{table} code.words>span'): + assert rules.get((None, selector)) == {'white-space': 'nowrap'}, selector + assert rules.get((None, f'{table} :not(pre):not([class^=L])>code.words')) == \ + {'white-space': 'normal'}, rules + assert rules.get((None, f'{table} code span.wbr')) == \ + {'display': 'none', 'white-space': 'normal'}, rules + live = {selector for (media, selector), declarations in rules.items() + if declarations == {'display': 'inline'} and 'wbr' in selector and media is None} + assert live == { + '#content .table-scroll.names>table.tableblock code span.wbr:not(.part)', + '#content .table-scroll.names>table.tableblock code span.wbr.path', + '#content table.tableblock.wrap-names code span.wbr:not(.part)', + '#content table.tableblock.wrap-names code span.wbr.path', + '#content .table-scroll.parts>table.tableblock code span.wbr', + '#content .table-scroll.loose>table.tableblock code span.wbr', + }, live + loose = {'white-space': 'normal', 'overflow-wrap': 'break-word'} + for selector in ('#content .table-scroll.loose>table.tableblock ' + ':not(pre):not([class^=L])>code', + '#content .table-scroll.loose>table.tableblock code.words>span'): + assert rules.get((None, selector)) == loose, selector + # No rule of a width wraps a table's code as prose any more. + wrapping = [(media, selector) for (media, selector), declarations in rules.items() + if 'table' in selector and 'code' in selector and 'loose' not in selector + and declarations.get('white-space') == 'normal' and 'words' not in selector + and 'wbr' not in selector] + assert wrapping == [], wrapping + assert rules.get((None, '#content code.whole')) == {'white-space': 'nowrap'}, rules + html = body(convert('[.wrap-names,cols="1,1,1",options="header"]\n|===\n| A | B | C\n\n' + '| x | y | z\n|===\n')) + assert '' in html, html + + +def test_a_matrix_keeps_its_keys_whole(_: None) -> None: + # A table of eight columns or more is a matrix, read down its columns as much as along its + # rows: postprocess.mjs marks it, the page's script lets it scroll rather than stack, and + # each word of its first column with a hyphen inside, a profile such as + # native-single-on-native, is a key the style keeps on one line, so that a row is one line or + # two rather than one a part. Code, the header and the other columns are left as they are. + def source(columns: int) -> str: + header = ' '.join(f'| H{index}' for index in range(columns)) + row = '| native-single-on-native, 15-character keys | `a-code-name-longer-than-24` ' + \ + ' '.join(f'| x-{index}' for index in range(columns - 2)) + return (f'[cols="{",".join(["1"] * columns)}",options="header"]\n|===\n{header}\n\n' + f'{row}\n|===\n') + html = body(convert(source(8) + '\n' + source(7))) + matrix, plain = html.split('
')[:2] + assert '' in matrix, matrix + assert ('native-single-on-native, ' + '15-character keys

') in matrix, matrix + assert parts('a-|code-|name-|longer-|than-|24') in matrix, matrix + assert '>x-0

' in matrix and 'x-' not in matrix, matrix + assert 'matrix' not in plain and 'class="key"' not in plain, plain + rules = {selector: declarations for media, selectors, declarations in page_style() + if media is None for selector in selectors} + for selector in ('table.tableblock.matrix span.key', 'table.tableblock.key-column span.key'): + assert rules.get(selector) == {'white-space': 'nowrap'}, (selector, rules) + assert rules.get('table.tableblock.matrix>tbody>tr>td:first-child') == \ + {'min-width': '9em'}, rules + + +def test_style_lifts_a_link_s_underline_off_underscores(_: None) -> None: + # A link's underline at its default height covers the underscores of a name of code, which + # then reads as words: under a link that holds code, or in code that holds a link, it is + # drawn lower. + lifted = {selector for media, selectors, declarations in page_style() + if media is None and declarations.get('text-underline-offset') == '.3em' + for selector in selectors} + assert {'#content a:has(>code)', '#content code a'} <= lifted, lifted + + +def test_a_table_too_wide_stacks_as_on_a_phone(_: None) -> None: + # A table whose columns do not fit the page stacks its rows as a phone's style does, at any + # width: the page's script measures each table's box and marks it stacked, and the style + # lays out a stacked box's table as the phone's rules lay out every table. + docinfo = (HERE / 'docinfo.html').read_text() + script = re.search(r'', docinfo, flags=re.S) + assert script, docinfo + for part in ("querySelectorAll('div.table-scroll')", + 'box.scrollWidth > box.clientWidth', 'box.classList.add(step)', + "addEventListener('DOMContentLoaded', fit)", + "addEventListener('resize', fit)", + # The web fonts and images change the widths without a resize. + "addEventListener('load', fit)", 'document.fonts?.ready.then(fit)', + # A table breaks its names after their :: and then between their parts + # before it stacks, and only when it does not fit with them whole; stacked + # and still too wide, its code wraps where it must. + "const STEPS = ['names', 'parts', 'stacked', 'loose'];", + 'classList.remove(...STEPS)', "mark(boxes.filter(wide), 'names')", + "mark(named.filter((box) => !keyed(box)), 'parts')", + # A table of the role key-column stacks rather than break its names between + # their parts. + "classList.contains('key-column')", + # A matrix (postprocess.mjs) scrolls in its box rather than stack. + "classList.contains('matrix')", + "mark(parted.filter((box) => !matrix(box)), 'stacked')", + "'loose'"): + assert part in script.group(1), (part, script.group(1)) + phone = {} + for media, selectors, declarations in page_style(): + if media == 'screen and (max-width: 56.1875em)': + for selector in selectors: + if selector.startswith('table.') and 'admonition' not in selector: + phone[selector] = declarations + stacked = {selector[len('.table-scroll.stacked>'):]: declarations + for media, selectors, declarations in page_style() if media is None + for selector in selectors if selector.startswith('.table-scroll.stacked>')} + assert phone and stacked == phone, (stacked, phone) + + +def test_a_key_column_keeps_room_for_its_words(_: None) -> None: + # A table of the role key-column keeps room in its first column, at every width, for the + # words a reader starts from: crypto's decision table. Its other columns' names, short ones + # too, which stay whole elsewhere, break after their :: and their path's /, then between + # their other parts, where it does not fit otherwise (the page's script marks its box) to + # make that room. + rules = {selector: declarations for media, selectors, declarations in page_style() + if media is None for selector in selectors} + assert rules.get('table.tableblock.key-column>tbody>tr>td:first-child') == \ + {'min-width': '10em'}, rules + # Inline code of the role keep, a target or a file a reader copies, stays on one line at + # every width: postprocess.mjs marks no part in it. + assert rules.get('#content code.keep') == {'white-space': 'nowrap'}, rules + kept = body(convert('[.keep]`+/third_party//ctaes+` and <>\n\n' + '[#x]\n== X\n')) + assert '/third_party//ctaes' in kept, kept + assert 'a_b.cpp' in kept, kept + source = ('|===\n| A | B | C\n\n| a password-reset link | `+/third_party//ctaes+` ' + '| `+x+` and `+aes256+`\n|===\n') + html = body(convert('[.wrap-names.key-column,cols="1,1,1",options="header"]\n' + source + + '\n[cols="1,1,1",options="header"]\n' + source)) + keyed, plain = html.split('
')[:2] + assert 'class="tableblock frame-all grid-all stretch wrap-names key-column"' in keyed, keyed + # A hyphenated word of its first column stays whole, as a matrix's key does. + assert '

a password-reset link

' in keyed, \ + keyed + assert 'class="key"' not in plain, plain + assert parts('/third_|party//|ctaes') in keyed, keyed + assert parts('aes256|<backends::ctaes>') in keyed, keyed + assert 'x' in keyed, keyed + assert '/third_party//ctaes' in plain, plain + assert 'aes256<backends::ctaes>' in plain, plain + + +def test_the_table_of_contents_breaks_a_name_after_its_scopes(_: None) -> None: + # An entry of the table of contents at the side, about 14em wide, breaks a name of the + # reference after a ::, as the name's heading does, rather than between two of its letters, + # `webcpp::crypto::ciphers::ae` and `s256_gcm`. Its other parts and its code stay as written. + page = convert('== webcpp::crypto::ciphers::aes256_gcm\n\n' + '== Ciphers: `webcpp::crypto::ciphers`\n\n== Boost.Hash2 and a_b\n', 'toc=left') + toc = page[page.index('
')] + assert f'>webcpp::{SCOPE}crypto::{SCOPE}ciphers::{SCOPE}aes256_gcm' in toc, toc + assert '>Ciphers: webcpp::crypto::ciphers' in toc, toc + assert '>Boost.Hash2 and a_b' in toc, toc + + +def test_detail_macros_stay_out_of_the_reference(_: None) -> None: + # A detail macro, WEBCPP__DETAIL_*, is the library's own business, as a detail + # namespace is: the shared settings exclude it, and reference.py fails a reference that + # shows one. + shared = reference.settings('demo', {'LIBRARY': 'demo', 'MACROS': 'WEBCPP_DEMO_', + 'SOURCE_ROOT': '"r"', 'DATABASE': '"d"', 'INPUT': '"i"', + 'OUTPUT': '"o"'}, None) + excluded = shared[shared.index('exclude-macros:'):].split('\n')[1:3] + assert excluded == [" - 'WEBCPP_*_HPP'", " - 'WEBCPP_*_DETAIL_*'"], excluded + text = '[#WEBCPP_DEMO_DETAIL_SEAM]\n== x\n\n[#WEBCPP_DEMO_NO_EXCEPTIONS]\n== y\n' + assert reference.detail_macros(text) == ['WEBCPP_DEMO_DETAIL_SEAM'], text + + CASES: list[Callable[[None], None]] = [ test_prose_shows_what_mrdocs_read, test_synopsis_keeps_its_links, @@ -680,6 +920,7 @@ def test_style_gives_the_content_a_right_gutter_from_the_toc(_: None) -> None: test_short_inline_code_stays_whole, test_a_flag_keeps_its_leading_hyphen, test_wide_table_labels_its_cells, + test_a_header_column_scopes_its_header_cells, test_dashes_stay_as_written_when_escaped, test_code_keeps_its_characters_when_escaped, test_urls_in_code_stay_as_written_when_escaped, @@ -703,6 +944,14 @@ def test_style_gives_the_content_a_right_gutter_from_the_toc(_: None) -> None: test_breaks_are_never_wbr_and_never_copied, test_style_scrolls_a_wide_table_in_its_box, test_style_gives_the_content_a_right_gutter_from_the_toc, + test_a_word_longer_than_any_line_breaks_at_every_width, + test_style_breaks_names_in_a_table_in_steps, + test_a_matrix_keeps_its_keys_whole, + test_style_lifts_a_link_s_underline_off_underscores, + test_a_table_too_wide_stacks_as_on_a_phone, + test_a_key_column_keeps_room_for_its_words, + test_the_table_of_contents_breaks_a_name_after_its_scopes, + test_detail_macros_stay_out_of_the_reference, ] diff --git a/tools/doc/mrdocs.yml.in b/tools/doc/mrdocs.yml.in index 8ca15d72..cf7a2656 100644 --- a/tools/doc/mrdocs.yml.in +++ b/tools/doc/mrdocs.yml.in @@ -32,12 +32,15 @@ implementation-defined: # Every macro of the library, WEBCPP__*, or every WEBCPP_* for config, # which holds the collection's, is extracted, so that an undocumented one is # reported; the include guards, WEBCPP__
_HPP and config's -# WEBCPP_
_HPP, are not macros of its interface. +# WEBCPP_
_HPP, are not macros of its interface, and neither is a +# detail macro, WEBCPP__DETAIL_*, the library's own business as a detail +# namespace is: the reference shows none (reference.py checks it). extract-all-macros: true include-macros: - '@MACROS@*' exclude-macros: - 'WEBCPP_*_HPP' + - 'WEBCPP_*_DETAIL_*' # What MrDocs writes: one AsciiDoc file without a document title, which the # library's page includes with leveloffset=+1, and whose links to the source diff --git a/tools/doc/postprocess.mjs b/tools/doc/postprocess.mjs index c0642b9c..3a462b20 100644 --- a/tools/doc/postprocess.mjs +++ b/tools/doc/postprocess.mjs @@ -31,11 +31,27 @@ // stacks the table's rows; a table of two columns, a name and what it is, // reads stacked without them. // +// A table with a header column gives its header cells their scope: the head's +// `col`, the body's `row`. +// +// A word of inline code too long for any line from 600px, more than 60 +// characters, is marked `long`, and the style keeps its breaks at every width. +// +// In a table of the role key-column, a word marked `whole` has its parts +// marked too, which the style breaks between only where the table does not fit +// with its names whole, so that the table's first column keeps room for its +// words. +// +// A table of eight columns or more, a matrix, is marked `matrix`, and each +// hyphenated word of its first column, and of a key-column table's, `key`, +// which the style keeps whole. +// // A name too long for a phone's line, in inline code, in a heading of the -// reference, `webcpp::xactor::scheduler::run_one`, or in a bare URL, may break +// reference (and its entry in the table of contents, after a `::` only), `webcpp::xactor::scheduler::run_one`, or in a bare URL, may break // between its parts, which an empty `` marks: after a `::`, // a `_`, a `/`, or a `.` between letters, before the `(` or the `<` that ends -// a name, and in code between the words of a name in camel case. So a phone +// a name, and in code after a `-` inside a word and between the words of a +// name in camel case. So a phone // breaks it there and never between two letters of a word, which the style // allows only to a part still wider than the line. From 600px, where such a // name has room, only the break after a `::` of a heading stays, as the @@ -105,11 +121,21 @@ const INLINE_CODE = /((?:[^<]|]*>|<\/a>)*)<\/code>/g; // a list item or a stacked table cell narrows to about 260px. const WHOLE = 24; +// The longest word of inline code that every line from 600px holds whole: at +// 600px the content is about 565px wide, about 65 characters of the code font. +// A longer word, a linker's symbol of 80 characters, keeps its breaks between +// its parts at every width, marked `long`: kept whole, it would make the page +// wider than the screen. +const LONG = 60; + // A break after a `::`, which a heading of the reference keeps at every width; // and one between the other parts of a name, which the style keeps only on a -// phone: from 600px every such name has room on a line. +// phone: from 600px every such name has room on a line. The break after a `/` +// of a path is such a part, which a table too wide for its box breaks at as it +// does after a `::` (docinfo.html). const SCOPE = ''; const PART = ''; +const PATH = ''; // The points a name breaks at, in text that holds no markup and its // references, each with what it becomes: after each `::`; after a run of `_` @@ -119,20 +145,22 @@ const PART = ''; const BREAKS = [ [/::/g, (scope) => scope + SCOPE], [/(?<=[A-Za-z0-9])_+(?=[A-Za-z0-9])/g, (run) => run + PART], - [/(?<=[^\s/])\/+(?=[^\s/])/g, (run) => run + PART], + [/(?<=[^\s/])\/+(?=[^\s/])/g, (run) => run + PATH], [/(?<=[A-Za-z])\.(?=[A-Za-z])/g, (dot) => dot + PART], [/(?<=\w)(?=\(|<)/g, () => PART] ]; -// Code breaks at these too, and between the words of a name written in camel -// case, `resolveHistory` and `DefaultTransition`: never prose, whose JavaScript -// is one word. And the hyphens that open a flag, `-mexec-model=reactor` or +// Code breaks at these too, after a `-` inside a word, `websocket-client-async`, +// and between the words of a name written in camel case, `resolveHistory` and +// `DefaultTransition`: never prose, whose JavaScript is one word and whose +// hyphens a line breaks after anyway. And the hyphens that open a flag, `-mexec-model=reactor` or // `--target`, at the start of a word or after a space, a `=`, a `(`, a `,` or // the `;` of a reference such as `>`, stay with the flag's first character // in a span the style keeps on one line: a break right after them would end a // line with a hyphen alone, which reads as a dash. const CODE_BREAKS = [ ...BREAKS, + [/(?<=[A-Za-z0-9])-(?=[A-Za-z0-9])/g, (hyphen) => hyphen + PART], [/(?<=[a-z])(?=[A-Z])/g, () => PART], [/(?<=^|[\s=(,;])-+[A-Za-z0-9]/g, (flag) => `${flag}`] ]; @@ -173,12 +201,19 @@ function isWhole(word) { return decodeEntities(textOf(word), { markup: true }).length <= WHOLE; } -// A word of inline code, as an element: `whole`, or breakable between its -// parts. +// Whether a word of inline code is longer than a line from 600px holds. +function isLong(word) { + return decodeEntities(textOf(word), { markup: true }).length > LONG; +} + +// A word of inline code, as an element: `whole`, breakable between its parts +// on a phone, or `long`, breakable between its parts at every width. function wordOf(element, word) { - return isWhole(word) - ? `<${element} class="whole">${word}` - : `<${element}>${breakableCode(word)}`; + if (isWhole(word)) { + return `<${element} class="whole">${word}`; + } + const kind = isLong(word) ? ' class="long"' : ''; + return `<${element}${kind}>${breakableCode(word)}`; } function wordsOfCode(html) { @@ -196,6 +231,60 @@ function wordsOfCode(html) { }); } +// A word of inline code a phone keeps whole, as code or as a word of code. +const WHOLE_WORD = /<(code|span) class="whole">((?:(?!<\/\1>)[\s\S])*?)<\/\1>/g; + +// Each table of the role key-column, its words of code marked whole made +// breakable between their parts: the style keeps them whole but where the +// table does not fit with them whole (docinfo.html). +function partsOfKeyColumnTables(html) { + return html.replace(TABLE, (table) => + /^]*\sclass="[^"]*\bkey-column\b/.test(table) + ? table.replace(WHOLE_WORD, (_word, element, text) => + `<${element} class="whole">${breakableCode(text)}`) + : table + ); +} + +// A table of MATRIX columns or more, a matrix, such as a benchmark's or a +// profile's, read down its columns as much as along its rows: its table is +// marked `matrix`, which the page's script lets scroll in its box rather than +// stack (docinfo.html), and each word of its first column's text with a hyphen +// inside, a key such as `native-single-on-native`, is marked `key`, which the +// style keeps on one line; and so is each of the first column of a table of the +// role key-column, `password-reset`. +const MATRIX = 8; +const FIRST_CELL = /(\s*]*>)([\s\S]*?)(<\/td>)/g; +const HYPHENATED = /[^\s<>]*[A-Za-z0-9]-[A-Za-z0-9][^\s<>]*/g; + +// The html of a cell with each hyphenated word of its text, outside its code, +// marked a key. +function keysOf(html) { + let code = false; + return html + .split(/(<[^>]+>)/) + .map((part, index) => { + if (index % 2 === 1) { + code = /^/.test(part)); + return part; + } + return code ? part : part.replace(HYPHENATED, (word) => `${word}`); + }) + .join(''); +} + +function matrices(html) { + return html.replace(TABLE, (table) => { + const matrix = (table.match(/= MATRIX; + if (!matrix && !/^]*\sclass="[^"]*\bkey-column\b/.test(table)) { + return table; + } + const marked = matrix ? table.replace(/^(]*\sclass="[^"]*)"/, '$1 matrix"') : table; + return marked.replace(BODY, (body) => + body.replace(FIRST_CELL, (_cell, open, text, close) => open + keysOf(text) + close)); + }); +} + // A bare URL, which Asciidoctor writes as the text of its link, and which holds // no break yet: one in a heading has its breaks already. const BARE_URL = /()([^<]*)(<\/a>)/g; @@ -273,6 +362,24 @@ function labelledTables(html) { }); } +// A table with a header column (cols="1h,...") has header cells in its body as in its head; each +// says what it heads, as WCAG's technique H63 asks and html-validate's wcag/h63 checks: the head's +// its column, the body's its row. A table without one keeps its cells as they are. +const HEAD = /[\s\S]*?<\/thead>/; +const TH = / { + const body = table.match(BODY); + if (body === null || !/ head.replace(TH, ' rows.replace(TH, ']*>|<\/table>/g; @@ -290,6 +397,35 @@ function boxedTables(html) { }); } +// The table of contents at the side of the page, up to the content, and the +// text of a link of it. +const TOC = /
)/; +const TOC_LINK = /()([\s\S]*?)(<\/a>)/g; + +// An entry of the table of contents, about 14em wide at the side of the page, +// breaks a name of the reference after each `::`, as the name's heading does, +// rather than between two of its letters where it must: its text outside its +// inline code, whose breaks wordsOfCode marked, and only after a `::`, which +// the style keeps at every width. +function scopesOfContents(html) { + return html.replace(TOC, (toc) => + toc.replace(TOC_LINK, (_link, open, inner, close) => { + let code = false; + const broken = inner + .split(TAG) + .map((part, index) => { + if (index % 2 === 1) { + code = /^/.test(part)); + return part; + } + return code ? part : breakable(part, [BREAKS[0]]); + }) + .join(''); + return open + broken + close; + }) + ); +} + // A heading, with what it holds. const HEADING = /(]*>)([\s\S]*?)(<\/h\2>)/g; @@ -384,8 +520,12 @@ function curledApostrophes(html) { class Page extends Postprocessor { process(_document, output) { - const page = labelledTables(wordsOfCode(decodeEntities(output))); - const built = curledApostrophes(boxedTables(partsOfURLs(partsOfHeadings(page)))); + const page = scopedHeaders( + labelledTables(matrices(partsOfKeyColumnTables(wordsOfCode(decodeEntities(output))))) + ); + const built = curledApostrophes( + boxedTables(partsOfURLs(scopesOfContents(partsOfHeadings(page)))) + ); return tbodied(styledColumns(silentAnchors(built))); } } diff --git a/tools/doc/reference.py b/tools/doc/reference.py index 9a3e8d80..72cd03df 100755 --- a/tools/doc/reference.py +++ b/tools/doc/reference.py @@ -119,6 +119,12 @@ def stray_macros(text: str) -> list[str]: if not any(name == family or name.startswith(f'{family}_') for family in families)] +def detail_macros(text: str) -> list[str]: + """The detail macros, WEBCPP__DETAIL_*, of a reference, MrDocs's text: none is of the + library's interface, and mrdocs.yml.in excludes them, as a detail namespace is.""" + return [name for name in MACRO_SECTION.findall(text) if '_DETAIL_' in name] + + def macro_prefix(library: str) -> str: """The prefix of the macros the library's reference lists: WEBCPP__, or WEBCPP_ for config.""" @@ -518,6 +524,10 @@ def reference(options: argparse.Namespace) -> int: f'({", ".join(libraries.CONFIG_FAMILIES)}); a new family goes into ' 'CONFIG_FAMILIES, in tools/doc/libraries.py' for name in stray_macros(written.read_text())] + if written.is_file(): + faults += [f'reference.py: {name}: a detail macro is in the reference, which ' + 'tools/doc/mrdocs.yml.in excludes' + for name in detail_macros(written.read_text())] try: found = doc_comments.check(clang, library, include, [*flags, f'-I{include}', *systems, str(aggregate)], diff --git a/tools/lint/lint.sh b/tools/lint/lint.sh index b4614a96..d9d8a741 100755 --- a/tools/lint/lint.sh +++ b/tools/lint/lint.sh @@ -28,7 +28,8 @@ # or class, that a comment of a Jam file keeps to 80 columns, that a library header raises # through boost::throw_exception, never with a bare throw, that no code span of a Doc Comment # holds __X__ unescaped, which MrDocs shows as a bold X, and that a library's changelog and a -# version's release notes keep their form. +# version's release notes keep their form, and that each canary of webcpp::crypto is pinned at +# its submodule's commit. # # clang-tidy reads the compilation database of tools/lint/compile_commands.py: what b2 compiles # for the libraries' tests and examples and for their own lanes, a served component among them, @@ -613,6 +614,41 @@ else printf ' the entropy\n' fi +# 8a. A header that reads entropy names no weaker source: no rand, random, the *rand48 family, +# the standard engines (mt19937, minstd_rand, ranlux, knuth_b, default_random_engine), time, +# clock or RDRAND (the _rdrandNN_step intrinsics, the compiler builtins, or +# the instruction in inline asm), even with lint-world:, in any header whose path ends +# entropy.hpp or random_device.hpp (DESIGN, 2026-10-11 "entropy, safest and readable"). +rule 'entropy sources' +files_matching '^(libs|tools/test/fixtures)/[^/]+/include/.*(entropy|random_device)\.hpp$' \ + > "${work_directory}/entropy_headers" +# The calls, with no space before the parenthesis so that prose such as "constant time (see x)" +# is spared; the engines and RDRAND by name wherever they appear. +weak_calls='s?rand|random|rand_r|[edjlmns]rand48|seed48|lcong48|time|clock' +weak_rdrand='_*rdrand(16|32|64)?_step|__builtin_ia32_rdrand(16|32|64)_step' +weak_engines='mt19937|minstd_rand|default_random_engine|ranlux|knuth_b' +weak='(^|[^_[:alnum:]])(((('"${weak_calls}|${weak_rdrand}"')\()|'"${weak_engines}"'|(rdrand([^_[:alnum:]]|$))))' +weak_found='' +entropy_failed=0 +while IFS= read -r -d '' entropy_header; do + entropy_status=0 + entropy_hits="$(grep -nHE -e "${weak}" "${entropy_header}")" || entropy_status=$? + if [ "${entropy_status}" -gt 1 ]; then + entropy_failed=1 # grep's own error (2) is a failure of the rule, never "no match" + elif [ "${entropy_status}" -eq 0 ]; then + weak_found+="${entropy_hits}"$'\n' + fi +done < "${work_directory}/entropy_headers" +if [ "${entropy_failed}" -ne 0 ]; then + fail "grep failed to read a header that reads entropy" +elif [ -n "${weak_found}" ]; then + printf '%s' "${weak_found}" \ + | sed 's/$/: a header that reads entropy names a weaker source/' + fail "a header that reads entropy names a weaker source" +else + printf 'no header that reads entropy names a weaker source\n' +fi + # 9. A library's test and example Jamfiles declare their programs with tools/webcpp.jam's rules, # which build each only for the targets it declares and add what every program needs; b2's # own run, run-fail, compile, compile-fail, exe and unit-test do neither (tools/lint/rules.py). @@ -768,6 +804,62 @@ else fail 'a changelog breaks its form (AGENTS.md chapter 5)' fi +# 19. Each canary's commit is its submodule's (CODING-GUIDELINES.md chapter 5, rule 11): +# every `#define WEBCPP_CRYPTO__COMMIT ` of crypto's detail/canary.h names +# the first seven digits of the commit the superproject records for +# third_party/libs/, read from git, so that no checkout is needed. The +# submodule is the canary's name, except ctaes, which Bitcoin Core's submodule holds. +rule 'canary pins' +canary_header='libs/crypto/include/webcpp/crypto/detail/canary.h' +pins="$(grep -hoE '^#define WEBCPP_CRYPTO_[A-Z0-9]+_COMMIT [0-9a-f]{7}$' \ + "${canary_header}" 2>/dev/null || true)" +pin_faults='' +# A line that starts like a pin and is not of the exact form is a fault too, never skipped; a +# test's override (the macro defined as another WEBCPP_CRYPTO_ macro) is no pin. +pin_form='#define WEBCPP_CRYPTO__COMMIT <7 hex>' +while IFS= read -r line; do + if ! printf '%s\n' "${pins}" | grep -qxF -- "${line}"; then + pin_faults="${pin_faults}${canary_header}: a pin is not of the form ${pin_form}: " + pin_faults="${pin_faults}${line} +" + fi +done < <(grep -E '^#define WEBCPP_CRYPTO_[A-Z0-9]+_COMMIT ' "${canary_header}" 2>/dev/null \ + | grep -vE ' WEBCPP_CRYPTO_[A-Z0-9_]+$' || true) +while read -r _ macro hex; do + [ -n "${macro}" ] || continue + name="$(printf '%s' "${macro}" | sed -E 's/^WEBCPP_CRYPTO_(.*)_COMMIT$/\1/' | tr 'A-Z' 'a-z')" + case "${name}" in + ctaes) submodule='bitcoin' ;; + *) submodule="${name}" ;; + esac + head="$(git rev-parse --short=7 "HEAD:third_party/libs/${submodule}" 2>/dev/null \ + || printf 'missing')" + if [ "${head}" != "${hex}" ]; then + pin_faults="${pin_faults}${canary_header}: ${name} is pinned at ${hex} and " + pin_faults="${pin_faults}third_party/libs/${submodule} is at ${head} +" + fi +done < str: + return ('// 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' + f'#ifndef WEBCPP_DEMO_{guard}_HPP\n' + f'#define WEBCPP_DEMO_{guard}_HPP\n' + '\n' + f'{body}' + '\n' + f'#endif // WEBCPP_DEMO_{guard}_HPP\n') + + source = ('// Calls getentropy(p, 16). lint-world: a test\n' + '// Names random_device. lint-world: a test\n' + '// The constant time (see the guide) of a comparison.\n') + write(root, header, licensed('ENTROPY', lines + source)) + # Outside the rule's scope, the same names are left alone. + write(root, other, licensed('OTHER', '// Calls rand(). lint-world: a test\n')) + expect_alone(lint(root), 'entropy sources', + [at(root, header, name) for name in weaker] + + [': a header that reads entropy names a weaker source'], + spared=(at(root, header, 'getentropy'), at(root, header, 'Names random_device'), + at(root, header, 'constant time'), other)) + + +def test_entropy_sources_unreadable_header(root): + prepare(root) + header = 'libs/demo/include/webcpp/demo/entropy.hpp' + write(root, header, '// Copyright (c) 2026 WebCpp.org\n') + (root / header).chmod(0) + try: + try: + (root / header).read_bytes() + except PermissionError: + pass + else: + # root reads whatever its mode: the case cannot make grep fail there. + print('test_entropy_sources_unreadable_header: skipped, the header is readable ' + '(running as root)') + return + result = lint(root) + finally: + (root / header).chmod(0o644) + # grep's own error (exit 2) fails the rule loudly; it is never read as "no match". + assert 'grep failed to read a header that reads entropy' in result.stdout, result.stdout[-3000:] + assert 'entropy sources' in FAILED.findall(result.stdout), result.stdout[-3000:] + + def test_bare_throw(root): prepare(root) # A library header raises through boost::throw_exception alone. A throw in a template that @@ -2050,6 +2114,86 @@ def test_include_boundaries_missing_key(root): expect_alone(lint(root), 'include boundaries', [f"{config}:1: a boundary is missing 'why'"]) +NODISCARD_HEADER = 'libs/demo/include/webcpp/demo/results.hpp' + + +def plant_results(root) -> None: + """Writes NODISCARD_HEADER: functions returning boost::system::result with and without + [[nodiscard]], and results that are no function's.""" + write(root, NODISCARD_HEADER, CPP + '\n' + '#ifndef WEBCPP_DEMO_RESULTS_HPP\n' + '#define WEBCPP_DEMO_RESULTS_HPP\n' + '\n' + '#include \n' + '\n' + '#include \n' + '\n' + 'namespace webcpp::demo {\n' + '\n' + '[[nodiscard]] inline boost::system::result kept_free() noexcept {\n' + ' return 1;\n' + '}\n' + '\n' + 'inline boost::system::result dropped_free() noexcept {\n' + ' return 1;\n' + '}\n' + '\n' + 'template \n' + 'boost::system::result> dropped_template() {\n' + ' return std::pair{};\n' + '}\n' + '\n' + 'template \n' + '[[nodiscard]] boost::system::result kept_template() {\n' + ' return T{};\n' + '}\n' + '\n' + 'class holder {\n' + 'public:\n' + ' [[nodiscard]] static boost::system::result kept_member() { return {}; }\n' + '\n' + 'protected:\n' + ' static boost::system::result dropped_member() { return {}; }\n' + '};\n' + '\n' + '// boost::system::result commented_out();\n' + 'inline boost::system::result const constant_value{1};\n' + '\n' + '} // namespace webcpp::demo\n' + '\n' + '#endif\n') + + +def test_nodiscard_results(root): + prepare(root) + # A library that asks for it in meta/lint.json declares each function returning a result + # [[nodiscard]]: a free function, a template's and a member after an access specifier fail + # at their lines, with the library's reason; what is kept, commented out or a variable's type + # does not. + write(root, 'libs/demo/meta/lint.json', '{"nodiscard-results": "a dropped result is lost"}\n') + plant_results(root) + message = 'a function returning boost::system::result without [[nodiscard]]: ' + expect_alone(lint(root), 'nodiscard results', [ + at(root, NODISCARD_HEADER, 'dropped_free') + ' ' + message + 'a dropped result is lost', + at(root, NODISCARD_HEADER, 'dropped_template') + ' ' + message, + at(root, NODISCARD_HEADER, 'dropped_member') + ' ' + message, + ], spared=(at(root, NODISCARD_HEADER, 'kept_free'), + at(root, NODISCARD_HEADER, 'kept_template'), + at(root, NODISCARD_HEADER, 'kept_member'), + at(root, NODISCARD_HEADER, 'commented_out'), + at(root, NODISCARD_HEADER, 'constant_value'))) + + +def test_nodiscard_results_is_asked_for(root): + prepare(root) + # Without meta/lint.json the same header passes; a file with another key fails, naming it. + plant_results(root) + expect_clean(lint(root)) + write(root, 'libs/demo/meta/lint.json', '{"nodiscard": "misspelled"}\n') + expect_alone(lint(root), 'nodiscard results', [ + "libs/demo/meta/lint.json:1: the file holds only the keys ['nodiscard-results']"]) + + def test_include_boundaries_glob_matches_nothing(root): prepare(root) config = boundaries_config(root, [{ @@ -2209,6 +2353,69 @@ def test_changelog(root): [f'libs/demo/doc/changelog.adoc:{number}: a line starts with']) +CANARY = (CPP + '\n#ifndef WEBCPP_CRYPTO_DETAIL_CANARY_H\n#define WEBCPP_CRYPTO_DETAIL_CANARY_H\n' + '#ifdef WEBCPP_CRYPTO_BEARSSL_CANARY_COMMIT\n' + '#define WEBCPP_CRYPTO_BEARSSL_COMMIT WEBCPP_CRYPTO_BEARSSL_CANARY_COMMIT\n#else\n' + '#define WEBCPP_CRYPTO_BEARSSL_COMMIT {bearssl}\n#endif\n' + '#define WEBCPP_CRYPTO_CTAES_COMMIT {ctaes}\n#endif\n') +CANARY_HEADER = 'libs/crypto/include/webcpp/crypto/detail/canary.h' + + +def record_submodule(root: Path, name: str, commit_id: str) -> None: + """Records the gitlink third_party/libs/name at commit_id in the scratch superproject's index, + as a submodule's is, without a checkout; the link the scratch copy has for third_party/libs + gives way to a directory first.""" + libs = root / 'third_party/libs' + if libs.is_symlink(): + git(root, 'rm', '-q', '--cached', 'third_party/libs') + libs.unlink() + libs.mkdir() + git(root, 'update-index', '--add', '--cacheinfo', + f'160000,{commit_id},third_party/libs/{name}') + + +def commit_recorded(root: Path, message: str) -> None: + """Commits the header and the gitlinks recorded, without commit's git add -A, which would + drop a gitlink whose directory is not there.""" + git(root, 'add', CANARY_HEADER) + git(root, 'commit', '-q', '-m', message) + + +def test_canary_pins(root): + prepare(root) + # Each pin of detail/canary.h is the first seven digits of the commit the superproject + # records for its submodule, ctaes' for bitcoin's; the macro of a test's override is no pin. + # A pin that differs, or whose submodule is not recorded, fails at the header, naming both; a + # pin that is not of the exact form (not seven hex digits) fails at its line. + bearssl = '7bea48e5e850ab4cafbe68d3765cdaba13a86d6f' + bitcoin = '1234567890abcdef1234567890abcdef12345678' + record_submodule(root, 'bearssl', bearssl) + record_submodule(root, 'bitcoin', bitcoin) + write(root, CANARY_HEADER, CANARY.format(bearssl='7bea48e', ctaes='1234567')) + commit_recorded(root, 'A canary') + expect_clean(lint(root)) + write(root, CANARY_HEADER, CANARY.format(bearssl='1234567', ctaes='1234568')) + commit_recorded(root, 'Canaries at other commits') + expect_alone(lint(root), 'canary pins', [ + f'{CANARY_HEADER}: bearssl is pinned at 1234567 and third_party/libs/bearssl is at 7bea48e', + f'{CANARY_HEADER}: ctaes is pinned at 1234568 and third_party/libs/bitcoin is at 1234567', + ]) + record_submodule(root, 'bearssl', '1234567' + bearssl[7:]) + write(root, CANARY_HEADER, CANARY.format(bearssl='1234567', ctaes='1234567')) + commit_recorded(root, 'Canaries at the recorded commits') + expect_clean(lint(root)) + git(root, 'rm', '-q', '--cached', 'third_party/libs/bearssl') + commit_recorded(root, 'No bearssl') + expect_alone(lint(root), 'canary pins', [ + 'bearssl is pinned at 1234567 and third_party/libs/bearssl is at missing']) + record_submodule(root, 'bearssl', '1234567' + bearssl[7:]) + write(root, CANARY_HEADER, CANARY.format(bearssl='1234567', ctaes='123456')) + commit_recorded(root, 'A malformed pin') + expect_alone(lint(root), 'canary pins', [ + f'{CANARY_HEADER}: a pin is not of the form #define WEBCPP_CRYPTO__COMMIT <7 hex>: ' + '#define WEBCPP_CRYPTO_CTAES_COMMIT 123456']) + + def test_pyright(root): prepare(root) # A warning fails as an error does. lint_test.py itself proves the import paths: it imports @@ -2503,6 +2710,8 @@ def test_wasip3_abi_snapshot_requires_integrity_before_style_exemption(root): test_banned_word, test_third_party_code_is_never_read, test_world_rule, + test_entropy_sources, + test_entropy_sources_unreadable_header, test_bare_throw, test_raw_rules, test_include_boundaries_angle_brackets, @@ -2512,6 +2721,8 @@ def test_wasip3_abi_snapshot_requires_integrity_before_style_exemption(root): test_include_boundaries_headers_glob_does_not_reach_a_deeper_path, test_include_boundaries_prefix_catches_bare_header, test_include_boundaries_glob_matches_nothing, + test_nodiscard_results, + test_nodiscard_results_is_asked_for, test_include_boundaries_unknown_key, test_include_boundaries_missing_key, test_include_boundaries_non_string_list_element, @@ -2520,6 +2731,7 @@ def test_wasip3_abi_snapshot_requires_integrity_before_style_exemption(root): test_doc_comment_references, test_doc_comment_code_spans, test_changelog, + test_canary_pins, test_pyright, test_python_line_length, test_python_blank_lines, diff --git a/tools/lint/rules.py b/tools/lint/rules.py index a6f29689..f358d49f 100755 --- a/tools/lint/rules.py +++ b/tools/lint/rules.py @@ -35,7 +35,9 @@ changelog a library's changelog and a version's release notes keep AGENTS.md chapter 5's form, every line a bullet in it; include-boundaries a library keeps to the include boundaries its own - libs//meta/include-boundaries.json declares, when it has one. + libs//meta/include-boundaries.json declares, when it has one; + nodiscard-results a library whose libs//meta/lint.json asks for it declares every + function of its headers that returns boost::system::result [[nodiscard]]. """ from __future__ import annotations @@ -723,6 +725,85 @@ def include_boundaries(paths: list[str]) -> Iterator[Finding]: yield from library_findings(config_path, paths) +LINT_CONFIG = re.compile(r'libs/([^/]+)/meta/lint\.json') + +# The keys of a library's meta/lint.json, each the reason the library gives for its rule. +LINT_CONFIG_KEYS = frozenset({'nodiscard-results'}) + + +def results_without_nodiscard(path: str, text: str) -> Iterator[int]: + """The line of each function a C++ header declares returning boost::system::result<...> + (system::result<...> too) with no [[nodiscard]] among the words of its declaration before + the return type: back to the ;, { or } before it, or to an access specifier's colon. A + result that is a variable's type, a cast's or a constructor call's, has no name and a + parenthesis after the >, and is not read.""" + tokens = [token for token in cpp_tokens(text) if not token[0].endswith('-comment')] + count = len(tokens) + for index, (kind, word, line) in enumerate(tokens): + qualified = (index >= 3 and tokens[index - 1][1] == ':' and tokens[index - 2][1] == ':' + and tokens[index - 3][1] == 'system') + if kind != 'word' or word != 'result' or not qualified: + continue + if index + 1 >= count or tokens[index + 1][1] != '<': + continue + depth, close = 0, index + 1 + while close < count: + depth += {'<': 1, '>': -1}.get(tokens[close][1], 0) + if depth == 0: + break + close += 1 + name = close + 1 + if not (name + 1 < count and tokens[name][0] == 'word' and tokens[name][1] != 'operator' + and tokens[name + 1][1] == '('): + continue + before = index - 4 + words: set[str] = set() + while before >= 0: + token = tokens[before][1] + if token in (';', '{', '}'): + break + if (token == ':' and tokens[before - 1][1] != ':' + and (before + 1 >= count or tokens[before + 1][1] != ':')): + break + words.add(token) + before -= 1 + if 'nodiscard' not in words: + yield line + + +def nodiscard_results(paths: list[str]) -> Iterator[Finding]: + """Each library of libs/ whose meta/lint.json holds "nodiscard-results", its reason, is held + to it: a function of its include/ headers that returns boost::system::result and is not + [[nodiscard]] fails at its line, with the reason. A malformed file, or an unknown key, fails + naming the file. A library without the file, or without the key, passes silently.""" + for config_path in sorted(paths): + if not LINT_CONFIG.fullmatch(config_path): + continue + with open(config_path, encoding='utf-8', errors='replace') as file: + text = file.read() + try: + document = json.loads(text) + except json.JSONDecodeError as error: + yield (config_path, 1, f'not valid JSON: {error}') + continue + if not isinstance(document, dict) or not set(document) <= LINT_CONFIG_KEYS or any( + not isinstance(value, str) or not value for value in document.values()): + yield (config_path, 1, f'the file holds only the keys {sorted(LINT_CONFIG_KEYS)}, ' + 'each with a non-empty string, its reason') + continue + why = document.get('nodiscard-results') + if why is None: + continue + prefix = config_path[:-len('meta/lint.json')] + 'include/' + for path in sorted(paths): + if path.startswith(prefix) and LIBRARY_HEADER.fullmatch(path): + with open(path, encoding='utf-8', errors='replace') as file: + header = file.read() + for line in results_without_nodiscard(path, header): + yield (path, line, f'a function returning boost::system::result without ' + f'[[nodiscard]]: {why}') + + def changelog_lines(path: str, text: str) -> Iterator[Finding]: """A library's changelog and a version's release notes keep AGENTS.md chapter 5's form, each line of them a bullet in it (tools/release/changelog.py).""" @@ -750,6 +831,7 @@ def changelog_lines(path: str, text: str) -> Iterator[Finding]: # Rules that need every path at once, to find a library's own files from among them. WHOLE_TREE_RULES: dict[str, Callable[[list[str]], Iterator[Finding]]] = { 'include-boundaries': include_boundaries, + 'nodiscard-results': nodiscard_results, } RULES = sorted({*PER_FILE_RULES, *WHOLE_TREE_RULES}) diff --git a/tools/release/changelog.py b/tools/release/changelog.py index b397e8a9..2cd2013a 100755 --- a/tools/release/changelog.py +++ b/tools/release/changelog.py @@ -25,7 +25,8 @@ (+, ----, [source] and the like) or a directive (include::, ifdef::) inside a region fails. It starts with one of VERBS, or with "*Breaking change:* " and then one of VERBS, whose first letter may be lower case, holds the prefix nowhere else, holds at most WORDS words, and holds no -cross-reference, <<...>>, xref: or link:#, since the index page shows it too. A library's +cross-reference, <<...>>, xref: or link:#, since the index page shows it too, and no inline +anchor, [[...]] or anchor:, which shows no text (a C++ attribute is `+[[nodiscard]]+`). A library's version holds at most MOST of them; the sections of release notes have no such limit. Outside its regions, a library's changelog holds no bullet, and no text after its first section. @@ -78,6 +79,9 @@ # A cross-reference as Asciidoctor finds one, in a code span too, once its passthroughs are out. CROSS_REFERENCE = re.compile(r'<<[\w#/.:{].*?>>|\bxref:[\w#/.:{][^\s\[]*\[|\blink:#[^\s\[]*\[') PASSTHROUGH = re.compile(r'\+[^+]*\+') +# An inline anchor as Asciidoctor finds one, in a code span too, once its passthroughs are out: +# [[id]] or [[id,text]], whose id may hold colons, as a C++ attribute does, and anchor:id[]. +INLINE_ANCHOR = re.compile(r'\[\[[^\W\d][\w:.-]*(?:,[^\]]*)?\]\]|\banchor:[^\W\d][\w:.-]*\[') Finding = tuple[int, str] @@ -162,6 +166,17 @@ def cross_references(bullet: Bullet) -> list[Finding]: 'page shows it too')] +def anchors(bullet: Bullet) -> list[Finding]: + """An inline anchor the line holds: Asciidoctor renders it as an empty element, so that its + text, a C++ attribute such as [[nodiscard]], is missing from the line, and the index page, + showing the line too, holds its id twice.""" + if INLINE_ANCHOR.search(PASSTHROUGH.sub('', bullet.text)) is None: + return [] + return [(bullet.line, 'a line holds no anchor, [[...]] or anchor:, which shows no text and ' + 'whose id the index page repeats: a C++ attribute is code, ' + '`+[[nodiscard]]+`')] + + def line_findings(bullet: Bullet) -> list[Finding]: """What breaks a line's form.""" findings: list[Finding] = [] @@ -180,7 +195,7 @@ def line_findings(bullet: Bullet) -> list[Finding]: if words > WORDS: findings.append((bullet.line, f'a line holds at most {WORDS} words, and this one holds ' f'{words}: {bullet.text}')) - return findings + cross_references(bullet) + return findings + cross_references(bullet) + anchors(bullet) def section_starts(lines: list[str], index: int) -> bool: @@ -337,7 +352,7 @@ def listed(slug: str, pattern: re.Pattern[str]) -> list[tuple[str, str]]: if match is None: findings.append((item.line, f'not a line of {slug}: {item.text}')) else: - findings.extend(cross_references(item)) + findings.extend(cross_references(item) + anchors(item)) entries.append((match.group('name'), match.group('what'))) return entries diff --git a/tools/release/changelog_test.py b/tools/release/changelog_test.py index 76b6d1e1..26c27b52 100755 --- a/tools/release/changelog_test.py +++ b/tools/release/changelog_test.py @@ -7,10 +7,10 @@ """Checks tools/release/changelog.py: a library's changelog and a version's release notes in AGENTS.md chapter 5's form pass, wrapped lines included; a line with no verb of the list, a -cross-reference, an eleventh line, text outside a bullet, a section out of order or without its -region, and notes out of form each fail, at their line. The reader reads a list as the doc -build's Asciidoctor.js renders it, which tools/node/install.py installs when it is not there. -Run with the names of some cases to run only those.""" +cross-reference, an inline anchor, an eleventh line, text outside a bullet, a section out of +order or without its region, and notes out of form each fail, at their line. The reader reads a +list as the doc build's Asciidoctor.js renders it, which tools/node/install.py installs when it +is not there. Run with the names of some cases to run only those.""" from __future__ import annotations @@ -30,6 +30,8 @@ VERB_LIST = 'Added, Changed, Deprecated, Fixed, Improved, Removed, Updated' CROSS_REFERENCE = ('a line holds no cross-reference, <<...>>, xref: or link:#: the index page ' 'shows it too') +ANCHOR = ('a line holds no anchor, [[...]] or anchor:, which shows no text and whose id the index ' + 'page repeats: a C++ attribute is code, `+[[nodiscard]]+`') NESTED = ('a line of a changelog is a bullet at the margin, "* ", with no nested list, block, ' 'attribute or directive: ') @@ -138,6 +140,12 @@ def links_into_the_page(self) -> list[str]: return [target for target in own if target.startswith('#')] + [ target for child in self.elements() for target in child.links_into_the_page()] + def anchors(self) -> list[str]: + """The ids of the anchors this element holds, at any depth: an with an id.""" + own = [self.attributes.get('id') or ''] if self.tag == 'a' and 'id' in self.attributes \ + else [] + return own + [anchor for child in self.elements() for anchor in child.anchors()] + class Tree(HTMLParser): """The tree of elements of an HTML text.""" @@ -269,6 +277,28 @@ def test_cross_references_as_asciidoctor_reads_them() -> None: assert changelog.changelog_findings(text, 'alpha') == expected, line +def test_anchors_as_asciidoctor_reads_them() -> None: + # An inline anchor renders an empty , in a code span too: the line loses the text and + # the index page, which shows the line, gets the id twice. A C++ attribute in a passthrough, + # +...+, is code. + anchored = ['* Added every result [[nodiscard]].', '* Added `[[nodiscard]]` results.', + '* Added [[alpha-x,the x]]x.', '* Added anchor:alpha-x[] x.', + '* Added `[[gnu::always_inline]]`.'] + plain = ['* Added every result `+[[nodiscard]]+`.', '* Added +[[maybe_unused]]+ names.', + '* Added `+std::array{{1, 2}}+`.', '* Added `a[b[0]]`.'] + rendered = asciidoctor(''.join(f'== Case {number}\n\n{line}\n\n' + for number, line in enumerate(anchored + plain))) + sections = [section for section in rendered.elements() if section.kind == 'sect1'] + for line, section in zip(anchored + plain, sections): + assert bool(section.elements()[1].anchors()) == (line in anchored), line + text = log('alpha', ('Unreleased', [line])) + expected = [(line_of(text, line), ANCHOR)] if line in anchored else [] + assert changelog.changelog_findings(text, 'alpha') == expected, line + tools = '* Added the rule [[nodiscard]].' + text = notes(tools=tools) + assert findings_of(text) == [(line_of(text, tools), ANCHOR)] + + def test_text_outside_every_region_fails() -> None: # A line after a region's end shows on the page, but no release note includes it; so does a # bullet among the opening paragraphs. Before [appendix], only the notice may come. @@ -510,6 +540,7 @@ def test_the_tree_s_changelogs_keep_their_form() -> None: test_text_outside_a_bullet_and_a_cross_reference_fail, test_a_breaking_change_goes_on_with_a_verb, test_cross_references_as_asciidoctor_reads_them, + test_anchors_as_asciidoctor_reads_them, test_text_outside_every_region_fails, test_sections_in_order_each_with_its_region, test_each_section_named_as_its_title, diff --git a/tools/report/lanes.py b/tools/report/lanes.py index 6c462691..94b2b062 100644 --- a/tools/report/lanes.py +++ b/tools/report/lanes.py @@ -401,6 +401,10 @@ def row(location: str, example: bool, row_name: str, row_type: str) -> tuple[Row action = Action(text_of(element, 'name'), status, slashed(text_of(element, 'path')), command, text_of(element, 'output')) builds = owners.get(action.path, []) + # MSVC's link writes the program and its .pdb, and b2 may record the link under the .pdb, + # which no test needs: it is the link of the program beside it. + if not builds and action.path.endswith('.pdb'): + builds = owners.get(action.path[:-len('.pdb')] + '.exe', []) for build in builds: build.actions.append(action) if not builds and action.status != 0: diff --git a/tools/report/report_test.py b/tools/report/report_test.py index 7262a89f..5d9e4e61 100644 --- a/tools/report/report_test.py +++ b/tools/report/report_test.py @@ -15,7 +15,8 @@ whose transcript differs, a run failure, and a library's own lane on a target, named after the target and the library, which its column and its failures show and which it must hold true; an emscripten lane, its link-only program a link test, and a driven test whose driver fails, a run -failure. One case uses lanes.py and pages.py alone; one checks that no sample names the machine's +failure. One case uses lanes.py and pages.py alone, and one reads a link that MSVC's lane records +under the program's .pdb; one checks that no sample names the machine's temporary directory, and one that none holds what Emscripten says of its cache; a last one records every sample afresh, untrimmed, and checks that the report reads it as it reads the committed one. Every page written is checked to be self-contained, to link only to the report's own pages, to the @@ -824,6 +825,83 @@ def test_lanes_and_pages_work_alone(root: Path) -> None: check_pages(root / 'pages') +# What b2 writes on Windows for a test of webcpp.link-fail whose link fails as expected, trimmed to +# what lanes.py reads: MSVC's link builds the program and its .pdb, and b2 records the failed link +# under the .pdb, a target the test does not list as needed. A program of the build's tools, which +# no test owns, fails its link too, outside every test. No sample can be recorded on macOS. +MSVC_LINK_FAIL = r""" + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +""" + + +def test_a_failed_link_msvc_records_under_its_pdb_is_the_programs(root: Path) -> None: + # The link of a link-fail test is its program's, though b2 names it by the .pdb beside the + # .exe: the test passes and nothing of it is outside every test. A .pdb whose program no test + # owns stays outside. + path = root / 'msvc-link-fail.xml' + path.write_text(MSVC_LINK_FAIL) + lane = lanes.read_lane('native', path) + assert lane.toolset == 'msvc-14.3', lane.toolset + assert {row_id: row.verdict() for row_id, row in lane.rows.items()} == { + 'demo/absent': 'pass'}, lane.rows + build = lane.rows['demo/absent'].builds[0] + assert [action.path.rsplit('/', 1)[-1] for action in build.actions] == [ + 'absent.obj', 'absent.pdb', 'absent.test'], build.actions + assert [action.path for action in lane.outside] == [ + 'W:/build/bin/tools/msvc-14.3/dbg/helper.pdb'], lane.outside + + def tables(out: Path) -> dict[str, list[list[list[tuple[str, frozenset[str], str | None]]]]]: """The tables of the pages directly in out, by page, a lane's header by its lane: the toolset under it is the machine's (clang-darwin-21 here, clang-linux-22 on a Linux runner).""" @@ -911,6 +989,7 @@ def test_samples_read_as_b2_writes_them_today(root: Path) -> None: test_served_test_passes_and_fails_as_a_run, test_emscripten_lane_and_its_link_and_driven_tests, test_lanes_and_pages_work_alone, + test_a_failed_link_msvc_records_under_its_pdb_is_the_programs, test_samples_name_no_temporary_directory, test_samples_hold_nothing_of_emscriptens_cache, test_samples_read_as_b2_writes_them_today, diff --git a/tools/same_program/compare.py b/tools/same_program/compare.py new file mode 100644 index 00000000..7f804560 --- /dev/null +++ b/tools/same_program/compare.py @@ -0,0 +1,46 @@ +#!/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) + +"""Compares the two programs of webcpp.same-program byte for byte, and on emscripten the .wasm +beside each .js. Usage: compare.py --output FILE WITH WITHOUT""" + +from __future__ import annotations + +import argparse +import sys +from pathlib import Path + + +def main(argv: list[str]) -> int: + parser = argparse.ArgumentParser() + parser.add_argument('--output', required=True) + parser.add_argument('with_library') + parser.add_argument('without_library') + args = parser.parse_args(argv) + pairs = [(Path(args.with_library), Path(args.without_library))] + if pairs[0][0].suffix == '.js': + pairs.append((pairs[0][0].with_suffix('.wasm'), pairs[0][1].with_suffix('.wasm'))) + missing = [str(path) for pair in pairs for path in pair if not path.is_file()] + if missing: + for path in missing: + print(f'same_program: missing: {path} was not written by the link', file=sys.stderr) + return 1 + lines, faults = [], [] + for a, b in pairs: + same = a.read_bytes() == b.read_bytes() + line = f'{a} ({a.stat().st_size} bytes) and {b} ({b.stat().st_size} bytes)' + lines.append(('same: ' if same else 'differ: ') + line) + if not same: + faults.append(line) + Path(args.output).write_text('\n'.join(lines) + '\n') + for fault in faults: + print(f'same_program: differ: {fault}', file=sys.stderr) + return 1 if faults else 0 + + +if __name__ == '__main__': + sys.exit(main(sys.argv[1:])) diff --git a/tools/same_program/same_program.jam b/tools/same_program/same_program.jam new file mode 100644 index 00000000..c62d2870 --- /dev/null +++ b/tools/same_program/same_program.jam @@ -0,0 +1,121 @@ +# 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 rule of a library named and not called (CODING-GUIDELINES.md chapter 5, +# rule 11), which tools/webcpp.jam offers as webcpp.same-program: two exes of +# the same sources, one with the library and one without, each renamed by a +# tag rule to the test's name so that both outputs have the same name (ld64's +# ad hoc signature embeds it), each in a directory of its own (b2's +# , which a target's name alone would not give it), and a +# test whose action compares them byte for byte. Release, without debug +# information, and, with MSVC, /Brepro, which keeps a time stamp out of the +# link. Both programs link with the same flags, the linker's removal of +# unused sections included (the usage requirement of a C library, which the +# program with the library would otherwise alone have), and with the library +# as an archive, so that only the named library differs between them. This +# file is loaded as the module webcpp-same-program. +import feature ; +import generators ; +import modules ; +import os ; +import path ; +import project ; +import testing ; +import type ; +import virtual-target ; + +type.register SAME_RESULT : same-result ; +type.register SAME_PROGRAM : : TEST ; +generators.register-composing webcpp-same-program.compare : EXE : SAME_RESULT ; +generators.register-standard testing.expect-success : SAME_RESULT : SAME_PROGRAM ; + +# The output name of both programs of a pair. Free and incidental: the two +# programs' directories differ by their , never by this. +feature.feature webcpp-same-name : : free incidental ; + +if [ os.name ] = NT { .python = python ; } else { .python = python3 ; } +.here = [ path.parent [ path.root [ path.make [ modules.binding $(__name__) ] ] [ path.pwd ] ] ] ; +.compare = [ path.native $(.here)/compare.py ] ; + +# What both programs link with, whichever has the library: the linker's +# removal of unused sections, which a C library's usage requirements give the +# program that links it (WebAssembly's linkers remove them by default). The +# spelling is the one of those usage requirements, tools/webcpp-openssl.jam's +# declare and, for a C library, the third_party recipe's (CODING-GUIDELINES.md +# chapter 5, rule 4): a recipe that spells it another way must change it here +# too, or the pair would differ by that flag. +.link = darwin:-Wl,-dead_strip + linux:-Wl,--gc-sections + windows:"/OPT:REF" ; + +# The tag rule: an executable takes the pair's name, with the prefix and the +# suffix its type has on the target (b2 adds none after a tag rule returns). +rule tag ( name : type ? : property-set ) +{ + local same = [ $(property-set).get ] ; + if $(same) && [ type.is-derived $(type) EXE ] + { + return [ virtual-target.add-prefix-and-suffix $(same) : $(type) : $(property-set) ] ; + } +} + +# found is tools/webcpp.jam's `where`; only is the program's requirements of +# its targets. The pair is linked with static, so that the library is an +# archive whatever its own request says, and requirements, which only the two +# programs get, hold the handler of a build without exceptions. +rule same-program ( found + : name : sources + : library : only * : requirements * ) +{ + local pair = $(requirements) $(only) release off + msvc:/Brepro msvc:/Brepro + $(.link) static $(name) @webcpp-same-program%tag ; + exe $(name)_with : $(sources) $(library) : $(pair) $(name)_with ; + exe $(name)_without : $(sources) : $(pair) $(name)_without ; + $(found[1]).mark-target-as-explicit $(name)_with $(name)_without ; + testing.make-test same-program : $(name)_with $(name)_without + : $(only) $(name) : $(name) ; +} + +# The side of the pair named name that the target source belongs to, with or +# without, from the directory of that side in its path, which b2 spells with +# the platform's separator, a backslash on Windows; nothing for another +# directory. +rule side ( name : source ) +{ + if [ MATCH "[/\\]($(name)_with)[/\\]" : $(source) ] + { + return with ; + } + else if [ MATCH "[/\\]($(name)_without)[/\\]" : $(source) ] + { + return without ; + } +} + +# The two programs are the sources whose name is the pair's, in the directory +# of their side, never the first and the second source: a link may add files +# (MSVC's .pdb) or order them as it likes. +rule compare ( target : sources * : properties * ) +{ + local name = [ feature.get-values : $(properties) ] ; + for local source in $(sources) + { + if $(source:B) = $(name) && ! ( $(source:S) = .pdb ) + { + switch [ side $(name) : $(source) ] + { + case with : WITH on $(target) = $(source) ; + case without : WITHOUT on $(target) = $(source) ; + } + } + } + PYTHON on $(target) = $(.python) ; + COMPARE on $(target) = $(.compare) ; +} + +actions compare bind WITH WITHOUT +{ + "$(PYTHON)" "$(COMPARE)" --output "$(<)" "$(WITH)" "$(WITHOUT)" +} diff --git a/tools/test/crypto_jamfiles_format_test.py b/tools/test/crypto_jamfiles_format_test.py new file mode 100644 index 00000000..550eb2d3 --- /dev/null +++ b/tools/test/crypto_jamfiles_format_test.py @@ -0,0 +1,193 @@ +#!/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 crypto_jamfiles_test.py's own rules, without building anything: what an outcome file +may say, what a run that builds nothing is, and how a failure's lines are matched (whole lines). +""" + +from __future__ import annotations + +import subprocess +import sys +import tempfile +from pathlib import Path + +import crypto_jamfiles_test as jamfiles +import harness + +TEST = Path(__file__).resolve().parent / 'crypto_jamfiles_test.py' + + +def parse(text: str, target: str = 'native') -> jamfiles.Outcome: + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / 'case.outcome' + path.write_text(text) + return jamfiles.outcome(path, target) + + +def refused(text: str, *words: str) -> None: + try: + parse(text) + except jamfiles.OutcomeError as error: + assert all(word in str(error) for word in words), (text, str(error)) + return + raise AssertionError(f'accepted: {text!r}') + + +def test_a_good_outcome_is_read(): + result = parse('[all]\ntargets: native wasip2\nbuild: succeeds\nrun: app\nok\n' + '[wasip3]\nwasip3 only\n') + assert (result.targets, result.succeeds, result.run, result.lines) == ( + ['native', 'wasip2'], True, 'app', ['ok']), result + assert parse('[all]\nbuild: succeeds\nrun: app\nok\n[native]\nnative\n').lines == [ + 'ok', 'native'] + + +def test_the_format_is_enforced(): + refused('[everything]\nbuild: fails\nx\n', 'no block') + refused('build: fails\nx\n', 'before the first') + refused('[all]\nbuild: succeed\n', 'succeeds or fails') + refused('[all]\nbuild: fails\nx\nrun: app\n', 'run: after build: fails') + refused('[all]\nbuild: succeeds\nx\n', 'no run:') + refused('[all]\nbuild: fails\n', 'no line to find') + refused('[all]\nrun: app\nx\n', 'no build:') + refused('[all]\ntargets: native vax\nbuild: fails\nx\n', 'no target') + refused('[all]\nbuild: fails\nx\nargument: y\n', 'no directive') + refused('[wasip3]\nbuilds: fails\n[all]\nbuild: fails\nx\n', 'no directive') + + +def test_line_states_a_literal_output_line(): + lines = parse('[all]\nbuild: fails\nline: error: x\nline:\nline: # c\nline: [x]\n' + 'line: line: y\n').lines + assert lines == ['error: x', '', '# c', '[x]', 'line: y'], lines + refused('[all]\nbuild: fails\nerror: x\n', 'no directive') + + +def test_a_leftover_option_is_a_usage_error(): + for arguments in (['--targt', 'hello'], ['--target', 'native', '--target', 'native']): + result = run(*arguments) + assert result.returncode == 2, (arguments, result) + + +def test_contains_matches_part_of_a_line(): + assert parse('[all]\nbuild: fails\ncontains: part\n').contains == ['part'] + refused('[all]\nbuild: succeeds\nrun: app\ncontains: x\n', 'contains:') + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + case = root / 'c' + case.mkdir() + original = harness.run_b2 + harness.run_b2 = lambda *_a, **_k: subprocess.CompletedProcess( + [], 1, '/some/path/c.cpp:7:2: error: "boom"\n') + try: + for text, faults in (('boom', 0), ('/other', 1)): + (case / 'c.outcome').write_text(f'[all]\nbuild: fails\ncontains: {text}\n') + assert len(jamfiles.run_target(root, 'native', [case])) == faults, text + finally: + harness.run_b2 = original + + +def test_not_contains_forbids_a_text_in_every_line(): + assert parse('[all]\nbuild: fails\ncontains: a\nnot-contains: b\n' + 'not-contains: c unless d\n').forbidden == [('b', None), ('c', 'd')] + refused('[all]\nbuild: succeeds\nrun: app\nnot-contains: x\n', 'not-contains:') + refused('[all]\nbuild: fails\ncontains: a\nnot-contains:\n', 'names nothing') + refused('[all]\nbuild: fails\ncontains: a\nnot-contains: x unless \n', 'unless') + refused('[all]\nbuild: fails\nnot-contains: x\n', 'no line to find') + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + case = root / 'c' + case.mkdir() + original = harness.run_b2 + harness.run_b2 = lambda *_a, **_k: subprocess.CompletedProcess( + [], 1, 'undefined reference to `canary\'\nundefined reference to `other\'\n') + try: + for directive, faults in (('not-contains: unrelated', 0), + ('not-contains: undefined reference unless canary', 1), + ('not-contains: undefined reference unless canary or other', + 2), + ('not-contains: reference to `other', 1), + ('not-contains: undefined reference', 2)): + (case / 'c.outcome').write_text( + f'[all]\nbuild: fails\ncontains: canary\n{directive}\n') + found = jamfiles.run_target(root, 'native', [case]) + assert len(found) == faults, (directive, found) + finally: + harness.run_b2 = original + + +def test_same_as_keeps_copies_identical(): + with tempfile.TemporaryDirectory() as directory: + cases = Path(directory) + (cases / 'a').mkdir() + (cases / 'b').mkdir() + (cases / 'a' / 'app.cpp').write_text('int main() {}\n') + (cases / 'b' / 'app.cpp').write_text('int main() {}\n') + outcome = cases / 'b' / 'b.outcome' + outcome.write_text('[all]\nsame-as: a/app.cpp app.cpp\nbuild: succeeds\n') + assert jamfiles.same_as_faults(cases / 'b', cases) == [] + (cases / 'b' / 'app.cpp').write_text('int main() { return 1; }\n') + faults = jamfiles.same_as_faults(cases / 'b', cases) + assert len(faults) == 1 and 'a/app.cpp' in faults[0], faults + outcome.write_text('[all]\nsame-as: a/missing.cpp app.cpp\nbuild: succeeds\n') + assert jamfiles.same_as_faults(cases / 'b', cases), 'a missing copy is a fault' + outcome.write_text('[all]\nsame-as: a/app.cpp\nbuild: succeeds\n') + assert jamfiles.same_as_faults(cases / 'b', cases), 'one name is a fault' + assert parse('[all]\nsame-as: a/app.cpp app.cpp\nbuild: succeeds\n').succeeds + + +def test_every_case_directory_is_read(): + cases = jamfiles.case_directories() + assert {c.name for c in cases} >= {'hello', 'broken'}, cases + + +def run(*arguments: str) -> subprocess.CompletedProcess: + return subprocess.run([sys.executable, str(TEST), *arguments], capture_output=True, + text=True, check=False) + + +def test_a_run_that_builds_nothing_fails(): + unknown = run('nonexistent_case') + assert unknown.returncode != 0 and 'no case named' in unknown.stderr, unknown + nothing = run('--target', 'wasip3', 'hello') + assert nothing.returncode != 0 and 'nothing was tested' in nothing.stderr, nothing + assert run('--target').returncode == 2 + assert run('--target', 'vax').returncode == 2 + + +def test_a_failure_line_is_matched_whole(): + printed = ['user/c/c.cpp:7:2: error: "boom"', ' 7 | #error "boom" '] + original = harness.run_b2 + + def fake(*_args, **_kwargs): + return subprocess.CompletedProcess([], 1, '\n'.join(printed) + '\n') + + harness.run_b2 = fake + try: + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + case = root / 'c' + case.mkdir() + for line, faults in ((' 7 | #error "boom"', 0), ('"boom"', 1), + ('7:2: error: "boom"', 1)): + (case / 'c.outcome').write_text(f'[all]\nbuild: fails\n{line}\n') + assert len(jamfiles.run_target(root, 'native', [case])) == faults, line + finally: + harness.run_b2 = original + + +def main() -> int: + for name, case in sorted(globals().items()): + if name.startswith('test_'): + case() + print(f'{name}: ok') + print('crypto_jamfiles_format_test: ok') + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tools/test/crypto_jamfiles_test.py b/tools/test/crypto_jamfiles_test.py new file mode 100644 index 00000000..9b4cd1e5 --- /dev/null +++ b/tools/test/crypto_jamfiles_test.py @@ -0,0 +1,308 @@ +#!/usr/bin/env python3 +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +"""Builds every fixture of tools/test/fixtures/crypto_jamfiles, a Jamfile as a user of +webcpp::crypto writes it (b2's raw exe), with b2 as a user runs it, and checks its outcome file: +the build's status, the lines a failure prints, and a program's output (CODING-GUIDELINES.md +chapter 8). One scratch superproject per target, with libs/crypto and the fixtures in it; every +case of a target shares one build directory, so BearSSL's 295 files are compiled once per +target. Run with the names of some cases to run only those, and with --target to run one +target.""" + +from __future__ import annotations + +import platform +import re +import shutil +import subprocess +import sys +import time +from dataclasses import dataclass, field +from pathlib import Path + +import harness + +CASES = harness.FIXTURES / 'crypto_jamfiles' +TOOLSETS = {'native': [], 'wasip2': ['toolset=clang-wasip2'], 'wasip3': ['toolset=clang-wasip3'], + 'emscripten': ['toolset=emscripten']} +SYSTEM = {'Linux': 'linux', 'Darwin': 'darwin', 'Windows': 'windows'}[platform.system()] + +# Cases whose outcome needs code that is not merged yet: a run without names leaves them out +# (and says so), a run that names one builds it. Each entry names what it waits for. The +# integrator empties it when the code it waits for is merged, and then rewrites the lines of those +# cases' outcome files as b2's whole output lines (a line: directive, if need be). +NOT_YET: dict[str, str] = {} + +BLOCKS = {'all', 'native', 'native-linux', 'native-darwin', 'native-windows', 'wasip2', 'wasip3', + 'emscripten'} + + +class OutcomeError(Exception): + """An outcome file or a case directory that does not follow the format.""" + + +def launcher(target: str) -> Path: + """The script the lanes run a WASI program with (tools/ci/matrix.py, wasm_lane).""" + return harness.ROOT / f'tools/boost/asio-{target}/run.sh' + + +@dataclass +class Outcome: + """What an outcome file says for one target.""" + targets: list[str] = field(default_factory=lambda: ['native']) + succeeds: bool | None = None + run: str | None = None + lines: list[str] = field(default_factory=list) + contains: list[str] = field(default_factory=list) + # (text, allowed): no line of b2's output contains text, unless it also contains allowed + # (none: not even then). + forbidden: list[tuple[str, str | None]] = field(default_factory=list) + arguments: list[str] = field(default_factory=list) + + +def outcome(path: Path, target: str) -> Outcome: + """The blocks of path that apply to target on this system, read into an Outcome. Every line + of the file is checked, whether its block applies or not, and so is the outcome that results + when target is one the case is built for (checked).""" + applying = {'all', target} | ({'native', 'native-' + SYSTEM} if target == 'native' else set()) + result = Outcome() + block = None + for number, raw in enumerate(path.read_text().splitlines(), 1): + where = f'{path.name}:{number}' + if not raw.strip() or raw.startswith('#'): + continue + if raw.startswith('[') and raw.endswith(']'): + block = raw[1:-1] + if block not in BLOCKS: + raise OutcomeError(f'{where}: no block [{block}]; the blocks are {sorted(BLOCKS)}') + continue + if block is None: + raise OutcomeError(f'{where}: a line before the first [block]: {raw!r}') + directive = re.match(r'([a-z]+(?:-[a-z]+)?):(?: |$)', raw) + key, value = (directive.group(1), raw[directive.end():]) if directive else ('', raw) + if key and key not in ('targets', 'build', 'run', 'arguments', 'line', 'contains', + 'not-contains', 'same-as'): + raise OutcomeError(f'{where}: no directive {key}: (a line of one lowercase word and ' + f'a colon is reserved for them): {raw!r}') + if key in ('targets', 'arguments', 'not-contains') and not value.split(): + raise OutcomeError(f'{where}: {key}: names nothing') + if key == 'targets': + unknown = [t for t in value.split() if t not in TOOLSETS] + if unknown: + raise OutcomeError( + f'{where}: no target {unknown}; the targets are {list(TOOLSETS)}') + elif key == 'build' and value not in ('succeeds', 'fails'): + raise OutcomeError(f'{where}: build: is succeeds or fails, not {value!r}') + elif key == 'run' and not value: + raise OutcomeError(f'{where}: run: names no program') + if block not in applying or key == 'same-as': + continue + if key == 'targets': + result.targets = value.split() + elif key == 'build': + result.succeeds = value == 'succeeds' + elif key == 'run': + result.run = value + elif key == 'arguments': + result.arguments += value.split() + elif key == 'contains': + result.contains.append(value) + elif key == 'not-contains': + text, separator, allowed = value.partition(' unless ') + if not text.strip() or (separator and not allowed.strip()): + raise OutcomeError(f'{where}: not-contains: needs a text, then ` unless ` ' + f'if any line may hold it: {raw!r}') + result.forbidden.append((text.strip(), allowed.strip() or None)) + else: + result.lines.append(value if key == 'line' else raw) + if target in result.targets: + checked(path, target, result) + return result + + +def checked(path: Path, target: str, result: Outcome) -> None: + """Raises an OutcomeError naming path and target unless result is coherent: a build is said + to succeed or fail; a failure has lines to find and no program to run; a success that + prints lines has a program.""" + if result.succeeds is None: + raise OutcomeError(f'{path.name} on {target}: no build: line') + if not result.succeeds and result.run is not None: + raise OutcomeError(f'{path.name} on {target}: run: after build: fails') + if result.succeeds and (result.contains or result.forbidden): + raise OutcomeError(f'{path.name} on {target}: contains: or not-contains: after build: ' + 'succeeds') + if not result.succeeds and not result.lines and not result.contains: + raise OutcomeError(f'{path.name} on {target}: build: fails with no line to find') + if result.succeeds and result.run is None and result.lines: + raise OutcomeError(f'{path.name} on {target}: lines after build: succeeds, with no run:') + + +def same_as_faults(case: Path, cases: Path = CASES) -> list[str]: + """Each `same-as: / ` of case's outcome file whose two files are not + byte-identical: the file of another case, and case's own copy of it. A fixture's program is + a copy, never a symbolic link (a checkout on Windows reads a link as a text file), and this + keeps the copies from drifting.""" + faults: list[str] = [] + for number, raw in enumerate((case / f'{case.name}.outcome').read_text().splitlines(), 1): + if not raw.startswith('same-as:'): + continue + names = raw[len('same-as:'):].split() + where = f'{case.name}.outcome:{number}' + if len(names) != 2: + faults.append(f'{where}: same-as: names / and , not {names}') + continue + original, copy = cases / names[0], case / names[1] + if not original.is_file() or not copy.is_file(): + faults.append(f'{where}: {names[0]} or {case.name}/{names[1]} does not exist') + elif original.read_bytes() != copy.read_bytes(): + faults.append(f'{where}: {case.name}/{names[1]} is not a copy of {names[0]}') + return faults + + +def case_directories() -> list[Path]: + """Every directory of CASES, each with its one outcome file named after it, and every + outcome file read for every target (so each line of each block is checked), else an + OutcomeError.""" + cases = sorted(p for p in CASES.iterdir() if p.is_dir()) + for case in cases: + found = sorted(p.name for p in case.glob('*.outcome')) + if found != [case.name + '.outcome']: + raise OutcomeError(f'{case.name}: the outcome files are {found}; ' + f'the one is {case.name}.outcome') + if not (case / 'Jamfile').is_file(): + raise OutcomeError(f'{case.name}: no Jamfile') + for target in TOOLSETS: + outcome(case / f'{case.name}.outcome', target) + faults = same_as_faults(case) + if faults: + raise OutcomeError('; '.join(faults)) + return cases + + +def program_command(build_dir: Path, case: str, name: str, target: str) -> list[str]: + """The command that runs the program name that the build of case made under build_dir, as its + lane runs one.""" + suffix = {'native': '.exe' if SYSTEM == 'windows' else '', 'wasip2': '.wasm', + 'wasip3': '.wasm', 'emscripten': '.js'}[target] + found = [p for p in build_dir.rglob(name + suffix) + if p.is_file() and f'user/{case}/' in p.relative_to(build_dir).as_posix()] + if len(found) != 1: + raise AssertionError(f'the build made {len(found)} files named {name}{suffix}') + if target == 'emscripten': + return ['node', str(found[0])] + if target.startswith('wasi'): + return [str(launcher(target)), str(found[0])] + return [str(found[0])] + + +def selected(cases: list[Path], names: list[str], target: str) -> list[Path]: + """The cases to build for target: the named ones, else every one that is not in NOT_YET, + each that its outcome file's targets line names target for.""" + return [case for case in cases + if (case.name in names if names else case.name not in NOT_YET) + and target in outcome(case / f'{case.name}.outcome', target).targets] + + +def run_target(root: Path, target: str, cases: list[Path]) -> list[str]: + """Builds each of cases for target in root and returns the faults, one line each.""" + faults: list[str] = [] + build_dir = root / 'bin' / f'user-{target}' + for case in cases: + expected = outcome(case / f'{case.name}.outcome', target) + scratch = root / 'scratch' / case.name + scratch.mkdir(parents=True, exist_ok=True) + arguments = [a.replace('@scratch', str(scratch)) for a in expected.arguments] + # No testing.launcher: a user's exe is run by this test, not by b2. + built = harness.run_b2(root, '-j3', f'--build-dir={build_dir}', *TOOLSETS[target], + *arguments, f'user/{case.name}') + output = built.stdout + if (built.returncode == 0) != expected.succeeds: + faults.append(f'{case.name} on {target}: the build ' + f'{"succeeded" if built.returncode == 0 else "failed"}\n{output[-3000:]}') + continue + if not expected.succeeds: + printed = {line.rstrip() for line in output.splitlines()} + faults += [f'{case.name} on {target}: b2 printed no line {line!r}' + for line in expected.lines if line.rstrip() not in printed] + faults += [f'{case.name} on {target}: no line of b2 contains {text!r}' + for text in expected.contains + if not any(text in line for line in printed)] + faults += [f'{case.name} on {target}: b2 printed {line!r}, which contains {text!r}' + f'{"" if allowed is None else f" and not {allowed!r}"}' + for text, allowed in expected.forbidden for line in sorted(printed) + if text in line and (allowed is None or allowed not in line)] + continue + if expected.run is not None: + try: + command = program_command(build_dir, case.name, expected.run, target) + except AssertionError as error: + faults.append(f'{case.name} on {target}: {error}') + continue + ran = subprocess.run(command, capture_output=True, text=True, check=False) + printed = ran.stdout.replace('\r\n', '\n').splitlines() + if ran.returncode != 0 or printed != expected.lines: + faults.append(f'{case.name} on {target}: {expected.run} exited {ran.returncode} ' + f'and printed {printed!r}; the outcome says {expected.lines!r}') + return faults + + +def main(argv: list[str]) -> int: + targets = list(TOOLSETS) + if '--target' in argv: + position = argv.index('--target') + if position + 1 >= len(argv) or argv[position + 1] not in TOOLSETS: + print(f'crypto_jamfiles: --target takes one of {list(TOOLSETS)}', file=sys.stderr) + return 2 + targets = [argv[position + 1]] + argv = argv[:position] + argv[position + 2:] + names = [a for a in argv if not a.startswith('--')] + if len(names) != len(argv): + print(f'crypto_jamfiles: no option {[a for a in argv if a.startswith("--")]}; ' + 'the one is --target ', file=sys.stderr) + return 2 + try: + cases = case_directories() + except OutcomeError as error: + print(f'crypto_jamfiles: {error}', file=sys.stderr) + return 2 + missing = [n for n in names if n not in {c.name for c in cases}] + if missing: + print(f'crypto_jamfiles: no case named {missing}', file=sys.stderr) + return 2 + if not names and NOT_YET: + for case, reason in NOT_YET.items(): + print(f'left out until {reason}: {case}') + faults: list[str] = [] + built = 0 + for target in targets: + chosen = selected(cases, names, target) + if not chosen: + continue + built += len(chosen) + started = time.monotonic() + root = harness.scratch_superproject() + try: + harness.copy_integration_libraries(root, 'config', 'crypto') + shutil.copytree(CASES, root / 'user', ignore=harness.built) + if target == 'emscripten': + harness.link_emsdk(root) + elif target.startswith('wasi'): + harness.link_wasi_tools(root) + faults += run_target(root, target, chosen) + finally: + shutil.rmtree(root) + print(f'{target}: done in {time.monotonic() - started:.0f} s') + if not built: + faults.append(f'no case was built for {targets}; nothing was tested') + for fault in faults: + print(f'crypto_jamfiles: {fault}', file=sys.stderr) + print('crypto_jamfiles_test: ' + ('failed' if faults else 'ok')) + return 1 if faults else 0 + + +if __name__ == '__main__': + sys.exit(main(sys.argv[1:])) diff --git a/tools/test/fixtures/crypto_jamfiles/.clang-tidy b/tools/test/fixtures/crypto_jamfiles/.clang-tidy new file mode 100644 index 00000000..13e0f95b --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/.clang-tidy @@ -0,0 +1,15 @@ +# The fixtures, users' programs, inherit the superproject's configuration and switch off one +# option. +# +# bugprone-exception-escape.CheckMain treats every example's main as a +# function that should not throw. An example is a short program that lets +# what the standard library may throw, a std::bad_alloc or a +# std::length_error from a container that grows, end the process uncaught, +# the way Boost's own examples do; that is main's ordinary role, not a +# defect. The check stays on for everything else: a noexcept function, a +# destructor, a move or a swap. +--- +InheritParentConfig: true +CheckOptions: + - key: bugprone-exception-escape.CheckMain + value: 'false' diff --git a/tools/test/fixtures/crypto_jamfiles/block/Jamfile b/tools/test/fixtures/crypto_jamfiles/block/Jamfile new file mode 100644 index 00000000..e0a8b3a4 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/block/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 block : block.cpp /webcpp/crypto//crypto /third_party//ctaes ; +# end::jamfile[] diff --git a/tools/test/fixtures/crypto_jamfiles/block/block.cpp b/tools/test/fixtures/crypto_jamfiles/block/block.cpp new file mode 100644 index 00000000..659cfb57 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/block/block.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) + +// Encrypts the FIPS-197 appendix C.3 block with AES-256 on ctaes, checks it, and decrypts it again. +#include +#include + +#include +#include +#include +#include + +int main() { + std::array key{}; + for (std::size_t i = 0; i < key.size(); ++i) { + key[i] = static_cast(i); + } + std::array const plain{ + 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, + 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff, + }; + std::array const expected{ + 0x8e, 0xa2, 0xb7, 0xca, 0x51, 0x67, 0x45, 0xbf, + 0xea, 0xfc, 0x49, 0x90, 0x4b, 0x49, 0x60, 0x89, + }; + std::array block = plain; + auto aes = webcpp::crypto::ciphers::aes256::make(key); + bool const ok = + aes && aes->encrypt(block) && block == expected && aes->decrypt(block) && block == plain; + std::printf("ctaes aes256 %s\n", ok ? "ok" : "FAILED"); + return ok ? 0 : 1; +} diff --git a/tools/test/fixtures/crypto_jamfiles/block/block.outcome b/tools/test/fixtures/crypto_jamfiles/block/block.outcome new file mode 100644 index 00000000..2851fe3d --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/block/block.outcome @@ -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) + +[all] +targets: native wasip2 wasip3 emscripten +build: succeeds +run: block +# tag::output[] +ctaes aes256 ok +# end::output[] diff --git a/tools/test/fixtures/crypto_jamfiles/both_bearssl_default/Jamfile b/tools/test/fixtures/crypto_jamfiles/both_bearssl_default/Jamfile new file mode 100644 index 00000000..9f90a9fe --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/both_bearssl_default/Jamfile @@ -0,0 +1,10 @@ +# 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//openssl /third_party//bearssl + : WEBCPP_CRYPTO_DEFAULT_BACKEND_BEARSSL ; +# end::jamfile[] diff --git a/tools/test/fixtures/crypto_jamfiles/both_bearssl_default/app.cpp b/tools/test/fixtures/crypto_jamfiles/both_bearssl_default/app.cpp new file mode 100644 index 00000000..14a122b2 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/both_bearssl_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) + +// Seals one zero block under AES-256-GCM with the default backend 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 + +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 = webcpp::crypto::ciphers::aes256_gcm::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 = webcpp::crypto::ciphers::aes256_gcm::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_default/both_bearssl_default.outcome new file mode 100644 index 00000000..9caa81fa --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/both_bearssl_default/both_bearssl_default.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) + +[all] +targets: native wasip2 wasip3 +same-as: web/app.cpp app.cpp +build: succeeds +run: app +# tag::output[] +aes256_gcm ok backend=bearssl +# end::output[] diff --git a/tools/test/fixtures/crypto_jamfiles/broken/Jamfile b/tools/test/fixtures/crypto_jamfiles/broken/Jamfile new file mode 100644 index 00000000..3aba4fed --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/broken/Jamfile @@ -0,0 +1,7 @@ +# 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) + +exe broken : broken.cpp ; diff --git a/tools/test/fixtures/crypto_jamfiles/broken/broken.cpp b/tools/test/fixtures/crypto_jamfiles/broken/broken.cpp new file mode 100644 index 00000000..38699138 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/broken/broken.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) + +#error "broken on purpose" + +int main() {} diff --git a/tools/test/fixtures/crypto_jamfiles/broken/broken.outcome b/tools/test/fixtures/crypto_jamfiles/broken/broken.outcome new file mode 100644 index 00000000..cac4e663 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/broken/broken.outcome @@ -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) + +[all] +build: fails + 7 | #error "broken on purpose" diff --git a/tools/test/fixtures/crypto_jamfiles/canary_ctaes_missing/Jamfile b/tools/test/fixtures/crypto_jamfiles/canary_ctaes_missing/Jamfile new file mode 100644 index 00000000..9853c636 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/canary_ctaes_missing/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) + +# The header found, the library not linked. +# tag::jamfile[] +exe app : app.cpp /webcpp/crypto//crypto + : WEBCPP_CRYPTO_HAS_CTAES=1 ../../third_party/libs/bitcoin/src/crypto/ctaes ; +# end::jamfile[] diff --git a/tools/test/fixtures/crypto_jamfiles/canary_ctaes_missing/app.cpp b/tools/test/fixtures/crypto_jamfiles/canary_ctaes_missing/app.cpp new file mode 100644 index 00000000..4d687f7b --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/canary_ctaes_missing/app.cpp @@ -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) + +// Makes an AES-256 block cipher on ctaes and encrypts one block: the program reads ctaes's +// canary, so that a library built other than by webcpp's third_party/Jamfile fails to link. +#include +#include + +#include +#include + +int main() { + std::array const key{}; + std::array block{}; + auto aes = webcpp::crypto::ciphers::aes256::make(key); + return aes && aes->encrypt(block) ? 0 : 1; +} diff --git a/tools/test/fixtures/crypto_jamfiles/canary_ctaes_missing/canary_ctaes_missing.outcome b/tools/test/fixtures/crypto_jamfiles/canary_ctaes_missing/canary_ctaes_missing.outcome new file mode 100644 index 00000000..c75b5f30 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/canary_ctaes_missing/canary_ctaes_missing.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_ctaes_9be056a_default__add_third_party_ctaes_to_your_link +[native-linux] +contains: webcpp_crypto_ctaes_9be056a_default__add_third_party_ctaes_to_your_link +contains: undefined reference to `webcpp_crypto_ctaes_9be056a_default__add_third_party_ctaes_to_your_link' +[wasip2] +contains: wasm-ld: error: +contains: undefined symbol: webcpp_crypto_ctaes_9be056a_default__add_third_party_ctaes_to_your_link +[wasip3] +contains: wasm-ld: error: +contains: undefined symbol: webcpp_crypto_ctaes_9be056a_default__add_third_party_ctaes_to_your_link +[emscripten] +contains: wasm-ld: error: +contains: undefined symbol: webcpp_crypto_ctaes_9be056a_default__add_third_party_ctaes_to_your_link +contains: em++: error: +# end::messages[] diff --git a/tools/test/fixtures/crypto_jamfiles/canary_missing/Jamfile b/tools/test/fixtures/crypto_jamfiles/canary_missing/Jamfile new file mode 100644 index 00000000..46ca7593 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/canary_missing/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) + +# The header found, the library not linked. +# tag::jamfile[] +exe app : app.cpp /webcpp/crypto//crypto + : WEBCPP_CRYPTO_HAS_BEARSSL=1 ../../third_party/libs/bearssl/inc ; +# end::jamfile[] diff --git a/tools/test/fixtures/crypto_jamfiles/canary_missing/app.cpp b/tools/test/fixtures/crypto_jamfiles/canary_missing/app.cpp new file mode 100644 index 00000000..9e538fc8 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/canary_missing/app.cpp @@ -0,0 +1,23 @@ +// 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 AES-256-GCM on BearSSL and seals one block: the program reads BearSSL's canary, so that +// a library built other than by webcpp's third_party/Jamfile fails to link. +#include +#include +#include + +#include +#include + +int main() { + std::array const key{}; + std::array const iv{}; + std::array data{}; + auto aead = webcpp::crypto::ciphers::gcm< + webcpp::crypto::ciphers::aes256>::make(key); + return aead && aead->seal(iv, {}, data) ? 0 : 1; +} diff --git a/tools/test/fixtures/crypto_jamfiles/canary_missing/canary_missing.outcome b/tools/test/fixtures/crypto_jamfiles/canary_missing/canary_missing.outcome new file mode 100644 index 00000000..8848ddbb --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/canary_missing/canary_missing.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_bearssl_7bea48e_getentropy__add_third_party_bearssl_to_your_link +[native-linux] +contains: webcpp_crypto_bearssl_7bea48e_getentropy__add_third_party_bearssl_to_your_link +contains: undefined reference to `webcpp_crypto_bearssl_7bea48e_getentropy__add_third_party_bearssl_to_your_link' +[wasip2] +contains: wasm-ld: error: +contains: undefined symbol: webcpp_crypto_bearssl_7bea48e_getentropy__add_third_party_bearssl_to_your_link +[wasip3] +contains: wasm-ld: error: +contains: undefined symbol: webcpp_crypto_bearssl_7bea48e_getentropy__add_third_party_bearssl_to_your_link +[emscripten] +contains: wasm-ld: error: +contains: undefined symbol: webcpp_crypto_bearssl_7bea48e_getentropy__add_third_party_bearssl_to_your_link +contains: em++: error: +# end::messages[] diff --git a/tools/test/fixtures/crypto_jamfiles/canary_other_commit/Jamfile b/tools/test/fixtures/crypto_jamfiles/canary_other_commit/Jamfile new file mode 100644 index 00000000..fb853de8 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/canary_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) + +# BearSSL linked, the program built for another commit of it. +# tag::jamfile[] +exe app : app.cpp /webcpp/crypto//crypto /third_party//bearssl + : WEBCPP_CRYPTO_BEARSSL_CANARY_COMMIT=0000000 ; +# end::jamfile[] diff --git a/tools/test/fixtures/crypto_jamfiles/canary_other_commit/app.cpp b/tools/test/fixtures/crypto_jamfiles/canary_other_commit/app.cpp new file mode 100644 index 00000000..9e538fc8 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/canary_other_commit/app.cpp @@ -0,0 +1,23 @@ +// 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 AES-256-GCM on BearSSL and seals one block: the program reads BearSSL's canary, so that +// a library built other than by webcpp's third_party/Jamfile fails to link. +#include +#include +#include + +#include +#include + +int main() { + std::array const key{}; + std::array const iv{}; + std::array data{}; + auto aead = webcpp::crypto::ciphers::gcm< + webcpp::crypto::ciphers::aes256>::make(key); + return aead && aead->seal(iv, {}, data) ? 0 : 1; +} diff --git a/tools/test/fixtures/crypto_jamfiles/canary_other_commit/canary_other_commit.outcome b/tools/test/fixtures/crypto_jamfiles/canary_other_commit/canary_other_commit.outcome new file mode 100644 index 00000000..dabf0ad8 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/canary_other_commit/canary_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_bearssl_0000000_getentropy__add_third_party_bearssl_to_your_link +[native-linux] +contains: webcpp_crypto_bearssl_0000000_getentropy__add_third_party_bearssl_to_your_link +contains: undefined reference to `webcpp_crypto_bearssl_0000000_getentropy__add_third_party_bearssl_to_your_link' +[wasip2] +contains: wasm-ld: error: +contains: undefined symbol: webcpp_crypto_bearssl_0000000_getentropy__add_third_party_bearssl_to_your_link +[wasip3] +contains: wasm-ld: error: +contains: undefined symbol: webcpp_crypto_bearssl_0000000_getentropy__add_third_party_bearssl_to_your_link +[emscripten] +contains: wasm-ld: error: +contains: undefined symbol: webcpp_crypto_bearssl_0000000_getentropy__add_third_party_bearssl_to_your_link +contains: em++: error: +# end::messages[] diff --git a/tools/test/fixtures/crypto_jamfiles/canary_other_configuration/Jamfile b/tools/test/fixtures/crypto_jamfiles/canary_other_configuration/Jamfile new file mode 100644 index 00000000..deffb40c --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/canary_other_configuration/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) + +# BearSSL linked, the program built for another configuration of it. +# tag::jamfile[] +exe app : app.cpp /webcpp/crypto//crypto /third_party//bearssl + : WEBCPP_CRYPTO_BEARSSL_CANARY_CONFIGURATION=sysrng ; +# end::jamfile[] diff --git a/tools/test/fixtures/crypto_jamfiles/canary_other_configuration/app.cpp b/tools/test/fixtures/crypto_jamfiles/canary_other_configuration/app.cpp new file mode 100644 index 00000000..9e538fc8 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/canary_other_configuration/app.cpp @@ -0,0 +1,23 @@ +// 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 AES-256-GCM on BearSSL and seals one block: the program reads BearSSL's canary, so that +// a library built other than by webcpp's third_party/Jamfile fails to link. +#include +#include +#include + +#include +#include + +int main() { + std::array const key{}; + std::array const iv{}; + std::array data{}; + auto aead = webcpp::crypto::ciphers::gcm< + webcpp::crypto::ciphers::aes256>::make(key); + return aead && aead->seal(iv, {}, data) ? 0 : 1; +} diff --git a/tools/test/fixtures/crypto_jamfiles/canary_other_configuration/canary_other_configuration.outcome b/tools/test/fixtures/crypto_jamfiles/canary_other_configuration/canary_other_configuration.outcome new file mode 100644 index 00000000..e6f40bf4 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/canary_other_configuration/canary_other_configuration.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_bearssl_7bea48e_sysrng__add_third_party_bearssl_to_your_link +[native-linux] +contains: webcpp_crypto_bearssl_7bea48e_sysrng__add_third_party_bearssl_to_your_link +contains: undefined reference to `webcpp_crypto_bearssl_7bea48e_sysrng__add_third_party_bearssl_to_your_link' +[wasip2] +contains: wasm-ld: error: +contains: undefined symbol: webcpp_crypto_bearssl_7bea48e_sysrng__add_third_party_bearssl_to_your_link +[wasip3] +contains: wasm-ld: error: +contains: undefined symbol: webcpp_crypto_bearssl_7bea48e_sysrng__add_third_party_bearssl_to_your_link +[emscripten] +contains: wasm-ld: error: +contains: undefined symbol: webcpp_crypto_bearssl_7bea48e_sysrng__add_third_party_bearssl_to_your_link +contains: em++: error: +# end::messages[] diff --git a/tools/test/fixtures/crypto_jamfiles/canary_secp256k1_missing/Jamfile b/tools/test/fixtures/crypto_jamfiles/canary_secp256k1_missing/Jamfile new file mode 100644 index 00000000..609463a0 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/canary_secp256k1_missing/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) + +# The header found, the library not linked. +# tag::jamfile[] +exe app : app.cpp /webcpp/crypto//crypto + : WEBCPP_CRYPTO_HAS_SECP256K1=1 ../../third_party/libs/secp256k1/include ; +# end::jamfile[] diff --git a/tools/test/fixtures/crypto_jamfiles/canary_secp256k1_missing/app.cpp b/tools/test/fixtures/crypto_jamfiles/canary_secp256k1_missing/app.cpp new file mode 100644 index 00000000..b0df35ef --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/canary_secp256k1_missing/app.cpp @@ -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) + +// Makes a key pair and signs once: the program reads libsecp256k1's canary, so that a library +// built other than by webcpp's third_party/Jamfile fails to link. +#include + +#include +#include + +int main() { + std::array secret{}; + secret.fill(0x42); + std::array const message{}; + std::array const aux{}; + auto key = webcpp::crypto::curves::secp256k1::keypair::make(secret); + return key && key->sign_schnorr(message, aux) ? 0 : 1; +} diff --git a/tools/test/fixtures/crypto_jamfiles/canary_secp256k1_missing/canary_secp256k1_missing.outcome b/tools/test/fixtures/crypto_jamfiles/canary_secp256k1_missing/canary_secp256k1_missing.outcome new file mode 100644 index 00000000..167b3090 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/canary_secp256k1_missing/canary_secp256k1_missing.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_secp256k1_6e2c8bc_w15c11x6__add_third_party_secp256k1_to_your_link +[native-linux] +contains: webcpp_crypto_secp256k1_6e2c8bc_w15c11x6__add_third_party_secp256k1_to_your_link +contains: undefined reference to `webcpp_crypto_secp256k1_6e2c8bc_w15c11x6__add_third_party_secp256k1_to_your_link' +[wasip2] +contains: wasm-ld: error: +contains: undefined symbol: webcpp_crypto_secp256k1_6e2c8bc_w15c11x6__add_third_party_secp256k1_to_your_link +[wasip3] +contains: wasm-ld: error: +contains: undefined symbol: webcpp_crypto_secp256k1_6e2c8bc_w15c11x6__add_third_party_secp256k1_to_your_link +[emscripten] +contains: wasm-ld: error: +contains: undefined symbol: webcpp_crypto_secp256k1_6e2c8bc_w15c11x6__add_third_party_secp256k1_to_your_link +contains: em++: error: +# end::messages[] diff --git a/tools/test/fixtures/crypto_jamfiles/canary_secp256k1_small/Jamfile b/tools/test/fixtures/crypto_jamfiles/canary_secp256k1_small/Jamfile new file mode 100644 index 00000000..d36ec94d --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/canary_secp256k1_small/Jamfile @@ -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) + +# libsecp256k1 built with the large tables (the default natively and on WASI, +# forced here so that Emscripten agrees), and a program that names the small +# configuration. +# tag::jamfile[] +exe app : app.cpp /webcpp/crypto//crypto /third_party//secp256k1 + : large WEBCPP_CRYPTO_SECP256K1_CANARY_CONFIGURATION=w2c2x5 ; +# end::jamfile[] diff --git a/tools/test/fixtures/crypto_jamfiles/canary_secp256k1_small/app.cpp b/tools/test/fixtures/crypto_jamfiles/canary_secp256k1_small/app.cpp new file mode 100644 index 00000000..b0df35ef --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/canary_secp256k1_small/app.cpp @@ -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) + +// Makes a key pair and signs once: the program reads libsecp256k1's canary, so that a library +// built other than by webcpp's third_party/Jamfile fails to link. +#include + +#include +#include + +int main() { + std::array secret{}; + secret.fill(0x42); + std::array const message{}; + std::array const aux{}; + auto key = webcpp::crypto::curves::secp256k1::keypair::make(secret); + return key && key->sign_schnorr(message, aux) ? 0 : 1; +} diff --git a/tools/test/fixtures/crypto_jamfiles/canary_secp256k1_small/canary_secp256k1_small.outcome b/tools/test/fixtures/crypto_jamfiles/canary_secp256k1_small/canary_secp256k1_small.outcome new file mode 100644 index 00000000..79b44a8c --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/canary_secp256k1_small/canary_secp256k1_small.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_secp256k1_6e2c8bc_w2c2x5__add_third_party_secp256k1_to_your_link +[native-linux] +contains: webcpp_crypto_secp256k1_6e2c8bc_w2c2x5__add_third_party_secp256k1_to_your_link +contains: undefined reference to `webcpp_crypto_secp256k1_6e2c8bc_w2c2x5__add_third_party_secp256k1_to_your_link' +[wasip2] +contains: wasm-ld: error: +contains: undefined symbol: webcpp_crypto_secp256k1_6e2c8bc_w2c2x5__add_third_party_secp256k1_to_your_link +[wasip3] +contains: wasm-ld: error: +contains: undefined symbol: webcpp_crypto_secp256k1_6e2c8bc_w2c2x5__add_third_party_secp256k1_to_your_link +[emscripten] +contains: wasm-ld: error: +contains: undefined symbol: webcpp_crypto_secp256k1_6e2c8bc_w2c2x5__add_third_party_secp256k1_to_your_link +contains: em++: error: +# end::messages[] diff --git a/tools/test/fixtures/crypto_jamfiles/canary_without/Jamfile b/tools/test/fixtures/crypto_jamfiles/canary_without/Jamfile new file mode 100644 index 00000000..a5e8e5c7 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/canary_without/Jamfile @@ -0,0 +1,15 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +# BearSSL built by other means, without webcpp's canary: the program links every +# BearSSL function it calls, and only the canary is missing. +# tag::jamfile[] +path-constant BEARSSL : ../../third_party/libs/bearssl ; +lib bearssl-plain : [ glob $(BEARSSL)/src/*.c $(BEARSSL)/src/*/*.c ] + : static off $(BEARSSL)/inc $(BEARSSL)/src + : : $(BEARSSL)/inc WEBCPP_CRYPTO_HAS_BEARSSL=1 ; +exe app : app.cpp bearssl-plain /webcpp/crypto//crypto ; +# end::jamfile[] diff --git a/tools/test/fixtures/crypto_jamfiles/canary_without/app.cpp b/tools/test/fixtures/crypto_jamfiles/canary_without/app.cpp new file mode 100644 index 00000000..9e538fc8 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/canary_without/app.cpp @@ -0,0 +1,23 @@ +// 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 AES-256-GCM on BearSSL and seals one block: the program reads BearSSL's canary, so that +// a library built other than by webcpp's third_party/Jamfile fails to link. +#include +#include +#include + +#include +#include + +int main() { + std::array const key{}; + std::array const iv{}; + std::array data{}; + auto aead = webcpp::crypto::ciphers::gcm< + webcpp::crypto::ciphers::aes256>::make(key); + return aead && aead->seal(iv, {}, data) ? 0 : 1; +} diff --git a/tools/test/fixtures/crypto_jamfiles/canary_without/canary_without.outcome b/tools/test/fixtures/crypto_jamfiles/canary_without/canary_without.outcome new file mode 100644 index 00000000..dccf7941 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/canary_without/canary_without.outcome @@ -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) + +[all] +targets: native wasip2 wasip3 emscripten +build: fails +# tag::messages[] +[native-darwin] +contains: Undefined symbols for architecture +contains: _webcpp_crypto_bearssl_7bea48e_getentropy__add_third_party_bearssl_to_your_link +[native-linux] +contains: webcpp_crypto_bearssl_7bea48e_getentropy__add_third_party_bearssl_to_your_link +contains: undefined reference to `webcpp_crypto_bearssl_7bea48e_getentropy__add_third_party_bearssl_to_your_link' +[wasip2] +contains: wasm-ld: error: +contains: undefined symbol: webcpp_crypto_bearssl_7bea48e_getentropy__add_third_party_bearssl_to_your_link +[wasip3] +contains: wasm-ld: error: +contains: undefined symbol: webcpp_crypto_bearssl_7bea48e_getentropy__add_third_party_bearssl_to_your_link +[emscripten] +contains: wasm-ld: error: +contains: undefined symbol: webcpp_crypto_bearssl_7bea48e_getentropy__add_third_party_bearssl_to_your_link +contains: em++: error: +# end::messages[] + +# The canary is the only link error (spec section 4.3): no line names an undefined symbol or +# reference that is not it. Each linker's own words for one. +[native-darwin] +not-contains: ", referenced from: unless webcpp_crypto_bearssl_7bea48e_getentropy__add_third_party_bearssl_to_your_link +[native-linux] +not-contains: undefined reference unless webcpp_crypto_bearssl_7bea48e_getentropy__add_third_party_bearssl_to_your_link +[wasip2] +not-contains: undefined symbol unless webcpp_crypto_bearssl_7bea48e_getentropy__add_third_party_bearssl_to_your_link +[wasip3] +not-contains: undefined symbol unless webcpp_crypto_bearssl_7bea48e_getentropy__add_third_party_bearssl_to_your_link +[emscripten] +not-contains: undefined symbol unless webcpp_crypto_bearssl_7bea48e_getentropy__add_third_party_bearssl_to_your_link diff --git a/tools/test/fixtures/crypto_jamfiles/default_openssl_on_emscripten/Jamfile b/tools/test/fixtures/crypto_jamfiles/default_openssl_on_emscripten/Jamfile new file mode 100644 index 00000000..3b515494 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/default_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 : WEBCPP_CRYPTO_DEFAULT_BACKEND_OPENSSL ; +# end::jamfile[] diff --git a/tools/test/fixtures/crypto_jamfiles/default_openssl_on_emscripten/app.cpp b/tools/test/fixtures/crypto_jamfiles/default_openssl_on_emscripten/app.cpp new file mode 100644 index 00000000..6c80fb35 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/default_openssl_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_openssl_on_emscripten/default_openssl_on_emscripten.outcome b/tools/test/fixtures/crypto_jamfiles/default_openssl_on_emscripten/default_openssl_on_emscripten.outcome new file mode 100644 index 00000000..c4bbaadd --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/default_openssl_on_emscripten/default_openssl_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_OPENSSL selects OpenSSL, which is not built for Emscripten. Remove that define, or make it WEBCPP_CRYPTO_DEFAULT_BACKEND_BEARSSL. +# end::messages[] diff --git a/tools/test/fixtures/crypto_jamfiles/encrypt_and_sign/Jamfile b/tools/test/fixtures/crypto_jamfiles/encrypt_and_sign/Jamfile new file mode 100644 index 00000000..474ac68f --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/encrypt_and_sign/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//bearssl /third_party//secp256k1 ; +# end::jamfile[] diff --git a/tools/test/fixtures/crypto_jamfiles/encrypt_and_sign/app.cpp b/tools/test/fixtures/crypto_jamfiles/encrypt_and_sign/app.cpp new file mode 100644 index 00000000..355a9bc7 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/encrypt_and_sign/app.cpp @@ -0,0 +1,60 @@ +// 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 with the default backend and checks it against the +// NIST test vector (GCM test case 14), opens it again, then signs a message with BIP340 through +// libsecp256k1, verifies the signature, and refuses a changed message. +#include +#include +#include + +#include +#include +#include + +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 = webcpp::crypto::ciphers::aes256_gcm::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 = webcpp::crypto::ciphers::aes256_gcm::backend_type::name; + std::printf("aes256_gcm %s backend=%.*s\n", sealed && opened ? "ok" : "FAILED", + static_cast(name.size()), name.data()); + + namespace secp256k1 = webcpp::crypto::curves::secp256k1; + std::array secret{}; + secret.fill(0x42); + std::array message{}; + message.fill(0x17); + std::array const aux{}; + auto pair = secp256k1::keypair::make(secret); + bool signed_ok = false; + if (pair) { + auto const signature = pair->sign_schnorr(message, aux); + auto const public_key = pair->xonly_public_key(); + signed_ok = + signature && public_key && secp256k1::verify_schnorr(*signature, message, *public_key); + message[0] ^= 1U; + signed_ok = signed_ok && !secp256k1::verify_schnorr(*signature, message, *public_key); + } + std::printf("schnorr %s\n", signed_ok ? "ok" : "FAILED"); + return sealed && opened && signed_ok ? 0 : 1; +} 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 new file mode 100644 index 00000000..67a3be74 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/encrypt_and_sign/encrypt_and_sign.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) + +[all] +targets: native wasip2 wasip3 emscripten +build: succeeds +run: app +# tag::output[] +aes256_gcm ok backend=bearssl +schnorr ok +# end::output[] diff --git a/tools/test/fixtures/crypto_jamfiles/has_openssl_on_emscripten/Jamfile b/tools/test/fixtures/crypto_jamfiles/has_openssl_on_emscripten/Jamfile new file mode 100644 index 00000000..e4a79588 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/has_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 : WEBCPP_CRYPTO_HAS_OPENSSL=1 ; +# end::jamfile[] diff --git a/tools/test/fixtures/crypto_jamfiles/has_openssl_on_emscripten/app.cpp b/tools/test/fixtures/crypto_jamfiles/has_openssl_on_emscripten/app.cpp new file mode 100644 index 00000000..6c80fb35 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/has_openssl_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/has_openssl_on_emscripten/has_openssl_on_emscripten.outcome b/tools/test/fixtures/crypto_jamfiles/has_openssl_on_emscripten/has_openssl_on_emscripten.outcome new file mode 100644 index 00000000..83a016a0 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/has_openssl_on_emscripten/has_openssl_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: OpenSSL is not built for Emscripten. In the program's Jamfile, replace /webcpp/crypto//openssl with /third_party//bearssl. +# end::messages[] diff --git a/tools/test/fixtures/crypto_jamfiles/hello/Jamfile b/tools/test/fixtures/crypto_jamfiles/hello/Jamfile new file mode 100644 index 00000000..ad3d487c --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/hello/Jamfile @@ -0,0 +1,7 @@ +# 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) + +exe hello : hello.cpp ; diff --git a/tools/test/fixtures/crypto_jamfiles/hello/hello.cpp b/tools/test/fixtures/crypto_jamfiles/hello/hello.cpp new file mode 100644 index 00000000..49ede000 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/hello/hello.cpp @@ -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) + +#include + +int main() { + std::cout << "hello from a user's Jamfile\n"; +} diff --git a/tools/test/fixtures/crypto_jamfiles/hello/hello.outcome b/tools/test/fixtures/crypto_jamfiles/hello/hello.outcome new file mode 100644 index 00000000..6be8be2d --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/hello/hello.outcome @@ -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) + +[all] +targets: native wasip2 +build: succeeds +run: hello +hello from a user's Jamfile diff --git a/tools/test/fixtures/crypto_jamfiles/no_backend_on_emscripten/Jamfile b/tools/test/fixtures/crypto_jamfiles/no_backend_on_emscripten/Jamfile new file mode 100644 index 00000000..4b12ef4a --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/no_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/no_backend_on_emscripten/app.cpp b/tools/test/fixtures/crypto_jamfiles/no_backend_on_emscripten/app.cpp new file mode 100644 index 00000000..239e2450 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/no_backend_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 uses the default backend, which on WebAssembly is BearSSL, and links none. +#include + +#include +#include + +int main() { + std::array const key{}; + return webcpp::crypto::ciphers::aes256_gcm::make(key) ? 0 : 1; +} 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 new file mode 100644 index 00000000..8860220f --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/no_backend_on_emscripten/no_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 #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. +[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) +# end::messages[] diff --git a/tools/test/fixtures/crypto_jamfiles/openssl_linked/Jamfile b/tools/test/fixtures/crypto_jamfiles/openssl_linked/Jamfile new file mode 100644 index 00000000..8d6646e7 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/openssl_linked/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//openssl ; +# end::jamfile[] diff --git a/tools/test/fixtures/crypto_jamfiles/openssl_linked/app.cpp b/tools/test/fixtures/crypto_jamfiles/openssl_linked/app.cpp new file mode 100644 index 00000000..9eecbb0e --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/openssl_linked/app.cpp @@ -0,0 +1,41 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// A user's program that names /webcpp/crypto//openssl: it prints the define the alias gives, +// then seals an empty message under the zero key of 32 bytes and the zero IV of 12 bytes +// with OpenSSL's AES-256-GCM, and prints the tag (McGrew and Viega's test case 13). + +#include +#include +#include + +#include +#include +#include +#include + +int main() { +#ifdef WEBCPP_CRYPTO_HAS_OPENSSL + std::printf("HAS_OPENSSL=%d\n", WEBCPP_CRYPTO_HAS_OPENSSL); +#endif + namespace crypto = webcpp::crypto; + std::array const key{}; + std::array const iv{}; + auto made = crypto::ciphers::gcm>::make(key); + if (!made) { + return 1; + } + auto const tag = made->seal(iv, {}, std::span()); + if (!tag) { + return 1; + } + std::printf("tag "); + for (std::uint8_t const b : *tag) { + std::printf("%02x", static_cast(b)); + } + std::printf("\n"); + return 0; +} diff --git a/tools/test/fixtures/crypto_jamfiles/openssl_linked/openssl_linked.outcome b/tools/test/fixtures/crypto_jamfiles/openssl_linked/openssl_linked.outcome new file mode 100644 index 00000000..882bbca2 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/openssl_linked/openssl_linked.outcome @@ -0,0 +1,8 @@ +[all] +targets: native wasip2 wasip3 +build: succeeds +run: app +# tag::output[] +HAS_OPENSSL=1 +tag 530f8afbc74536b9a963b4f1c4cb738b +# end::output[] diff --git a/tools/test/fixtures/crypto_jamfiles/openssl_on_emscripten/Jamfile b/tools/test/fixtures/crypto_jamfiles/openssl_on_emscripten/Jamfile new file mode 100644 index 00000000..8d6646e7 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/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 /webcpp/crypto//openssl ; +# end::jamfile[] diff --git a/tools/test/fixtures/crypto_jamfiles/openssl_on_emscripten/app.cpp b/tools/test/fixtures/crypto_jamfiles/openssl_on_emscripten/app.cpp new file mode 100644 index 00000000..1ed000df --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/openssl_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 user's program over /webcpp/crypto//openssl. Until Task 12 writes the backend's header it +// prints the define and calls OpenSSL_version_num() alone; Task 12 Step 3 gives it the seal. + +#include + +#include + +int main() { +#if defined(WEBCPP_CRYPTO_HAS_OPENSSL) + std::cout << "HAS_OPENSSL=" << WEBCPP_CRYPTO_HAS_OPENSSL << '\n'; +#endif + return OpenSSL_version_num() >= 0x30000000UL ? 0 : 1; +} diff --git a/tools/test/fixtures/crypto_jamfiles/openssl_on_emscripten/openssl_on_emscripten.outcome b/tools/test/fixtures/crypto_jamfiles/openssl_on_emscripten/openssl_on_emscripten.outcome new file mode 100644 index 00000000..be30f285 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/openssl_on_emscripten/openssl_on_emscripten.outcome @@ -0,0 +1,6 @@ +[all] +targets: emscripten +build: fails +# tag::messages[] +contains: webcpp::crypto: /webcpp/crypto//openssl is named in a build for Emscripten, where webcpp does not build OpenSSL. +# end::messages[] diff --git a/tools/test/fixtures/crypto_jamfiles/server/Jamfile b/tools/test/fixtures/crypto_jamfiles/server/Jamfile new file mode 100644 index 00000000..8d6646e7 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/server/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//openssl ; +# end::jamfile[] diff --git a/tools/test/fixtures/crypto_jamfiles/server/app.cpp b/tools/test/fixtures/crypto_jamfiles/server/app.cpp new file mode 100644 index 00000000..14a122b2 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/server/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) + +// Seals one zero block under AES-256-GCM with the default backend 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 + +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 = webcpp::crypto::ciphers::aes256_gcm::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 = webcpp::crypto::ciphers::aes256_gcm::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/server/server.outcome b/tools/test/fixtures/crypto_jamfiles/server/server.outcome new file mode 100644 index 00000000..21b573cd --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/server/server.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) + +[all] +targets: native +same-as: web/app.cpp app.cpp +build: succeeds +run: app +# tag::output[] +aes256_gcm ok backend=openssl +# end::output[] diff --git a/tools/test/fixtures/crypto_jamfiles/sign/Jamfile b/tools/test/fixtures/crypto_jamfiles/sign/Jamfile new file mode 100644 index 00000000..41879233 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/sign/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 sign : sign.cpp /webcpp/crypto//crypto /third_party//secp256k1 ; +# end::jamfile[] diff --git a/tools/test/fixtures/crypto_jamfiles/sign/sign.cpp b/tools/test/fixtures/crypto_jamfiles/sign/sign.cpp new file mode 100644 index 00000000..fe328c21 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/sign/sign.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) + +// Signs a message with BIP340 through libsecp256k1, verifies it, and refuses a changed one. +#include + +#include +#include +#include + +int main() { + namespace secp256k1 = webcpp::crypto::curves::secp256k1; + std::array secret{}; + secret.fill(0x42); + std::array message{}; + message.fill(0x17); + std::array const aux{}; + auto 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 && secp256k1::verify_schnorr(*signature, message, *public_key); + message[0] ^= 1U; + ok = ok && !secp256k1::verify_schnorr(*signature, message, *public_key); + } + std::printf("schnorr %s\n", ok ? "ok" : "FAILED"); + return ok ? 0 : 1; +} diff --git a/tools/test/fixtures/crypto_jamfiles/sign/sign.outcome b/tools/test/fixtures/crypto_jamfiles/sign/sign.outcome new file mode 100644 index 00000000..eaba0877 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/sign/sign.outcome @@ -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) + +[all] +targets: native wasip2 wasip3 emscripten +build: succeeds +run: sign +# tag::output[] +schnorr ok +# end::output[] diff --git a/tools/test/fixtures/crypto_jamfiles/sign_small/Jamfile b/tools/test/fixtures/crypto_jamfiles/sign_small/Jamfile new file mode 100644 index 00000000..60e68d78 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/sign_small/Jamfile @@ -0,0 +1,10 @@ +# 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 sign : sign.cpp /webcpp/crypto//crypto /third_party//secp256k1 + : small ; +# end::jamfile[] diff --git a/tools/test/fixtures/crypto_jamfiles/sign_small/sign.cpp b/tools/test/fixtures/crypto_jamfiles/sign_small/sign.cpp new file mode 100644 index 00000000..fe328c21 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/sign_small/sign.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) + +// Signs a message with BIP340 through libsecp256k1, verifies it, and refuses a changed one. +#include + +#include +#include +#include + +int main() { + namespace secp256k1 = webcpp::crypto::curves::secp256k1; + std::array secret{}; + secret.fill(0x42); + std::array message{}; + message.fill(0x17); + std::array const aux{}; + auto 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 && secp256k1::verify_schnorr(*signature, message, *public_key); + message[0] ^= 1U; + ok = ok && !secp256k1::verify_schnorr(*signature, message, *public_key); + } + std::printf("schnorr %s\n", ok ? "ok" : "FAILED"); + return ok ? 0 : 1; +} diff --git a/tools/test/fixtures/crypto_jamfiles/sign_small/sign_small.outcome b/tools/test/fixtures/crypto_jamfiles/sign_small/sign_small.outcome new file mode 100644 index 00000000..b5d58df9 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/sign_small/sign_small.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) + +[all] +targets: native wasip2 wasip3 emscripten +same-as: sign/sign.cpp sign.cpp +build: succeeds +run: sign +# tag::output[] +schnorr ok +# end::output[] diff --git a/tools/test/fixtures/crypto_jamfiles/web/Jamfile b/tools/test/fixtures/crypto_jamfiles/web/Jamfile new file mode 100644 index 00000000..44088649 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/web/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//bearssl ; +# end::jamfile[] diff --git a/tools/test/fixtures/crypto_jamfiles/web/app.cpp b/tools/test/fixtures/crypto_jamfiles/web/app.cpp new file mode 100644 index 00000000..14a122b2 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/web/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) + +// Seals one zero block under AES-256-GCM with the default backend 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 + +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 = webcpp::crypto::ciphers::aes256_gcm::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 = webcpp::crypto::ciphers::aes256_gcm::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/web/web.outcome b/tools/test/fixtures/crypto_jamfiles/web/web.outcome new file mode 100644 index 00000000..c9e860a3 --- /dev/null +++ b/tools/test/fixtures/crypto_jamfiles/web/web.outcome @@ -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) + +[all] +targets: native wasip2 wasip3 emscripten +build: succeeds +run: app +# tag::output[] +aes256_gcm ok backend=bearssl +# end::output[] diff --git a/tools/test/jamroot_test.py b/tools/test/jamroot_test.py index e7718fe3..75cbd6dc 100755 --- a/tools/test/jamroot_test.py +++ b/tools/test/jamroot_test.py @@ -7,9 +7,9 @@ """Checks the Jamroot: it finds the installed Boost and searches it first, refuses a missing or older one by naming the fix, refuses one whose version it cannot read, checks again when Boost -changes, keeps Boost's warnings out of -Werror, refuses CPATH, and installs the headers. Each -case builds a scratch superproject with the fixture library demo. Run with the names of some -cases to run only those.""" +changes, keeps Boost's warnings out of -Werror, refuses CPATH, reaches third_party/ through both +of its project ids, and installs the headers. 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 @@ -216,6 +216,26 @@ def test_install_copies_headers_to_prefix(root): shutil.rmtree(prefix) +def test_third_party_has_both_ids(root): + # A user's Jamfile names /third_party// (CODING-GUIDELINES.md chapter 5, rule 5); + # the existing consumers name /webcpp/third_party//: both reach one project. The probe + # is appended to the real third_party/Jamfile, whose targets the Jamroot names. + with (root / 'third_party/Jamfile').open('a') as jamfile: + jamfile.write('\nalias probe : : : : WEBCPP_TEST_PROBE=1 ;\nexplicit probe ;\n') + harness.add_library(root, 'ids', 'alias one : /third_party//probe ;\n' + 'alias two : /webcpp/third_party//probe ;\n', {}) + result = harness.run_b2(root, '-n', 'libs/ids/test//one', 'libs/ids/test//two') + harness.expect(result, True) + + +def test_third_party_refuses_a_name_it_does_not_have(root): + # A name that is no target of third_party/Jamfile stops the build and says so, by the id a + # user's Jamfile writes (spec section 4.1, "A user names a backend by its project id"). + harness.add_library(root, 'nothere', 'alias one : /third_party//nothere ;\n', {}) + result = harness.run_b2(root, '-n', 'libs/nothere/test//one') + harness.expect(result, False, 'Unable to find file or target named', 'nothere') + + CASES = [ test_boost_found_and_fixture_builds, test_no_boost_configured_names_the_fix, @@ -228,6 +248,8 @@ def test_install_copies_headers_to_prefix(root): test_cpath_set_is_refused, test_a_relative_user_config_is_found, test_install_copies_headers_to_prefix, + test_third_party_has_both_ids, + test_third_party_refuses_a_name_it_does_not_have, ] diff --git a/tools/test/openssl_one_copy_test.py b/tools/test/openssl_one_copy_test.py new file mode 100644 index 00000000..3b96200d --- /dev/null +++ b/tools/test/openssl_one_copy_test.py @@ -0,0 +1,81 @@ +#!/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 asio's and crypto's OpenSSL aliases in one program link libssl.a and libcrypto.a +once each, from one directory (CODING-GUIDELINES.md chapter 5 rule 10). + +It reads the link line b2 prints (-d+2 with -n, so nothing is rebuilt) for +libs/crypto/test//openssl_one_copy and its _no_exceptions twin, and fails on any archive count +other than one per program, or on archives from two directories. +""" +import os +import re +import subprocess +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +ARCHIVE = re.compile(r'[^\s"]*/lib(ssl|crypto)\.a') +LINK = re.compile(r'-o "?[^\s"]*/openssl_one_copy(_no_exceptions)?"?(\s|$)') + + +def check_link_line(line: str) -> list[str]: + """The faults of one link line: an archive not exactly once, or two directories.""" + found = [m.group(0) for m in ARCHIVE.finditer(line)] + faults = [] + for name in ('libssl.a', 'libcrypto.a'): + count = sum(1 for path in found if path.endswith('/' + name)) + if count != 1: + faults.append(f'{name} is linked {count} times') + if len({path.rsplit('/', 1)[0] for path in found}) > 1: + faults.append(f'the archives come from different directories: {sorted(set(found))}') + return faults + + +def self_test() -> None: + """The checker itself: a line with a repeated archive or two directories must fail.""" + good = '-o "x/openssl_one_copy" /a/config-1/libssl.a /a/config-1/libcrypto.a' + assert check_link_line(good) == [] + twice = good + ' /a/config-1/libssl.a' + assert check_link_line(twice) == ['libssl.a is linked 2 times'] + split = '-o "x/openssl_one_copy" /a/config-1/libssl.a /b/config-2/libcrypto.a' + assert 'different directories' in ' '.join(check_link_line(split)) + assert check_link_line('-o "x/openssl_one_copy"') != [] + + +def main() -> int: + self_test() + unset = ('CPATH', 'CPLUS_INCLUDE_PATH', 'C_INCLUDE_PATH') + env = {k: v for k, v in os.environ.items() if k not in unset} + command = ['b2', f'--user-config={ROOT}/.local/user-config.jam', '-a', '-n', '-d+2', '-j3', + '--build-dir=' + str(ROOT / 'bin/lane-onecopy'), *sys.argv[1:], + 'libs/crypto/test//openssl_one_copy', + 'libs/crypto/test//openssl_one_copy_no_exceptions'] + result = subprocess.run(command, cwd=ROOT, env=env, capture_output=True, text=True, check=False) + if result.returncode != 0: + print(result.stdout + result.stderr, file=sys.stderr) + return 1 + lines = [line for line in result.stdout.splitlines() + if LINK.search(line) and ARCHIVE.search(line)] + # b2 prints a command on several lines; join each link command from its -o line to the next + # blank. + text = result.stdout + commands = [chunk for chunk in re.split(r'\n\s*\n', text) + if LINK.search(chunk) and ARCHIVE.search(chunk)] + if len(commands) != 2: + print(f'openssl_one_copy: expected 2 link commands, found {len(commands)} ' + f'({len(lines)} lines)', file=sys.stderr) + return 1 + faults = [fault for chunk in commands for fault in check_link_line(chunk)] + for fault in faults: + print(f'openssl_one_copy: {fault}', file=sys.stderr) + if not faults: + print('openssl_one_copy_test: ok') + return 1 if faults else 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tools/test/third_party_test.py b/tools/test/third_party_test.py index edcc4851..893513ca 100755 --- a/tools/test/third_party_test.py +++ b/tools/test/third_party_test.py @@ -10,8 +10,13 @@ emscripten, and on wasip2 and wasip3, where wasmtime is given that directory; a changed file of the suite runs such a test again; and a suite that is not checked out stops a build that needs it, naming the command that checks it out, and no other build. Each case builds a scratch superproject -with the fixture library demo, whose path holds a space. Run with the names of some cases to run -only those.""" +with the fixture library demo, whose path holds a space. It also checks that BearSSL, pinned and +built from its real sources with the canary of libs/crypto, compiles file by file with the flags a C +library needs and holds the canary's symbol; that a BearSSL or a libs/crypto that is not checked out +stops the build that needs it, naming the command; and that loading third_party/Jamfile prints +nothing b2 warns of. libsecp256k1, pinned, is built file by file with every module and +webcpp::crypto's canary, with the large tables natively and the small ones on request and on +emscripten. Run with the names of some cases to run only those.""" from __future__ import annotations @@ -29,6 +34,16 @@ WASIP3 = ('toolset=clang-wasip3', 'testing.launcher=wasmtime') EMSCRIPTEN = ('toolset=emscripten',) +BEARSSL = 'third_party/libs/bearssl' + +# The commit BearSSL is pinned at, of the mirror webcpporg/bearssl. +BEARSSL_COMMIT = '7bea48e5e850ab4cafbe68d3765cdaba13a86d6f' + +BITCOIN = 'third_party/libs/bitcoin' + +# The commit ctaes's submodule, Bitcoin Core v31.1, is pinned at. +BITCOIN_COMMIT = '9be056a8a72b624dae9623b2f7bded92c2a21c91' + PASSED = re.compile(r'^\*\*passed\*\* (.*)$', re.MULTILINE) SUITE = 'third_party/libs/JSON-Schema-Test-Suite' @@ -36,6 +51,38 @@ # The commit the suite is pinned at, of 2026-09-21. SUITE_COMMIT = '5b0ee1613e45fcc2bddac00e07c19cd49b00d8a8' +WYCHEPROOF = 'third_party/libs/wycheproof' + +# The commit Wycheproof is pinned at, of 2026-10-06. +WYCHEPROOF_COMMIT = '12fd3aaf33eb5fa1f52e026912ee00c054f9d984' + +BIPS = 'third_party/libs/bips' + +# The commit the Bitcoin Improvement Proposals' repository is pinned at: the test vectors of +# BIP340 and BIP341 (libs/crypto/test/secp256k1_bip340_test.cpp, secp256k1_xonly_tweak_test.cpp). +BIPS_COMMIT = '927b6de9915c9262615a6399de51b200f81e5aa4' + +SECP256K1 = 'third_party/libs/secp256k1' + +# libsecp256k1 v0.8.0, the commit it is pinned at. +SECP256K1_COMMIT = '6e2c8bc4ecdc6e71dbe7a368f360d8d453ce435d' + +# The C files /third_party//secp256k1 compiles, as libsecp256k1's CMake builds the library, and +# webcpp::crypto's canary. +SECP256K1_FILES = ['secp256k1.c', 'precomputed_ecmult.c', 'precomputed_ecmult_gen.c', + 'canary_secp256k1.c'] + +# Its seven modules, every one on. +SECP256K1_MODULES = [f'-DENABLE_MODULE_{name}=1' for name in + ('ECDH', 'RECOVERY', 'EXTRAKEYS', 'SCHNORRSIG', 'MUSIG', 'ELLSWIFT', + 'SILENTPAYMENTS')] + +# The small tables: window 2 and comb 2x5. +SECP256K1_SMALL = ['-DECMULT_WINDOW_SIZE=2', '-DCOMB_BLOCKS=2', '-DCOMB_TEETH=5'] + +# The compile line of a C file, as b2 prints it at -d+2. +C_COMPILE = re.compile(r'^\s*"?\S*(?:clang|gcc|emcc|em\+\+)\S*"? -x c .*$', re.MULTILINE) + READER_JAMFILE = ('import webcpp ;\n' '\n' 'webcpp.targets native wasip2 wasip3 emscripten ;\n' @@ -94,6 +141,12 @@ def test_the_suite_is_pinned(_: Path) -> None: assert listed.stdout.split()[:2] == ['160000', SUITE_COMMIT], listed.stdout +def test_wycheproof_is_pinned(_: Path) -> None: + listed = subprocess.run(['git', '-C', str(harness.ROOT), 'ls-files', '-s', WYCHEPROOF], + capture_output=True, text=True, check=True) + assert listed.stdout.split()[:2] == ['160000', WYCHEPROOF_COMMIT], listed.stdout + + def test_the_suite_reaches_a_native_test(root: Path) -> None: add_reader(root) result = harness.run_b2(root, '-a', 'libs/suite_reader/test') @@ -146,6 +199,98 @@ def test_a_changed_suite_file_runs_the_test_again(root: Path) -> None: assert passed(again) == set(), (changed, again.stdout[-4000:]) +def test_bips_is_pinned(_: Path) -> None: + listed = subprocess.run(['git', '-C', str(harness.ROOT), 'ls-files', '-s', BIPS], + capture_output=True, text=True, check=True) + assert listed.stdout.split()[:2] == ['160000', BIPS_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) + assert listed.stdout.split()[:2] == ['160000', BEARSSL_COMMIT], listed.stdout + + +def test_bearssl_is_built_file_by_file(root: Path) -> None: + harness.copy_integration_libraries(root, 'config', 'crypto') + result = harness.run_b2(root, '-a', '-d+2', 'third_party//bearssl') + harness.expect(result, True) + compiles = [line for line in result.stdout.splitlines() + if re.search(r'(clang|gcc)\S* .*-x c ', line) and ' -c ' in line] + # The 294 files of BearSSL's src/ and webcpp::crypto's canary. + assert len(compiles) == 295, (len(compiles), result.stdout[-4000:]) + required = ['-ffunction-sections', '-fdata-sections', '-DBR_RDRAND=0', '-DBR_USE_URANDOM=0', + '-DBR_USE_GETENTROPY=1', '-D_DEFAULT_SOURCE'] + if sys.platform == 'darwin': + required.append('-include sys/random.h') + for line in compiles: + for flag in required: + assert flag in line, (flag, line) + assert '-std=' not in line, line + archive = sorted((root / 'bin').rglob('libbearssl.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 '' + canary = (f'{prefix}webcpp_crypto_bearssl_7bea48e_getentropy__add_third_party_bearssl' + '_to_your_link') + assert canary in symbols.stdout.split(), symbols.stdout[-2000:] + + +def test_third_party_jamfile_loads_without_noise(root: Path) -> None: + # b2 prints "Unescaped special character in argument" on stdout for a flag such as /OPT:REF + # that a Jamfile does not quote, on every load of that Jamfile. + result = harness.run_b2(root, '-n', 'third_party//json-schema-test-suite') + harness.expect(result, True) + assert 'Unescaped special character' not in result.stdout, result.stdout[-4000:] + + +def test_bearssl_not_checked_out_is_refused(root: Path) -> None: + harness.copy_integration_libraries(root, 'config', 'crypto') + harness.third_party_of_its_own(root, 'bearssl', checked_out=False) + result = harness.run_b2(root, 'third_party//bearssl') + harness.expect(result, False, 'third_party/libs/bearssl is not checked out', + 'git submodule update --init third_party/libs/bearssl') + # A build that needs no BearSSL never looks for it. + harness.expect(harness.run_b2(root, 'libs/demo/test//pass'), True) + + +def test_crypto_not_checked_out_is_refused(root: Path) -> None: + # No libs/crypto in the scratch superproject: the canary is missing. + result = harness.run_b2(root, 'third_party//bearssl') + harness.expect(result, False, 'libs/crypto is not checked out', + 'git submodule update --init libs/crypto') + + +def test_ctaes_is_pinned(_: Path) -> None: + listed = subprocess.run(['git', '-C', str(harness.ROOT), 'ls-files', '-s', BITCOIN], + capture_output=True, text=True, check=True) + assert listed.stdout.split()[:2] == ['160000', BITCOIN_COMMIT], listed.stdout + + +def test_ctaes_is_built_from_one_file_and_the_canary(root: Path) -> None: + harness.copy_integration_libraries(root, 'config', 'crypto') + result = harness.run_b2(root, '-a', '-d+2', 'third_party//ctaes') + harness.expect(result, True) + compiles = [line for line in result.stdout.splitlines() + if re.search(r'(clang|gcc)\S* .*-x c ', line) and ' -c ' in line] + # Bitcoin Core's src/crypto/ctaes/ctaes.c and webcpp::crypto's canary: nothing else of the + # tree, whose libsecp256k1 is never built. + assert len(compiles) == 2, (len(compiles), result.stdout[-4000:]) + assert any('src/crypto/ctaes/ctaes.c' in line for line in compiles), compiles + for line in compiles: + for flag in ('-ffunction-sections', '-fdata-sections'): + assert flag in line, (flag, line) + assert '-std=' not in line, line + assert 'src/secp256k1' not in line, line + archive = sorted((root / 'bin').rglob('libctaes.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 '' + canary = (f'{prefix}webcpp_crypto_ctaes_9be056a_default__add_third_party_ctaes' + '_to_your_link') + assert canary in symbols.stdout.split(), symbols.stdout[-2000:] + + def test_a_suite_not_checked_out_is_refused(root: Path) -> None: harness.third_party_of_its_own(root, 'JSON-Schema-Test-Suite', checked_out=False) add_reader(root) @@ -156,13 +301,90 @@ 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_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) + result = harness.run_b2(root, 'third_party//ctaes') + harness.expect(result, False, 'third_party/libs/bitcoin is not checked out', + 'git submodule update --init --depth 1 third_party/libs/bitcoin') + + +def build_secp256k1(root: Path, *request: str) -> tuple[list[str], bytes]: + """Builds /third_party//secp256k1 with every action shown, from libs/crypto's real canary, + and returns its C compile lines and the bytes of its archive.""" + harness.copy_integration_libraries(root, 'crypto') + result = harness.run_b2(root, '-a', '-d+2', *request, 'third_party//secp256k1') + harness.expect(result, True) + archives = sorted((root / 'bin').rglob('libsecp256k1.a')) + assert len(archives) == 1, archives + return C_COMPILE.findall(result.stdout), archives[0].read_bytes() + + +def expect_secp256k1(lines: list[str], archive: bytes, small: bool) -> None: + """Asserts that the five C files were compiled once each with every module on and the tables + asked, and that the archive defines the canary of that configuration.""" + compiled = sorted(Path(line.rsplit(' ', 1)[-1].strip('"')).name for line in lines) + assert compiled == sorted(SECP256K1_FILES), compiled + for line in lines: + for define in SECP256K1_MODULES: + assert define in line.split(), (define, line) + for define in SECP256K1_SMALL: + assert (define in line.split()) == small, (define, line) + configuration = 'w2c2x5' if small else 'w15c11x6' + canary = (f'webcpp_crypto_secp256k1_6e2c8bc_{configuration}' + '__add_third_party_secp256k1_to_your_link') + assert canary.encode() in archive, canary + + +def test_secp256k1_is_pinned(_: Path) -> None: + listed = subprocess.run(['git', '-C', str(harness.ROOT), 'ls-files', '-s', SECP256K1], + capture_output=True, text=True, check=True) + assert listed.stdout.split()[:2] == ['160000', SECP256K1_COMMIT], listed.stdout + + +def test_secp256k1_natively_has_the_large_tables(root: Path) -> None: + expect_secp256k1(*build_secp256k1(root), small=False) + + +def test_secp256k1_small_tables_on_request(root: Path) -> None: + expect_secp256k1(*build_secp256k1(root, 'webcpp-secp256k1-tables=small'), small=True) + + +def test_secp256k1_on_emscripten_has_the_small_tables(root: Path) -> None: + harness.link_emsdk(root) + expect_secp256k1(*build_secp256k1(root, *EMSCRIPTEN), small=True) + + +def test_secp256k1_not_checked_out_is_refused(root: Path) -> None: + harness.third_party_of_its_own(root, 'secp256k1', checked_out=False) + harness.copy_integration_libraries(root, 'crypto') + result = harness.run_b2(root, 'third_party//secp256k1') + harness.expect(result, False, 'third_party/libs/secp256k1 is not checked out', + 'git submodule update --init third_party/libs/secp256k1') + + CASES = [ test_the_suite_is_pinned, + test_wycheproof_is_pinned, test_the_suite_reaches_a_native_test, test_the_suite_reaches_a_test_on_emscripten, 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_bips_is_pinned, + test_bearssl_is_pinned, + test_bearssl_is_built_file_by_file, + test_third_party_jamfile_loads_without_noise, + test_bearssl_not_checked_out_is_refused, + test_crypto_not_checked_out_is_refused, + test_ctaes_is_pinned, + test_ctaes_is_built_from_one_file_and_the_canary, + test_ctaes_not_checked_out_is_refused, + test_secp256k1_is_pinned, + test_secp256k1_natively_has_the_large_tables, + test_secp256k1_small_tables_on_request, + test_secp256k1_on_emscripten_has_the_small_tables, + test_secp256k1_not_checked_out_is_refused, ] diff --git a/tools/test/webcpp_jam_test.py b/tools/test/webcpp_jam_test.py index 71d5d152..4c632d5b 100755 --- a/tools/test/webcpp_jam_test.py +++ b/tools/test/webcpp_jam_test.py @@ -12,7 +12,8 @@ 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, and is skipped on a toolset that is not clang; +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; `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 @@ -21,7 +22,11 @@ is built and run natively only, its framework always with exceptions; Boost.JSON's definitions link on every target; every program sees C++20 and exceptions, on every target; and a test reads the directory webcpp.data gives it, which must be absolute and hold no character the shell would read, -at the same path on every target, wasmtime being given it on WASI. Each case builds a scratch +at the same path on every target, wasmtime being given it on WASI; and webcpp.same-program passes +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.""" from __future__ import annotations @@ -241,6 +246,81 @@ def test_compile_diagnostic_passes_only_on_its_diagnostic(root): assert 'stated' not in result.stdout, result.stdout[-4000:] +def test_compile_diagnostic_fails_on_a_directive_clang_drops(root): + # A directive that clang's -verify cannot read is dropped, with an error of its own that the + # rule's tolerance of a header's cascade of errors would hide: one that names a header that + # does not exist, alone, beside a directive that holds, or on a later line of a /* */ + # comment, and one whose text runs past its line. Each such test proves nothing, and fails, + # naming the directive; so does one whose compile reports no error at all. The cascade of + # errors that follows a header's #error is still tolerated, and so are a directive in a + # branch the preprocessor skips, which clang never reads, an expected note, and a // in a + # string before a directive on the same line. + guard = '#error "the guard says no"\nint after_the_guard() { return undeclared; }\n' + stated = ('// expected-error@guard.hpp:* {{the guard says no}}\n' + '#include "guard.hpp"\n' + 'int main() { return undeclared; }\n') + holds = { + 'stated': stated, + # Never read: clang skips the branch, so it names nothing. + 'skipped': '#if 0\n// expected-error@renamed/guard.hpp:* {{never}}\n#endif\n' + stated, + 'noted': ('template void needs_int(T) requires(sizeof(T) == 4) {}\n' + '// expected-note@-1 {{because}}\n' + 'void call() {\n' + ' // expected-error@+1 {{no matching function}}\n' + ' needs_int(1.0);\n' + '}\n'), + # The error is on the line of its directive, after a string that holds //, before the + # comment. + 'url': ('const char* url = "http://example.org"; int value = undeclared;' + ' // expected-error {{undeclared}}\n'), + } + dropped = { + 'missing': (stated.replace('@guard.hpp', '@renamed/guard.hpp'), + "file 'renamed/guard.hpp' could not be located", 'missing.cpp:1:'), + 'missing_beside': ('// expected-error@renamed/guard.hpp:* {{the guard says no}}\n' + + stated, "file 'renamed/guard.hpp' could not be located", + 'missing_beside.cpp:1:'), + 'missing_in_block': ('/* The guard, stated twice:\n' + ' expected-error@renamed/guard.hpp:* {{the guard says no}} */\n' + + stated, "file 'renamed/guard.hpp' could not be located", + 'missing_in_block.cpp:2:'), + 'unfinished': (stated.replace('{{the guard says no}}', '{{the guard\n// says no}}'), + "cannot find end ('}}')", 'unfinished.cpp:1:'), + 'no_error': ('// expected-no-diagnostics\nint main() { return 0; }\n', + 'reported no error', 'no_error'), + } + sources = {f'{name}.cpp': text for name, text in holds.items()} + sources.update({f'{name}.cpp': text for name, (text, _, _) in dropped.items()}) + harness.add_library( + root, 'dropped', + 'import webcpp ;\n' + '\n' + 'webcpp.targets native wasip2 ;\n' + '\n' + + ''.join(f'webcpp.compile-diagnostic {name} : {name}.cpp ;\n' + for name in [*holds, *dropped]), + dict(sources, **{'guard.hpp': guard})) + result = harness.run_b2(root, *(f'libs/dropped/test//{name}' for name in holds)) + harness.expect(result, True) + assert passed(result) == set(holds), (passed(result), result.stdout[-4000:]) + for name, (_, said, where) in dropped.items(): + result = harness.run_b2(root, f'libs/dropped/test//{name}') + harness.expect(result, False, said, where) + assert not passed(result), (name, result.stdout[-4000:]) + result = harness.run_b2(root, *WASIP2, 'libs/dropped/test//missing') + harness.expect(result, False, "file 'renamed/guard.hpp' could not be located") + assert not passed(result), result.stdout[-4000:] + # The check is a source of the test: a change of it runs the check again. (clang writes no + # object for a translation unit with errors, -verify or not, so each build compiles the + # test's source again too.) + kept = ('libs/dropped/test//stated',) + harness.expect(harness.run_b2(root, *kept), True) + harness.replace(root / 'tools/compile_diagnostic/check.py', + "if __name__ == '__main__':\n", + "if __name__ == '__main__':\n sys.exit('the check changed')\n") + harness.expect(harness.run_b2(root, *kept), False, 'the check changed') + + 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 @@ -1110,6 +1190,202 @@ def test_link_fail_checks_linking_and_keeps_success_controls(root): harness.expect(harness.run_b2(root, 'libs/linkage/test'), False) +# The fixture library of webcpp.same-program: a static library whose one function a program may +# call, whose usage requirement defines SAME_HAS_UNUSED, as a C library's defines +# WEBCPP__HAS_, so that a program's own source differs between the pair unless it +# ignores the define. +SAME_JAMFILE = ('import webcpp ;\n' + '\n' + 'webcpp.targets native wasip2 wasip3 emscripten ;\n' + '\n' + 'lib unused : unused.cpp : static : : SAME_HAS_UNUSED ;\n' + 'webcpp.same-program hello_unused : hello.cpp : unused ;\n') + +SAME_LIBRARY = 'int unused_answer() { return 42; }\n' + +SAME_SOURCES = { + 'unused.cpp': SAME_LIBRARY, + # Names the library and calls nothing of it. + 'hello.cpp': ('#include \n' + 'int main() { std::puts("hello"); return 0; }\n'), +} + +# The same program calling the library's function, when the library is there. +SAME_CALLS = ('#include \n' + '#ifdef SAME_HAS_UNUSED\n' + 'int unused_answer();\n' + '#endif\n' + 'int main() {\n' + '#ifdef SAME_HAS_UNUSED\n' + ' std::printf("%d\\n", unused_answer());\n' + '#endif\n' + ' return 0;\n' + '}\n') + + +def add_same_program(root, jamfile=SAME_JAMFILE, sources=None): + """Adds the library same, whose test Jamfile declares webcpp.same-program hello_unused.""" + harness.add_library(root, 'same', jamfile, sources or SAME_SOURCES) + + +def test_a_library_named_and_not_called_adds_nothing(root): + harness.link_wasi_tools(root) + add_same_program(root) + for request in ((), WASIP2, WASIP3): + result = harness.run_b2(root, '-a', *request, 'libs/same/test') + harness.expect(result, True) + assert passed(result) == {'hello_unused'}, (request, passed(result), result.stdout[-4000:]) + # b2 lists it with the tests and the report records it (tools/report reads the --out-xml). + harness.expect(harness.run_b2(root, '-d0', '--dump-tests', 'libs/same/test'), True, + 'hello_unused') + xml = root / 'same.xml' + harness.expect(harness.run_b2(root, '-a', f'--out-xml={xml}', 'libs/same/test'), True) + assert 'hello_unused' in xml.read_text(), xml.read_text()[-2000:] + + +def test_a_library_called_differs(root): + add_same_program(root, sources=dict(SAME_SOURCES, **{'hello.cpp': SAME_CALLS})) + result = harness.run_b2(root, '-a', 'libs/same/test') + harness.expect(result, False, 'same_program: differ: ', 'bytes) and ', 'bytes)') + # Both files are named, in directories of their own, with their sizes. + differ = re.search(r'differ: (\S+) \((\d+) bytes\) and (\S+) \((\d+) bytes\)', result.stdout) + assert differ, result.stdout[-4000:] + with_file, with_size, without_file, without_size = differ.groups() + assert with_file != without_file, differ.group(0) + assert (root / with_file).read_bytes() != (root / without_file).read_bytes(), differ.group(0) + assert (int(with_size), int(without_size)) == ((root / with_file).stat().st_size, + (root / without_file).stat().st_size) + assert with_file.rsplit('/', 1)[-1] == without_file.rsplit('/', 1)[-1] == 'hello_unused', ( + differ.group(0)) + assert passed(result) == set(), result.stdout[-4000:] + # The library's code gone from the program, the pair is the same again. + (root / 'libs/same/test/hello.cpp').write_text(SAME_SOURCES['hello.cpp']) + harness.expect(harness.run_b2(root, '-a', 'libs/same/test'), True) + + +def linked_as(result, name, suffix=''): + """The directories of the files b2's link lines of result write as name, in order.""" + found = (re.search(rf'-o "?(\S*)/{re.escape(name + suffix)}"? ', line) for line in + result.stdout.splitlines() if ' -o ' in line) + return [match.group(1) for match in found if match] + + +def test_the_pair_shares_one_name(root): + harness.link_wasi_tools(root) + add_same_program(root) + for request, suffix in (((), ''), (WASIP2, '.wasm')): + result = harness.run_b2(root, '-d+2', '-a', *request, 'libs/same/test') + harness.expect(result, True) + directories = linked_as(result, 'hello_unused', suffix) + assert len(directories) == 2 and len(set(directories)) == 2, ( + request, directories, result.stdout[-4000:]) + assert sorted(part for d in directories for part in d.split('/') + if part.startswith('hello_unused_')) == [ + 'hello_unused_with', 'hello_unused_without'], directories + + +def test_the_pair_shares_one_name_on_emscripten(root): + harness.link_emsdk(root) + add_same_program(root) + result = harness.run_b2(root, '-d+2', '-a', *EMSCRIPTEN, 'libs/same/test') + harness.expect(result, True) + assert passed(result) == {'hello_unused'}, (passed(result), result.stdout[-4000:]) + for suffix in ('js', 'wasm'): + found = sorted((root / 'bin').rglob(f'hello_unused.{suffix}')) + assert len(found) == 2 and found[0].parent != found[1].parent, (suffix, found) + assert found[0].read_bytes() == found[1].read_bytes(), found + # A program that calls the library differs, and the report names the .wasm too. + (root / 'libs/same/test/hello.cpp').write_text(SAME_CALLS) + result = harness.run_b2(root, '-a', *EMSCRIPTEN, 'libs/same/test') + harness.expect(result, False, 'same_program: differ: ') + assert '.wasm (' in result.stdout, result.stdout[-4000:] + + +# A program that throws through Boost's handler: built without exceptions it links only with +# tools/throw_exception.cpp, which every program rule gives it, the pair's two programs included. +SAME_THROWS = ('#include \n' + '#include \n' + 'int main(int argc, char**) {\n' + ' if (argc > 5) boost::throw_exception(std::runtime_error("planted"));\n' + ' return 0;\n' + '}\n') + + +def test_a_pair_built_without_exceptions_links_the_handler_and_compares_equal(root): + harness.link_wasi_tools(root) + add_same_program(root, sources=dict(SAME_SOURCES, **{'hello.cpp': SAME_THROWS})) + for request in ((), WASIP2): + result = harness.run_b2(root, '-a', '-j3', *request, 'exception-handling=off', + 'libs/same/test') + harness.expect(result, True) + assert passed(result) == {'hello_unused'}, (request, passed(result), result.stdout[-4000:]) + + +def test_a_shared_library_is_compared_as_a_static_one(root): + # The library's own request is the default, shared: the pair still links it as an archive, or + # the program with it would differ by its load command alone. + add_same_program(root, SAME_JAMFILE.replace('unused.cpp : static : :', + 'unused.cpp : : :')) + harness.expect(harness.run_b2(root, '-a', '-j3', 'libs/same/test'), True) + assert list((root / 'bin').glob('**/release/**/link-static/libunused.a')), sorted( + path.name for path in (root / 'bin').rglob('libunused*')) + + +# A library that carries the usage requirement a C library's third_party recipe gives it, the +# linker's removal of unused sections: the pair must link with the same flags, so that it is the +# library, and not the flag, that differs. The program holds a function nothing calls, in its own +# section, which that removal takes out of a program that links with the flag. +SAME_GC_JAMFILE = ('import webcpp ;\n' + '\n' + 'webcpp.targets native wasip2 wasip3 emscripten ;\n' + '\n' + 'lib unused : unused.cpp : static : :\n' + ' darwin:-Wl,-dead_strip\n' + ' linux:-Wl,--gc-sections\n' + ' windows:/OPT:REF ;\n' + 'webcpp.same-program hello_unused : hello.cpp : unused\n' + ' : : -ffunction-sections -fdata-sections ;\n') + +SAME_DEAD = ('#include \n' + 'int dead_weight() { return 7; }\n' + 'int main() { std::puts("hello"); return 0; }\n') + + +def test_a_library_with_gc_flags_still_compares_equal(root): + harness.link_wasi_tools(root) + add_same_program(root, SAME_GC_JAMFILE, dict(SAME_SOURCES, **{'hello.cpp': SAME_DEAD})) + for request in ((), WASIP2): + result = harness.run_b2(root, '-a', *request, 'libs/same/test') + harness.expect(result, True) + assert passed(result) == {'hello_unused'}, (request, passed(result), result.stdout[-4000:]) + + +def test_the_pair_is_found_by_its_directory_on_every_path_separator(root): + # The compare rule tells the two programs apart by the directory of their side, which b2 + # spells with the platform's separator: a backslash on Windows, where the pair was compared + # with nothing until the rule read both separators. b2 here runs on POSIX, so the rule is fed + # the targets' names as each platform spells them (a Jam token's backslash is doubled). + sources = { + 'posix with': 'hello_unused.exe', + 'posix without': 'hello_unused.exe', + 'nt with': r'hello_unused.exe', + 'nt without': r'hello_unused.exe', + 'neither': r'hello_unused.exe', + 'a prefix only': 'hello_unused.exe', + } + jamfile = 'import modules ;\nimport webcpp ;\n\n' + for label, source in sources.items(): + jamfile += (f'ECHO "side {label}:" ' + f'[ modules.call-in webcpp-same-program : side hello_unused : {source} ] ;\n') + harness.add_library(root, 'probe', jamfile, {}) + result = harness.run_b2(root, 'libs/probe/test') + harness.expect(result, True) + found = {line.split(':', 1)[0].removeprefix('side '): line.split(':', 1)[1].strip() + for line in result.stdout.splitlines() if line.startswith('side ')} + assert found == {'posix with': 'with', 'posix without': 'without', 'nt with': 'with', + 'nt without': 'without', 'neither': '', 'a prefix only': ''}, found + + CASES = [ test_link_fail_checks_linking_and_keeps_success_controls, test_source_only_corpus_is_not_loaded_as_a_build, @@ -1119,6 +1395,7 @@ def test_link_fail_checks_linking_and_keeps_success_controls(root): test_compile_builds_only_where_declared, 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_filter_maps_each_toolset_to_its_target, test_undeclared_jamfile_is_native_only, test_emscripten_builds_only_what_declares_it, @@ -1148,6 +1425,14 @@ def test_link_fail_checks_linking_and_keeps_success_controls(root): test_without_its_data_a_wasi_test_reads_nothing, test_data_must_be_absolute, test_data_the_shell_would_read_is_refused, + test_a_library_named_and_not_called_adds_nothing, + test_a_library_called_differs, + test_the_pair_shares_one_name, + test_the_pair_shares_one_name_on_emscripten, + test_a_library_with_gc_flags_still_compares_equal, + 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, ] diff --git a/tools/webcpp.jam b/tools/webcpp.jam index 3b10003a..e6c29449 100644 --- a/tools/webcpp.jam +++ b/tools/webcpp.jam @@ -55,6 +55,13 @@ # webcpp.reference library : requirements * : also-checked * ; # webcpp.index page ; # +# the rule of a library named and not called, tools/same_program's, which +# builds sources with the library and without it, and passes when the two +# programs are byte-identical: +# +# webcpp.same-program name : sources + : library : targets * +# : requirements * ; +# # and the rules of the oracle, tools/oracle/oracle.jam's, with which a # library's test/oracle/Jamfile runs its original over its twins and cases: # @@ -221,6 +228,18 @@ modules.load webcpp-generated : generated.jam : [ path.native [ path.join $(.tools) generated ] ] ; import webcpp-generated ; +# The test type of compile-diagnostic, loaded as the module +# webcpp-compile-diagnostic, as the documentation's are. +modules.load webcpp-compile-diagnostic : compile_diagnostic.jam + : [ path.native [ path.join $(.tools) compile_diagnostic ] ] ; +import webcpp-compile-diagnostic ; + +# The rule of a library named and not called, loaded as the module +# webcpp-same-program, as the documentation's are. +modules.load webcpp-same-program : same_program.jam + : [ path.native [ path.join $(.tools) same_program ] ] ; +import webcpp-same-program ; + .nl = "\n" ; # The conditional requirement of every program: no when the toolset @@ -313,7 +332,7 @@ rule targets ( targets + ) # is recorded for declared, and each program as " # ..." for programs: kind is the rule that declares it, run, # run-fail, compile, compile-fail, compile-diagnostic, boost-test, example, -# headers-alone, serve, link or drive. +# headers-alone, serve, link, drive or same-program. local rule program ( kind : names + : targets * ) { local jamfile = [ jamfile ] ; @@ -604,22 +623,30 @@ rule compile-fail ( name : sources + : requirements * : targets * ) # clang's -verify comments: `// expected-error@:* {{}}` for # an error of a header they include, `// expected-error@+1 {{}}` for # one of the next line. clang's -verify makes the compile succeed only when -# every stated error appears; an error that is not stated, and a note, are -# ignored (-verify-ignore-unexpected=error,note), so that a header's -# #error may be followed by what the rest of the header then fails on. A -# compile-fail test passes on any error, the wrong one included; this one -# only on the one it states. -verify is clang's: on a toolset other than +# every stated error appears, in the file it names; an error that is not +# stated, and a note, are ignored (-verify-ignore-unexpected=error,note), so +# that a header's #error may be followed by what the rest of the header then +# fails on. Among those ignored errors are the ones -verify reports on a +# directive it cannot read, which it then drops: a header it names that +# cannot be located, a text whose `}}` is not on its line. The test's check, +# tools/compile_diagnostic's, runs the compile again with clang's diagnostic +# log and fails on any error located in a comment, a // or a /* */ one over +# several lines, after an expected- of that comment, and on a compile +# that reports no error at all. So each directive clang reads, every one +# outside a branch the preprocessor skips, must be read whole, its header +# found and included, and its error raised there. A compile-fail test +# passes on any error, the wrong one included; this one only on the one it +# states. -verify is clang's: on a toolset other than # 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 * ) { - testing.compile $(sources) + webcpp-compile-diagnostic.compile-diagnostic $(name) : $(sources) : $(requirements) "-Xclang -verify -Xclang -verify-ignore-unexpected=error,note" @webcpp%clang-only [ program compile-diagnostic : $(name) : $(targets) ] - $(.node-test) - : $(name) ; + $(.node-test) ; } # The conditional requirement of compile-diagnostic: no on a toolset @@ -1372,3 +1399,14 @@ rule generated ( name : script : arguments * : outputs + ) { webcpp-generated.generated [ where ] : $(name) : $(script) : $(arguments) : $(outputs) ; } + +# A test that builds sources with library and without it, under one output +# name, in two directories of their own, and passes when the two files are +# byte-identical: a library named and not called adds no byte +# (CODING-GUIDELINES.md chapter 5, rule 11). +rule same-program ( name : sources + : library : targets * : requirements * ) +{ + local only = [ program same-program : $(name) : $(targets) ] ; + webcpp-same-program.same-program [ where ] : $(name) : $(sources) : $(library) : $(only) + : $(requirements) $(.handler) ; +}