diff --git a/CODING-GUIDELINES.md b/CODING-GUIDELINES.md index be764ee..92fa571 100644 --- a/CODING-GUIDELINES.md +++ b/CODING-GUIDELINES.md @@ -7044,10 +7044,13 @@ and not built is in chapter 17. constant time on Apple silicon; a program does nothing. The guard's cost is measured from a release build by `bench/collect.py --timing` and published beside the throughput, and the constant-time lane sets no DIT of its own: it - measures what a program gets. + measures what a program gets. webcpp::hash's keyed functions hold hash's own + copy of the guard, a change to either copy is a change to both, and + `test/timing_hash_interop_test.cpp` runs the two together (chapter 17, hash). Source: `libraries/crypto/openspec/changes/data-independent-timing/design.md` D1 to D7 (proposals); `include/webcpp/crypto/detail/timing.hpp`, - `test/timing_coverage__test.cpp` (libs/crypto). + `test/timing_coverage__test.cpp`, + `test/timing_hash_interop_test.cpp` (libs/crypto). - **`` is reached only through `detail/windows.hpp`, which defines `NOMINMAX` and `WIN32_LEAN_AND_MEAN` only when absent and undefines only what it defined, and every header writes `(max)()`, `(min)()` and @@ -9492,6 +9495,35 @@ and G4); the proposal, with the specification, the design and the plan, is in link's (`.gc`), each defined once. Source: `libraries/hash/openspec/changes/genesis/reference/spec.md` section 5 (proposals). +- **Every function that computes on a key, a password or a key derivation's + secret input holds `detail::timing_guard` as its first statement, on every + backend: `mac`, the key derivations, the password hashes (`bcrypt_verify` + included), and the keyed modes of BLAKE2b (`digest_of` and `hasher` when the + options carry a key) and of the `blake3` class, which construct it with + whether the call is keyed (a disengaged guard does nothing). Unkeyed digests + and Boost.Hash2's types by alias (`hmac`, the `hmac_*` aliases, + `siphash_32`, `siphash_64`) hold none, and the asynchronous family's + initiating functions hold none: the synchronous function they call holds it + on the thread that computes.** A digest's input is not a secret by its + contract, a guard per `update` would cost every checksum for no secret, and + the same algorithm is also Boost.Hash2's type by alias, which hash cannot + guard (design D2); a guard inside an alias would need a wrapper type in + place of Boost.Hash2's own (design D3), so the documentation names + `mac>` instead. A coverage test per backend + (`test/timing_coverage__test.cpp`) reads `doc/capabilities.json` + and fails when a keyed cell has no call, when a call's first guard is not + its own function's, or when an unkeyed function enters one: a new keyed + function or cell holds the guard and gets its call. The guard is a copy of + webcpp::crypto's (`include/webcpp/hash/detail/timing.hpp`; crypto depends on + hash, so hash cannot include crypto's), with the engaged flag added; a change + to either copy is made to both, and crypto's + `test/timing_hash_interop_test.cpp` runs the two nested in either order. Its + cost is measured from a release build by `bench/collect.py --timing` and + published in `doc/performance.adoc`. + Source: `libraries/hash/openspec/changes/data-independent-timing/design.md` + D1 to D9 (proposals); `include/webcpp/hash/detail/timing.hpp`, + `test/timing_coverage__test.cpp` (libs/hash); + `test/timing_hash_interop_test.cpp` (libs/crypto). - **Seven increments, each usable alone.** The first, built, is Hash2 by alias, `keccak_256`, `blake3`, HKDF, PBKDF2, Argon2id, scrypt, the default backend and the measured table; the second, built, is the families and libsodium's diff --git a/libs/crypto b/libs/crypto index 171e091..185c1e0 160000 --- a/libs/crypto +++ b/libs/crypto @@ -1 +1 @@ -Subproject commit 171e091829b45102498e86bb26d6c04ae71cd9c5 +Subproject commit 185c1e049be95acbcef29cbac0c1d19989659ffe diff --git a/libs/hash b/libs/hash index 24f2d63..3af42a2 160000 --- a/libs/hash +++ b/libs/hash @@ -1 +1 @@ -Subproject commit 24f2d63a5c0473e5360cb5fcc524f1f2e7d39d28 +Subproject commit 3af42a2a9abb617524d7c38e0c53beaa46ff3b66 diff --git a/tools/hash/doc_tables.py b/tools/hash/doc_tables.py index 6cdd2c5..c41618a 100644 --- a/tools/hash/doc_tables.py +++ b/tools/hash/doc_tables.py @@ -33,7 +33,9 @@ - generated/measured.adoc: the includes of the data chapters, backends.adoc and measurements.adoc (this tool), performance.adoc (bench/collect.py) and allocation.adoc (bench/allocation_collect.py), each one that is there; -- backends.adoc: the capability table as the guide's data chapter shows it; +- backends.adoc: the capability table as the guide's data chapter shows it, with which functions + set DIT around their calls and which do not (design D1 to D6 of the change + data-independent-timing), from the table's chapters and kinds; - measurements.adoc: measurements.json's tables, labelled as the dated reference they are; - llms.txt: the guide's index for language models, installed beside the page. @@ -88,6 +90,28 @@ # function's default is of the same order (design D33). FAMILY_KINDS = ('digest', 'mac', 'kdf') FAMILY_DEFAULTS = ('hash2', 'xkcp', 'blake3', 'sodium') +# The chapters whose functions compute on a key, a password or a secret input, and so set DIT +# around each call: every row of them but a type, which is Boost.Hash2's by alias (the change +# data-independent-timing, design D1 and D3). The coverage tests read the same rule from the table. +KEYED_CHAPTERS = {'macs': 'MACs', 'kdfs': 'Key derivation', 'password_hashing': 'Password hashing'} +# How a call names a row of each kind: a tag through its family's template, a function by its +# name. +CALLED_AS = {'mac': 'mac<{}>', 'kdf': 'argon2<{}>', 'digest': 'digest_of<{}>'} +# The functions a keyed row's cell also holds, which the table lists under that row: bcrypt's +# verification, always keyed, listed after bcrypt. +ALSO_KEYED = {'bcrypt': 'bcrypt_verify'} +# The keyed calls of a row the keyed chapters do not hold, each with the row it is a call of: the +# keyed modes of a digest (design D1), keyed by their arguments (D4). +KEYED_CALLS = ( + ('digests::blake2b', '`digest_of` and `hasher` (`make`, ' + '`update`, `finish`) when the options carry a key'), + ('blake3', 'the `blake3` class in its keyed, key-derivation and seeded keyed modes (a ' + 'non-empty byte seed, a non-zero integer seed: BLAKE3\'s keyed hash): `keyed`, `derive_key`, ' + 'those constructors, and `update`, `result`, `squeeze` and `reset` of such an object'), +) +APPLE_DIT = ('https://developer.apple.com/documentation/xcode/' + 'writing-arm64-code-for-apple-platforms' + '#Enable-DIT-for-constant-time-cryptographic-operations') # The chapter each namespace's tags belong in: a tag of macs is listed with the MACs. NAMESPACE_CHAPTERS = {'digests::': 'digests', 'macs::': 'macs'} # The templates a family's tag is the first template argument of, by its kind, each declared in @@ -653,6 +677,12 @@ def llms_txt(data: Data) -> str: 'Primitives only: protocol steps (BIP39, hash160, EIP-55, Nostr ids, NIP-44) ' 'are what a domain library builds from these functions; the guide shows them as ' 'examples, never as this library\'s API.', '', + 'Timing: every MAC, key derivation and password hash, and BLAKE2b\'s and BLAKE3\'s ' + 'keyed modes, set DIT (data-independent timing) around each call on 64-bit ARM under ' + 'Apple\'s systems and Linux where the CPU has FEAT_DIT, on every synchronous backend, ' + 'and leave the thread\'s DIT as they found it; ' + 'unkeyed digests and Boost.Hash2\'s hmac by alias do not, so an HMAC with DIT is ' + f'mac>. [Section]({page}#hash-backends-dit)', '', f'- [The guide]({page}): every chapter, example and table', f'- [Choose by use case]({page}#hash-choose): a decision table, need to ' 'function, backend and example', ''] @@ -694,6 +724,95 @@ def llms_txt(data: Data) -> str: return '\n'.join(lines) +def keyed_rows(data: Data) -> tuple[dict[str, list[str]], list[str]]: + """The rows that set DIT, by chapter, each as a call names it (a tag through its family), and + the types of the keyed chapters that do not (the aliases), in the table's order.""" + keyed: dict[str, list[str]] = {} + aliases: list[str] = [] + for algorithm in data.capabilities['algorithms']: + if algorithm['chapter'] not in KEYED_CHAPTERS: + continue + for function in algorithm['functions']: + if function['kind'] == 'type': + aliases.append(function['name']) + else: + called = CALLED_AS.get(function['kind'], '{}').format(function['name']) + keyed.setdefault(algorithm['chapter'], []).append(called) + if function['name'] in ALSO_KEYED: + keyed[algorithm['chapter']].append(ALSO_KEYED[function['name']]) + return keyed, aliases + + +def dit_section(data: Data) -> list[str]: + """Which functions set DIT around their calls and which do not, and why: the keyed chapters' + rows from the table, the keyed calls of other rows, and the rest.""" + keyed, aliases = keyed_rows(data) + lines = [ + '[#hash-backends-dit]', '=== Data-independent timing (DIT)', '', + '64-bit ARM\'s DIT (data-independent timing) bit, PSTATE.DIT, makes the instructions Arm ' + 'lists take a time independent of their data, and Apple requires it of constant-time code ' + f'({link("Apple, enable DIT for constant-time cryptographic operations", APPLE_DIT)}). ' + 'None of the libraries hash calls sets it, so hash does: every function that computes ' + 'on a key, a password or a key derivation\'s secret input runs its whole body inside ' + '`detail::timing_guard`, on every synchronous backend, which on 64-bit ARM under ' + 'macOS, iOS, Linux and Android, where the CPU has FEAT_DIT (`hw.optional.arm.FEAT_DIT` ' + 'on Apple\'s systems, `HWCAP_DIT` on Linux), sets DIT for the call and returns with ' + 'the thread\'s DIT as it found it: clear when it was clear, set when the program set ' + 'it itself (Apple\'s `timingsafe_enable_if_supported`) or an outer call did. An error ' + 'and an exception leave it as found too, and DIT is a thread\'s own state, so a call ' + 'never changes another thread\'s. A program does nothing. Elsewhere the guard executes ' + 'no instruction: on x86 the counterpart, DOITM, is a register only the kernel writes; ' + 'on WebAssembly the engine decides; on Windows on ARM64 no documented way to ask ' + 'whether the CPU has FEAT_DIT was found, and DIT\'s instructions trap on a CPU without ' + 'it.', '', + 'The functions that set DIT, on every synchronous backend of their cells:', ''] + for chapter, names in keyed.items(): + lines.append(f'* {KEYED_CHAPTERS[chapter]}: {listed([f"`{name}`" for name in names])}.') + calls = [text for row, text in KEYED_CALLS if row in data.functions] + if calls: + lines.append('* Keyed by their arguments: ' + '; '.join(calls) + '. Called without a ' + 'key, they hold a disengaged guard, which reads its flag and does nothing ' + 'else.') + lines += [ + '', 'The functions that do not:', '', + '* Unkeyed digests and extendable-output functions, through `digest_of`, `hasher` and ' + 'the types of Boost.Hash2\'s form (`keccak_256`, `blake3` in its plain mode): their input ' + 'is not a secret by their contract (a program that derives from a secret uses a MAC or a ' + 'key derivation, which set DIT); they are the streaming case, where a guard per `update` ' + 'of every checksum would cost a real fraction of a short chunk for no secret; and the ' + 'same algorithm is also Boost.Hash2\'s own type by alias, which hash cannot guard, so ' + 'that guarding one spelling would make the protection depend on the spelling.'] + if aliases: + lines.append( + '* Boost.Hash2\'s types by alias, ' + listed([f'`{name}`' for name in aliases]) + + ': they are Boost.Hash2\'s own classes, and a guard inside them would need a type of ' + 'hash\'s in place of the alias. An HMAC with DIT is `mac>`, which runs ' + 'the same Boost.Hash2 code on `backends::hash2` inside its guard, and a SipHash with ' + 'DIT is `mac`; a program that calls `hmac` or `siphash_64` ' + 'directly sets DIT itself. HKDF and PBKDF2 on `backends::hash2` run ' + 'Boost.Hash2\'s `hmac` inside their own guard.') + lines += [ + '* The initiating functions of `async.hpp`: they check sizes and post, and the ' + 'synchronous function they call sets DIT on the thread that computes, a thread of the ' + 'work executor\'s pool for a heavy function, the caller\'s for a cheap one ' + '(<>). On `backends::webcrypto` the browser\'s JavaScript engine computes, ' + 'and nothing is added.', '', + 'A coverage test per backend (`test/timing_coverage__test.cpp`) reads this ' + 'table and fails when a keyed cell of its backend has no call, when a call enters no ' + 'guard, when the first guard it enters is not its own function\'s, or when it leaves DIT ' + 'otherwise than it found it, from a thread with DIT clear and from one that set it; it ' + 'checks that the unkeyed functions enter none. `test/timing_during_test.cpp` reads DIT ' + 'while HKDF, PBKDF2 and `mac` compute, through a hash that records it at each update, ' + 'on the calling thread and on an `async_pbkdf2` pool\'s. The guard ' + 'is hash\'s own copy of ' + 'webcpp::crypto\'s, which depends on hash: a change to one is a change to the other, and ' + 'crypto\'s test `timing_hash_interop_test` runs both nested, in either order.', ''] + if (data.library / 'doc' / 'performance.adoc').is_file(): + lines += ['What the guard adds to a call, measured from a release build, is in ' + '<>.', ''] + return lines + + def chapter_header(title: str, anchor: str, sources: str) -> list[str]: return [generated_header(sources), f'[#{anchor}]', f'== {title}', ''] @@ -737,6 +856,7 @@ def backends_chapter(data: Data) -> str: f'| {hmacs}', f'| {c["constant_time"]["value"]}', f'| {targets}'] lines += ['|===', ''] + lines += dit_section(data) lines += ['=== The default backends', '', 'The backend a call that names none uses, on every target, whatever the program ' 'links (<>):', '', diff --git a/tools/test/hash_collect_test.py b/tools/test/hash_collect_test.py index 326437b..59eadaa 100644 --- a/tools/test/hash_collect_test.py +++ b/tools/test/hash_collect_test.py @@ -5,15 +5,23 @@ # accompanying file LICENSE_1_0.txt or copy at # https://www.boost.org/LICENSE_1_0.txt) -"""Checks that libs/hash/bench/collect.py, which measures bench/pbkdf2_sha512 and renders -doc/performance.adoc, builds its table only from release builds: a program whose build directory, -b2's bench///..., names another variant, or does not say, is refused before -anything runs or is written; one at variant=release is taken (it gets as far as running); and -`--render-only` refuses data whose build is not variant=release, before it writes the page. Run -with the names of some cases to run only those.""" +"""Checks that libs/hash/bench/collect.py, which measures bench/pbkdf2_sha512 and bench/timing and +renders doc/performance.adoc, builds its page only from release builds: a program whose build +directory, b2's bench///..., names another variant, or does not say, is refused +before anything runs or is written, the guard's `--timing` program as the throughput's; one at +variant=release is taken (it gets as far as running); `--timing` alone stores the guard's cost +beside the data's throughput, which it keeps, with UTC's date, and the page renders it; `--exe` +alone keeps the data's guard, and replaces data it cannot keep, saying so, with UTC's date; +`--provisional` marks the guard's figures and the page says so, a measurement without it clears the +mark, and it is refused without `--timing`; `--timing` without data, a timing line that is not the +form collect.py reads and a "timing_guard" that is not the form it writes are refused with a +message, not a traceback, before anything is written; and `--render-only` refuses data whose build, +or whose guard's build, is not variant=release, before it writes the page, and renders the committed +data as the committed page. Run with the names of some cases to run only those.""" from __future__ import annotations +import datetime import json import subprocess import sys @@ -23,6 +31,10 @@ ROOT = Path(__file__).resolve().parents[2] COLLECT = ROOT / 'libs/hash/bench/collect.py' +DATA = ROOT / 'libs/hash/doc/measurements.throughput.json' +PAGE = ROOT / 'libs/hash/doc/performance.adoc' +# A stand-in's body that fails when run, after saying so. +FAILS = 'echo "the stand-in ran" >&2\nexit 3\n' def run(*args: str | Path) -> subprocess.CompletedProcess[str]: @@ -30,12 +42,14 @@ def run(*args: str | Path) -> subprocess.CompletedProcess[str]: capture_output=True, text=True, check=False, timeout=120) -def program(scratch: Path, variant: str) -> Path: - """A stand-in of bench/pbkdf2_sha512 where b2 builds it at variant, which fails when run.""" +def program(scratch: Path, variant: str, body: str = FAILS, + name: str = 'pbkdf2_sha512') -> Path: + """A stand-in of bench/ where b2 builds it at variant, which runs body (by default, it + fails).""" path = (scratch / 'bin/libs/hash/bench/clang-darwin-21' / variant - / 'cxxstd-20-iso/optimization-speed/pbkdf2_sha512') + / 'cxxstd-20-iso/optimization-speed' / name) path.parent.mkdir(parents=True) - path.write_text('#!/bin/sh\necho "the stand-in ran" >&2\nexit 3\n') + path.write_text('#!/bin/sh\n' + body) path.chmod(0o755) return path @@ -72,11 +86,165 @@ def test_a_program_built_at_variant_release_is_measured(scratch: Path) -> None: expect(done, 1, 'native: --list exit 3', 'the stand-in ran') +def test_a_timing_program_not_built_at_variant_release_is_refused(scratch: Path) -> None: + data, page = scratch / 'data.json', scratch / 'page.adoc' + data.write_text(DATA.read_text()) + for variant in ('debug', 'profile'): + exe = program(scratch / variant, variant, FAILS, 'timing') + done = run('--timing', exe, '--data', data, '--page', page) + expect(done, 1, f'timing={exe} was built at variant={variant}', + 'only from release builds') + if 'the stand-in ran' in done.stderr or page.exists(): + raise AssertionError(f'{variant}: the program ran or the page was written') + if data.read_text() != DATA.read_text(): + raise AssertionError(f'{variant}: the data was rewritten') + + +GUARD = {'dit': True, 'clear': 12.345, 'set': 0.678, 'disengaged': -0.04, + 'clear_fastest': 11.25, 'clear_slowest': 19.75, 'set_fastest': 0.25, 'set_slowest': 1.75, + 'disengaged_fastest': -0.25, 'disengaged_slowest': 0.375, 'iterations': 10000000, + 'runs': 5, 'target': 'native', 'compiler': 'clang'} + + +def timing_program(scratch: Path, line: str = json.dumps(GUARD)) -> Path: + """A stand-in of bench/timing at variant=release whose --measure prints line.""" + return program(scratch, 'release', 'if [ "$1" = --measure ]; then ' + f"echo '{line}'; else exit 3; fi\n", 'timing') + + +def test_the_guard_is_measured_kept_beside_the_throughput_and_rendered(scratch: Path) -> None: + data, page = scratch / 'data.json', scratch / 'page.adoc' + committed = json.loads(DATA.read_text()) + data.write_text(json.dumps(committed)) + before = datetime.datetime.now(datetime.timezone.utc).date().isoformat() + expect(run('--timing', timing_program(scratch), '--data', data, '--page', page), 0) + written = json.loads(data.read_text()) + guard = written['timing_guard'] + stored = {key: guard[f'{key}_ns'] for key in GUARD if isinstance(GUARD[key], float)} + if stored != {key: value for key, value in GUARD.items() if isinstance(value, float)} or \ + guard['dit'] is not True or guard['build'] != committed['build'] or \ + guard['provisional'] is not False: + raise AssertionError(f'the guard was not stored as measured: {guard}') + utc = {datetime.datetime.now(datetime.timezone.utc).date().isoformat(), before} + if guard['date'] not in utc: + raise AssertionError(f"the guard's date {guard['date']} is not UTC's {utc}") + if {key: value for key, value in written.items() if key != 'timing_guard'} != \ + {key: value for key, value in committed.items() if key != 'timing_guard'}: + raise AssertionError('the throughput was not kept') + text = page.read_text() + if 'provisional' in text: + raise AssertionError(f'the page says provisional without --provisional:\n{text}') + for expected in ('[#hash-performance-timing]', '<>', '| 12.3', '| 11.2', + '| 19.8', '| 0.7', '| 0.2', '| 1.8', '| 0.0', '| 0.4', + 'The guard sets DIT on this machine', '10,000,000 guards'): + if expected not in text: + raise AssertionError(f'{expected!r} is not on the page:\n{text}') + if text.index('[#hash-performance-pbkdf2]') > text.index('[#hash-performance-timing]'): + raise AssertionError('the guard is not rendered after the throughput') + + +def throughput_program(scratch: Path) -> Path: + """A stand-in of bench/pbkdf2_sha512 at variant=release with one variant, hash2, whose key is + right.""" + line = json.dumps({'key_correct': True, 'median_ms': 900.0, 'runs_ms': [899.0, 901.0], + 'compiler': 'clang', 'iterations': 1000000}) + return program(scratch, 'release', 'if [ "$1" = --list ]; then echo hash2; ' + f"else echo '{line}'; fi\n") + + +def test_the_throughput_alone_keeps_the_guard_or_replaces_bad_data(scratch: Path) -> None: + data, page = scratch / 'data.json', scratch / 'page.adoc' + committed = json.loads(DATA.read_text()) + data.write_text(json.dumps(committed)) + exe = throughput_program(scratch) + utc = {datetime.datetime.now(datetime.timezone.utc).date().isoformat()} + expect(run('--exe', f'native={exe}', '--invocations', '1', '--data', data, '--page', page), 0) + written = json.loads(data.read_text()) + if written['timing_guard'] != committed['timing_guard']: + raise AssertionError("a measurement of the throughput alone did not keep the guard") + utc.add(datetime.datetime.now(datetime.timezone.utc).date().isoformat()) + if written['date'] not in utc or [c['median_ms'] for c in written['cases']] != [900.0]: + raise AssertionError(f'the throughput was not stored as measured, with UTC\'s date: ' + f'{written["date"]}, {written["cases"]}') + # Data it cannot keep, of another build or not JSON, is replaced, and the message says so. + for bad in (json.dumps({**committed, 'build': 'variant=debug'}), 'not json'): + data.write_text(bad) + done = run('--exe', f'native={exe}', '--invocations', '1', '--data', data, '--page', + page) + expect(done, 0, 'the guard is not kept') + if 'timing_guard' in json.loads(data.read_text()) or 'Traceback' in done.stderr: + raise AssertionError(f'bad data was not replaced cleanly:\n{done.stderr}') + + +def test_provisional_marks_the_guard_and_a_measurement_without_it_clears_it( + scratch: Path) -> None: + data, page = scratch / 'data.json', scratch / 'page.adoc' + data.write_text(DATA.read_text()) + exe = timing_program(scratch) + expect(run('--timing', exe, '--provisional', '--data', data, '--page', page), 0) + if json.loads(data.read_text())['timing_guard']['provisional'] is not True: + raise AssertionError('--provisional did not mark the guard') + text = page.read_text() + if text.count('NOTE: these figures are provisional') != 1 or \ + text.index('NOTE: these figures are provisional') < \ + text.index('[#hash-performance-timing]'): + raise AssertionError(f'the page does not mark the guard alone:\n{text}') + expect(run('--timing', exe, '--data', data, '--page', page), 0) + if json.loads(data.read_text())['timing_guard']['provisional'] is not False or \ + 'provisional' in page.read_text(): + raise AssertionError('a measurement without --provisional kept the mark') + before = data.read_text() + done = run('--render-only', '--provisional', '--data', data, '--page', scratch / 'other.adoc') + expect(done, 1, '--provisional marks the guard\'s figures: give it with --timing') + if data.read_text() != before or (scratch / 'other.adoc').exists(): + raise AssertionError('--provisional without --timing wrote a file') + + +def test_timing_alone_without_data_is_refused_with_a_message(scratch: Path) -> None: + exe = program(scratch, 'release', FAILS, 'timing') + data, page = scratch / 'missing.json', scratch / 'page.adoc' + done = run('--timing', exe, '--data', data, '--page', page) + expect(done, 1, f'collect.py: {data} does not exist') + if 'Traceback' in done.stderr or 'the stand-in ran' in done.stderr: + raise AssertionError(f'a traceback, or the program ran:\n{done.stderr}') + if data.exists() or page.exists(): + raise AssertionError('a file was written') + + +def test_a_timing_line_or_guard_of_another_form_is_refused_with_a_message(scratch: Path) -> None: + data, page = scratch / 'data.json', scratch / 'page.adoc' + lines = { + 'not json': 'line (not JSON)', + json.dumps({key: value for key, value in GUARD.items() if key != 'disengaged'}): + 'line.disengaged (missing)', + json.dumps({**GUARD, 'clear': 'fast'}): 'line.clear', + json.dumps({**GUARD, 'dit': 1}): 'line.dit', + } + for index, (line, named) in enumerate(lines.items()): + data.write_text(DATA.read_text()) + done = run('--timing', timing_program(scratch / str(index), line), '--data', data, + '--page', page) + expect(done, 1, 'not the form collect.py reads', named) + if 'Traceback' in done.stderr or page.exists() or data.read_text() != DATA.read_text(): + raise AssertionError(f'{line}: a traceback, or a file was written:\n{done.stderr}') + committed = json.loads(DATA.read_text()) + for change, named in ((lambda g: g.pop('set_ns'), 'data.timing_guard.set_ns (missing)'), + (lambda g: g.update(dit='yes'), 'data.timing_guard.dit'), + (lambda g: g.update(provisional=None), 'data.timing_guard.provisional')): + broken = json.loads(json.dumps(committed)) + change(broken['timing_guard']) + data.write_text(json.dumps(broken)) + done = run('--render-only', '--data', data, '--page', page) + expect(done, 1, 'not the data collect.py writes', named) + if 'Traceback' in done.stderr or page.exists(): + raise AssertionError(f'{named}: a traceback, or the page was written:\n{done.stderr}') + + def test_render_only_refuses_data_not_built_at_variant_release(scratch: Path) -> None: - committed = json.loads((ROOT / 'libs/hash/doc/measurements.throughput.json').read_text()) + committed = json.loads(DATA.read_text()) page = scratch / 'page.adoc' for build in ('variant=debug optimization=speed', None): - data = dict(committed) + data = json.loads(json.dumps(committed)) if build is None: del data['build'] else: @@ -87,16 +255,30 @@ def test_render_only_refuses_data_not_built_at_variant_release(scratch: Path) -> expect(done, 1, 'only from release builds') if page.exists(): raise AssertionError(f'{build}: the page was written') + data = json.loads(json.dumps(committed)) + data['timing_guard']['build'] = 'variant=debug' path = scratch / 'data.json' + path.write_text(json.dumps(data)) + done = run('--render-only', '--data', path, '--page', page) + expect(done, 1, "timing guard was measured with build variant=debug", + 'only from release builds') + if page.exists(): + raise AssertionError("the guard's debug build: the page was written") path.write_text(json.dumps(committed)) expect(run('--render-only', '--data', path, '--page', page), 0) - if page.read_text() != (ROOT / 'libs/hash/doc/performance.adoc').read_text(): + if page.read_text() != PAGE.read_text(): raise AssertionError('the committed data does not render the committed page') CASES: list[Callable[[Path], None]] = [ test_a_program_not_built_at_variant_release_is_refused, test_a_program_built_at_variant_release_is_measured, + test_a_timing_program_not_built_at_variant_release_is_refused, + test_the_throughput_alone_keeps_the_guard_or_replaces_bad_data, + test_the_guard_is_measured_kept_beside_the_throughput_and_rendered, + test_provisional_marks_the_guard_and_a_measurement_without_it_clears_it, + test_timing_alone_without_data_is_refused_with_a_message, + test_a_timing_line_or_guard_of_another_form_is_refused_with_a_message, test_render_only_refuses_data_not_built_at_variant_release, ] diff --git a/tools/test/hash_doc_tables_test.py b/tools/test/hash_doc_tables_test.py index cdbe686..46ab5f1 100644 --- a/tools/test/hash_doc_tables_test.py +++ b/tools/test/hash_doc_tables_test.py @@ -21,7 +21,11 @@ sits in its namespace's chapter. A backend of the asynchronous family alone (backends::webcrypto) is named so in every table, with its targets as the guide spells them, and is never a default; a row of an unknown kind fails. Each backend's constant-time statements are one bullet. llms.txt's -defaults are the capability table's, not a text written once. +defaults are the capability table's, not a text written once. The data chapter's section on DIT +lists every row of the keyed chapters (MACs, key derivation, password hashing) but a type, as a +call names it, among the functions that set DIT, and their types among Boost.Hash2's aliases that +do not, so that a row the table gains is said; it names the guard's measured cost only where +performance.adoc is, and llms.txt points to it. Without doc/measurements.json the tables say so, carry no measured column and render no measurements.adoc; with it (a fixture in its shape) they carry the throughput and the size, and measurements.adoc renders it as the dated reference that decides nothing; a hand edit of the @@ -512,6 +516,51 @@ def test_each_backend_s_constant_time_sources_are_together(scratch: Path) -> Non expect(len(bullets) == len(set(bullets)), f'{name}: {bullets}') +def test_the_dit_section_follows_the_table(scratch: Path) -> None: + library = scratch_library(scratch) + files = write_ok(library) + chapter = files['backends.adoc'] + section = chapter.split('[#hash-backends-dit]')[1].split('=== The default backends')[0] + sets, rest = section.split('The functions that do not:') + for named in ('`mac>`', '`mac`', '`hkdf`', + '`blake2b_subkey`', '`x963kdf`', '`argon2`', '`bcrypt_pbkdf`', + '`digest_of`', 'the `blake3` class', '`bcrypt_verify`'): + expect(named in sets, f'{named} is not among the functions that set DIT:\n{sets}') + # bcrypt_verify always holds an engaged guard: it is a password function, never one keyed by + # its arguments, whose unkeyed calls hold a disengaged guard. + password = next(line for line in sets.splitlines() if line.startswith('* Password hashing:')) + by_arguments = next(line for line in sets.splitlines() + if line.startswith('* Keyed by their arguments:')) + expect('`bcrypt`, `bcrypt_verify`' in password, f'bcrypt_verify is not after bcrypt:\n{sets}') + expect('bcrypt_verify' not in by_arguments, f'bcrypt_verify is said disengaged:\n{sets}') + for named in ('`hmac_sha2_256`', '`siphash_64`', '`hmac`,'): + expect(named in rest and named not in sets, f'{named} is not among the aliases:\n{rest}') + expect('`mac>`' in rest, 'the aliases do not name the guarded call') + expect('`mac`' in rest, 'the SipHash aliases do not name the guarded call') + expect('<>' not in section, 'the cost named without its chapter') + expect('#hash-backends-dit)' in files['llms.txt'], 'llms.txt does not point to the section') + # A row the table gains in a keyed chapter is said: a function among those that set DIT, a + # type among the aliases; and the measured cost is named once its chapter is there. + table = json.loads((library / 'doc/capabilities.json').read_text(encoding='utf-8')) + macs = next(a for a in table['algorithms'] if a['chapter'] == 'macs') + tag = next(f for f in macs['functions'] if f['kind'] == 'mac') + alias = next(f for f in macs['functions'] if f['kind'] == 'type') + macs['functions'] += [{**tag, 'name': 'macs::fixture_mac'}, {**alias, 'name': 'fixture_alias'}] + (library / 'doc/capabilities.json').write_text(json.dumps(table), encoding='utf-8') + guide = json.loads((library / 'doc/guide.json').read_text(encoding='utf-8')) + guide['functions']['macs::fixture_mac'] = guide['functions'][tag['name']] + guide['functions']['fixture_alias'] = guide['functions'][alias['name']] + (library / 'doc/guide.json').write_text(json.dumps(guide), encoding='utf-8') + (library / 'doc/performance.adoc').write_text('x\n', encoding='utf-8') + section = write_ok(library)['backends.adoc'].split('[#hash-backends-dit]')[1] + sets, rest = section.split('The functions that do not:') + expect('`mac`' in sets, f'a new MAC is not said:\n{sets}') + expect('`fixture_alias`' in rest.split('=== The default backends')[0], + f'a new alias is not said:\n{rest}') + expect('<>' in rest.split('=== The default backends')[0], + 'the measured cost is not named') + + def test_an_asynchronous_backend_is_said(scratch: Path) -> None: # backends::webcrypto serves the asynchronous family alone (its "asynchronous_only" field): # every table names it with that note, and a synchronous call never names it. @@ -692,6 +741,7 @@ def test_the_real_library_s_files_are_its_data_s(scratch: Path) -> None: test_a_function_without_a_backend_of_the_order_has_no_default, test_a_function_s_default_is_of_the_order, test_each_backend_s_constant_time_sources_are_together, + test_the_dit_section_follows_the_table, test_an_asynchronous_backend_is_said, test_an_exceptions_only_backend_is_said, test_without_measurements_the_tables_say_so,