From 5c7fd4aa0a7e233540674a1a7981d055c30b1cfc Mon Sep 17 00:00:00 2001 From: R Date: Mon, 30 Nov 2026 19:49:10 -0300 Subject: [PATCH 01/10] codecs: over-in-place, over decodes a value in place under the inner value codec's decode bound (design, spec, tasks, plan) --- .../changes/over-in-place/.openspec.yaml | 11 + .../openspec/changes/over-in-place/design.md | 326 +++++++++++ .../changes/over-in-place/proposal.md | 80 +++ .../changes/over-in-place/reference/plan.md | 548 ++++++++++++++++++ .../over-in-place/specs/codecs/spec.md | 63 ++ .../openspec/changes/over-in-place/tasks.md | 24 + 6 files changed, 1052 insertions(+) create mode 100644 libraries/codecs/openspec/changes/over-in-place/.openspec.yaml create mode 100644 libraries/codecs/openspec/changes/over-in-place/design.md create mode 100644 libraries/codecs/openspec/changes/over-in-place/proposal.md create mode 100644 libraries/codecs/openspec/changes/over-in-place/reference/plan.md create mode 100644 libraries/codecs/openspec/changes/over-in-place/specs/codecs/spec.md create mode 100644 libraries/codecs/openspec/changes/over-in-place/tasks.md diff --git a/libraries/codecs/openspec/changes/over-in-place/.openspec.yaml b/libraries/codecs/openspec/changes/over-in-place/.openspec.yaml new file mode 100644 index 0000000..4056436 --- /dev/null +++ b/libraries/codecs/openspec/changes/over-in-place/.openspec.yaml @@ -0,0 +1,11 @@ +schema: spec-driven +created: 2026-11-30 +webcpp: + library: codecs + title: "codecs: over decodes a value in place under the inner value codec's decode bound" + kind: own + port_of: null + status: accepted + release: null + implementation: null + decided: 2026-11-30 diff --git a/libraries/codecs/openspec/changes/over-in-place/design.md b/libraries/codecs/openspec/changes/over-in-place/design.md new file mode 100644 index 0000000..24fb7ad --- /dev/null +++ b/libraries/codecs/openspec/changes/over-in-place/design.md @@ -0,0 +1,326 @@ +## Open questions for the owner + +Two choices change the public contract and nothing decided so far answers them. The plan is +written with the recommendation of each; the places that change with the answer are marked +"(Q1)" or "(Q2)" in the plan. + +1. **Q1. The error of a payload past the decode bound.** The intermediate of `over` cannot hold + more than the inner value codec's decode bound, so a text whose payload is longer is refused + by codecs before the inner value codec sees a byte; codecs must name that error. + - **A (recommended): `codecs::error::input_too_long`, in `over` alone.** It is what `over` + already returns for an intermediate past a bound known at compile time (over.hpp's + `past_bound`, for a text of a static size), and the error's own message, "the input is + longer than the format or the buffer allows". The direct `decode(format, bytes)` + still hands every input to the value codec. Cost: crypto's PEM of a payload past the bound + becomes `codecs::error::input_too_long` where crypto's `formats` spec says + `invalid_encoding`; crypto's `pem-forward` changes that sentence and its tests (an RSA + public key's PEM under `PUBLIC KEY`, the toy's 17 bytes), and the DER formats keep their + errors. + - **B: `input_too_long`, enforced by the core in every decode of a value codec that states a + bound,** the direct one too. One rule everywhere; but crypto's DER errors change as well (a + P-256 PKCS#8 of 150 bytes, refused today with `invalid_encoding` by crypto's spec, would be + `input_too_long`), a larger churn in crypto for no gain in `over`. + - **C: the value codec names its refusal**, an optional + `static constexpr` error enumerator `decode_input_too_long` (any enumeration that is a + `boost::system` error code enumeration), `input_too_long` when absent; crypto states its + `invalid_encoding`, and its errors do not change at all. Cost: one more optional member in + the contract, for one error. +2. **Q2. The cap on the in-place intermediate of a decode bound.** The genesis puts an + intermediate of a static bound in place with no cap (its R3): the caller chose a static input + and can pass a view of a dynamic extent to reach the heap. A decode bound is the format + author's, and the caller has no such escape; a value codec of a certificate or of a JSON + document may state tens of kilobytes, and Emscripten's default stack is 64 KiB. + - **A (recommended): in place when the bound is at most 4096 bytes, on the heap above it**, + the bound still checked before the allocation. 4096 is the owner's own threshold of + 2026-11-26 for `assign_to`'s scratch (`detail::in_place_scratch_limit`), reused, not a new + number. Every crypto bound (at most 138 today, 83 for PKCS#8 v2) is far below it. + - **B: no cap**, as the genesis' R3: simpler to state, but a large bound costs every caller its + stack, with no way out. + +## Context + +This change builds on webcpp::codecs as merged (codecs#1, `80d90d0`, its genesis +`libraries/codecs/openspec/changes/genesis/`, owner decisions 1 to 27 and the rulings of its +implementation) and on crypto's `formats` change as merged (`libraries/crypto/openspec/changes/formats/`), +which runs right before it. + +What codecs does today, in `include/webcpp/codecs/detail/core/over.hpp`: + +- `over` holds its intermediate in `in_place_intermediate` + (a `std::array` in the frame of each of its functions, its written bytes wiped by + `secure::erase_secret` when the chain is secret) when `Bound` is known at compile time, and in + `heap_intermediate` (a `std::vector` or a `basic_secret_byte_vector` of + `over`'s allocator) otherwise. +- For a decode, `Bound` is `decoded_bound>()`, the outer link's + `max_decoded_size` of the text's static size, or `std::dynamic_extent` for a `std::string_view`. + The value decode (`over_value_decode`) asks the outer link's exact `decoded_size` (which checks + the whole text, so the outer link's data errors come first), refuses a size past `Bound` with + `input_too_long`, makes the intermediate, decodes the outer link into it and gives the written + bytes to the inner value codec's `decode`. +- Its `noexcept` (genesis R3) follows the intermediate: `over_value_decode_is_noexcept` is false + whenever `Bound` is `std::dynamic_extent`, so the typed `decode` of such a chain is not + `noexcept`. +- A value codec states `output`, optionally `secret`, optionally `max_encoded_size` (which sizes + the encode's intermediate and the default result); it states nothing about the longest input + its decode takes. `SIZE_MAX` (`detail::size_maximum`, equal to `std::dynamic_extent`) is the + saturated bound that means "no size to hold in place". +- `detail::in_place_scratch_limit = 4096` (tokens.hpp) is the threshold the owner set on + 2026-11-26 for `assign_to`'s scratch: in place up to 4096 elements, the target's allocator + above. + +What crypto does after `formats` (its design R24, R37 and owner decision 23): each crypto value +codec that decodes states `max_decode_input_size` (crypto's `formats.hpp` checks it is there and, +today, that it equals `max_encoded_size`); `crypto::decode` of `pem(F)` calls +`detail::decode_pem`, which decodes the armor through codecs' buffer form into a +`std::array>`, maps `output_too_small` to +`crypto::error::invalid_encoding`, then calls `codecs::decode(format.inner, ...)` and wipes +the buffer of a secret pair; `codecs::decode` of the same format and text allocates, which crypto's +guide and tests state as "the documented difference". + +## Goals / Non-Goals + +**Goals:** `codecs::decode(over{outer, inner}, text)` of a text of a dynamic size, when the +inner value codec states a decode bound, holds its intermediate in place, allocates nothing and is +`noexcept` when the links' calls are; the inner value codec never receives more than its decode +bound from `over`; a secret intermediate is wiped on every path; crypto's PEM decode becomes a +forward to codecs with no heap. + +**Non-goals:** a decode bound on `codec` (a codec's `max_decoded_size(n)` already bounds a +decode from its input's size); a decode bound on `over`'s own value codec (R8); the encode side +of `over` (its intermediate is already in place under `max_encoded_size`, and its outer link's +encode fault after `prepare` stays as the genesis documents, R12); a stream form of a value +codec's `over` (decision 17 of the genesis: a value codec has no transformer); PKCS#8 v2, which +stays deferred (crypto's owner decision 23). + +**Anti-goals:** a heap allocation where the decode bound is known and small; a stack array sized +by a bound the caller cannot see or escape; a secret byte of the intermediate left unwiped; a +change of the errors a value codec returns to a direct decode. + +## Owner decisions (binding) + +28. **`over` decodes in place under the inner value codec's decode bound** (2026-11-30, crypto + `formats`' question Q1, approved): a small codecs change queued right after `formats` and + before `hpke`. The decode bound is the one owner decision 23 of crypto's `formats` gave every + crypto value codec, `max_decode_input_size`, the longest encoded input its decoder accepts + (48 for Ed25519's and X25519's `pkcs8`, 138 for P-256's, equal to `max_encoded_size` today), + never `max_encoded_size`, which bounds the encoder's output. An intermediate longer than the + bound is refused before it is written, as no inner decoder accepts it; codecs adopts crypto's + name for the member, after which crypto's two steps become a forward. + +The numbers 1 to 27 are the genesis'; this change continues them. + +## Decisions + +### D1. The decode bound in the value codec contract + +```cpp +template <> struct value_codec { + static constexpr codecs::output_kind output = codecs::output_kind::bytes; + static constexpr bool secret = true; + static constexpr std::size_t max_encoded_size = 138; // optional: the longest encoding encode writes + static constexpr std::size_t max_decode_input_size = 138; // optional: the longest input decode accepts + // encoded_size, encode, decode as the genesis' D4 +}; +``` + +`max_decode_input_size` is optional, a `static constexpr` value convertible to `std::size_t`, +counted in the elements `decode` reads: bytes for `output_kind::bytes`, characters for +`output_kind::text`. It promises that `decode` refuses every longer input. The core reads it +through a detail concept, `detail::has_decode_input_bound`, and +`detail::value_decode_bound()` (the bound, or `std::dynamic_extent` when absent); there is +no public reader, as there is none for `max_encoded_size` (R1). When a value codec states both +bounds, the core stops the build if `max_decode_input_size < max_encoded_size` (R2). + +### D2. Where the intermediate of a value decode lives + +`over_value_decode` sizes its intermediate by `detail::over_value_middle_bound()`, the smallest of the bounds known at compile time: + +| The text | The inner value codec | The intermediate | +| --- | --- | --- | +| static size `N` (genesis) | no decode bound | in place, `codec::max_decoded_size(N)` | +| static size `N` | decode bound `D` at most 4096 | in place, the smaller of the two | +| static size `N` | decode bound `D` above 4096 | in place, `codec::max_decoded_size(N)` (the genesis' rule for a static text, no cap) | +| dynamic | decode bound `D` at most 4096 | in place, `D` (this change) | +| dynamic | decode bound `D` above 4096 | heap, from `over`'s allocator, exactly the written size, at most `D` (Q2) | +| dynamic | no decode bound | heap, from `over`'s allocator (genesis, unchanged) | + +A bound of `SIZE_MAX` is above 4096 and never refuses anything: it is no bound, with no special +case. + +### D3. The refusal past the bound + +The order of a value decode through `over` becomes: + +1. the chain's configuration (the outer link's first), as the genesis; +2. the outer link's `decoded_size`, which checks the whole text and returns the outer link's data + error (outer before inner, the genesis' B23); +3. **new:** an exact size past the inner value codec's decode bound is `input_too_long` (Q1); +4. an exact size past the intermediate's bound known at compile time is `input_too_long` + (genesis; with D2 this can now only be the static text's own bound, which an exact size never + passes, so it stays as a guard); +5. the intermediate is made (in place, or from the allocator) and the outer link decodes into it; +6. the inner value codec decodes the written bytes and its errors reach the caller unchanged. + +Nothing is written, allocated or wiped before step 5, so a refusal at step 3 costs no +allocation, even where the intermediate would have been on the heap. + +### D4. `noexcept` and allocation + +`over_value_decode_is_noexcept` keeps the genesis' rule (R3: `noexcept` exactly when the +intermediate is in place and the links' calls cannot throw), with the middle bound of D2. So +`codecs::decode(over{formats::armor("PUBLIC KEY"), spki}, std::string_view)` is `noexcept` and +allocates nothing when the inner value codec states a bound of at most 4096 and its `decode` is +`noexcept`; the typed `decode` follows through `typed_decode_is_noexcept`, as it does +today for a static text. + +### D5. Secrecy + +The intermediate in place is `in_place_intermediate`, unchanged: it records the +exact size it was made with and wipes those bytes by `secure::erase_secret` when it goes, on +success, on an outer link's failure in its `decode` (which a codec whose `decoded_size` checks the +whole text never has, but which the wipe covers) and on the inner value codec's failure. A +refusal at D3's steps 2 to 4 makes no intermediate, so there is nothing to wipe. The heap +path above the cap keeps `basic_secret_byte_vector`. A secret operation holds the timing guard +and runs both links' secret arithmetic (genesis R7) as before. + +### D6. Constant time + +The one new branch compares the outer link's exact decoded size, a length, with a constant. +Lengths are public in codecs' model (the genesis' D12 and the spec's constant-time requirement: +"the input's length, the output's length ... MAY be public"), and the size is computed by the +outer link's `decoded_size` as before. The constant-time lane gains the path that exercises it +with a secret: a secret test value decoded through `over{formats::armor("TEST SECRET"), ...}` from +a `std::string_view`, its payload marked undefined, under memcheck and MemorySanitizer, which +checks that no branch and no address depends on the payload in the outer link, in the bound's +check and in the copy into the intermediate. No dudect case is added: the code timed is the +armor's decode, which the lane's armor case already measures; the inner value codec is the +test's own. + +### D7. Fuzzing + +A new target, `over_value` (`test/fuzz/over_value_fuzz.cpp`): the input's first byte chooses the +outer link (`formats::hex`, or `formats::armor("RECORD")`) over a value codec of the tests' own +with a decode bound of 16 and an encoded bound of 12, the rest is the text, given as a +`std::string_view`. Each input checks: no crash; no allocation at all (the global counter, since +the intermediate is in place; under AddressSanitizer a write past the 16 bytes is the +sanitizer's); the result equals a two-step reference (the outer link's own decode into a +`std::vector`, then `input_too_long` past 16 bytes, else the value codec's own decode of those +bytes), value or error; the secret twin of the value gives the same; what decodes encodes back to +a text that decodes to the same value. Its corpus seeds: the empty text, the 12-byte and the +16-byte forms, 17 bytes, an outer error past the 16th byte, an armor with CRLF lines. + +### D8. Documentation + +`doc/composition.adoc`'s "Where the intermediate lives" gains the decode bound (D2's table in +prose) and its "Errors" the refusal (D3); `doc/writing_a_format.adoc`'s value codec section the +member (D1) and the rule against `max_encoded_size`; `doc/allocators.adoc` the sentence on what +`over`'s allocator is still used for. A new example, `example/over_value.cpp`, decodes a value of +its own through `over{formats::armor("RECORD"), ...}` from a `std::string`, shows the payload past +the bound refused, and states (in its output) that no heap was used; it is built and run on every +lane as every example. The changelog's line under "Unreleased". + +## Rulings + +- **R1. Ruling: the member is `max_decode_input_size`, crypto's name, with no public reader in + codecs** - why: owner decision 28 says codecs adopts crypto's name, so crypto's five headers + keep theirs; codecs offers no reader for `max_encoded_size` either, a value codec's members + being the contract - cost if wrong: a reader is one variable template. +- **R2. Ruling: a value codec stating both bounds with `max_decode_input_size < max_encoded_size` + stops the build** (`static_assert` in the core, in `detail::check_value_bounds()`, called + where `check_secret_value_overloads` is, so that every encode and decode of the pair, and every + `over` of it, checks it; message "webcpp::codecs: a value codec's max_decode_input_size is below + its max_encoded_size, so its decode would refuse its own longest encoding") - why: such a codec + is wrong by construction; crypto checks the stronger equality of its own pairs (its R37) - cost + if wrong: a value codec that writes encodings it cannot read would need the check removed. +- **R3. Ruling: the middle bound is D2's table** - why: owner decision 28, and the smaller bound + is always the safer stack - cost if wrong: none for crypto's bounds. +- **R4. Ruling: a size past the bound is refused after the outer link's errors and before the + intermediate is made, with `input_too_long` (Q1, recommendation A), in `over` alone; the direct + decode of a value codec is unchanged** - why: the intermediate cannot be written past its + bound, and refusing before the allocation also bounds the heap path; `over` already answers an + intermediate past a compile-time bound with `input_too_long`; a direct decode gives the value + codec the bytes and has no reason to override its error - cost if wrong: the error changes in + one function, and crypto's `pem-forward` sentence and tests follow (Q1's B or C). +- **R5. Ruling: a decode bound above 4096 bytes keeps the heap intermediate (Q2, recommendation + A), reusing `detail::in_place_scratch_limit`, moved from tokens.hpp to size_maximum.hpp so that + `over.hpp` and `tokens.hpp` share it** - why: the owner's own threshold for `assign_to`'s + scratch, and a format author's bound must not cost every caller a large stack with no escape; + Emscripten's default stack is 64 KiB - cost if wrong: a value codec above 4096 bytes allocates + where it could have been in place; removing the cap is one condition. +- **R6. Ruling: a value codec with no decode bound keeps the genesis' behaviour (the heap for a + text of a dynamic size), and is neither refused nor warned** - why: the bound is optional in + codecs' contract; value codecs of other libraries and of programs (the tests' `be16` number, a + value of any length) have none, and refusing them would break chains that work; crypto + requires a bound of its own pairs in its own check (its R37) - cost if wrong: a later change + could require it with one `static_assert`. +- **R7. Ruling: `noexcept` follows the intermediate, as the genesis' R3** - why: one rule for + every `over` form - cost if wrong: none. +- **R8. Ruling: `over`'s own value codec states no `max_decode_input_size`** - why: the longest + text a chain decodes has no bound from its links' contracts: a codec's decoder may accept text + longer than the longest it writes (the armor's CRLF lines, a case-folded or padded text), and + codecs has no "longest accepted text" for a codec; so in a chain of chains only the level + whose inner link is a value codec with a bound is in place for a dynamic text, and the outer + levels are as the genesis says - cost if wrong: a codec-level accepted bound is a change of + its own. +- **R9. Ruling: the secret intermediate is the genesis' `in_place_intermediate`, wiping the bytes + it was made for** - why: it is already wiped on every path; D3 makes no intermediate before + the refusal, so no wipe is needed there - cost if wrong: none. +- **R10. Ruling: the constant-time lane gains a memcheck and MemorySanitizer path, and no dudect + case** - why: D6 - cost if wrong: one dudect case of the armor over a value codec. +- **R11. Ruling: a new fuzz target `over_value` rather than a branch of `over`'s** - why: `over`'s + target is a bytes chain over an arena; the value chain's check is that nothing allocates at + all, which needs the global counter alone, and a target per subject keeps their corpora apart + - cost if wrong: none. +- **R12. Ruling: the encode side is not changed, and the outer link's encode fault after `prepare` + with a heap intermediate stays as documented** - why: owner decision 28 is about the decode; + the encode's intermediate is already in place whenever the value codec states + `max_encoded_size` (every crypto pair), so the documented case remains only for an input of a + dynamic size with no encode bound, where the probe, being `noexcept`, cannot allocate - cost if + wrong: a later change could let the probe allocate in a non-`noexcept` form. +- **R13. Ruling: crypto's follow-up is a crypto change of its own, `pem-forward`, run in this + stream after codecs' tasks and merged with it, the superproject moving both gitlinks in one + pull request** - why: once codecs' `over` decodes in place, crypto's `formats` tests that state + "`codecs::decode` of a PEM allocates" and "a payload past the bound is `invalid_encoding`" + through `codecs::decode` no longer hold, so the superproject's `main` would be red between the + two; and crypto's `detail::decode_pem` becomes dead weight - cost if wrong: one more pull + request. +- **R14. Ruling: a new example, `over_value.cpp`, rather than a change of `over_chain.cpp` or + `pem.cpp`** - why: both show bytes chains and their outputs are pinned; a value codec of the + example's own shows the member a format author writes - cost if wrong: none. +- **R15. Ruling: the plan's tasks change only codecs' `detail` and its tests, docs and example; + no public name is added** - why: D1's member is a name of the value codec's author, not of + codecs - cost if wrong: none. + +## Builder's calls + +- The names of the detail helpers (`has_decode_input_bound`, `value_decode_bound`, + `check_value_bounds`, `over_value_middle_bound`) and of the test support + (`test/support/bounded_records.hpp`: `bounded_t`, `short_record`, `sealed_record`, + `wide_record`). +- Whether `over_value_middle_bound` is a function or a variable template. + +## Risks / Trade-offs + +- **The error of a long PEM payload changes** for a caller of `codecs::decode` (Q1): from the + inner value codec's error to `input_too_long`. Only crypto's PEM exists today, and crypto's + `pem-forward` changes with it. +- **A decode bound is a promise the core now relies on for memory**: a value codec that states + a bound and accepts a longer input through its direct decode is inconsistent; through `over` + it simply refuses the longer one. The spec states the promise; crypto's toy and its pairs are + checked by their tests. +- **The stack**: up to 4096 bytes per level of a chain whose inner value codec states a bound, + in the frame of the decode; crypto's largest is 138. + +## Migration Plan + +crypto's `formats` merges; then, in this change's stream (`codecs-over`, its folder and heavy.sh's +stream name in the plan's commands), codecs' Tasks 1 to 4 on branch `codecs/over-in-place` of +webcpporg/codecs, crypto's Task P1 (`libraries/crypto/openspec/changes/pem-forward/`) on branch +`crypto/pem-forward` of webcpporg/crypto, the superproject's gitlinks (Task 5), the delivery +(Task 6): pull requests in the order codecs, crypto, superproject, proposals, merged by the +stream under the owner's standing instruction, one CI at the end. Then `hpke`. + +## Open Questions + +Q1 and Q2, at the top of this design. Nothing else is open. diff --git a/libraries/codecs/openspec/changes/over-in-place/proposal.md b/libraries/codecs/openspec/changes/over-in-place/proposal.md new file mode 100644 index 0000000..a82c915 --- /dev/null +++ b/libraries/codecs/openspec/changes/over-in-place/proposal.md @@ -0,0 +1,80 @@ +## Why + +`codecs::over` holds the bytes between its links, its intermediate, in place only +when their bound is known at compile time: the input's type states its size, or, for an encode, +the inner value codec states `max_encoded_size`. A decode reads a text, and a text arrives as a +`std::string_view` or a `std::string`, whose size is not static, so every decode of a value +through `over` from such a text puts the intermediate on the heap, from `over`'s allocator. PEM +is exactly that: crypto's `pem(F)` is `over`, a PEM file is a run-time +string, and `codecs::decode(pem(spki), text)` allocates, is not `noexcept`, and +breaks crypto's owner decision 3 ("no heap"). + +crypto's `formats` change worked around it (its design R24): `crypto::decode` of a PEM format runs +the two links itself, the armor into a stack buffer of the inner format's decode bound and then +the inner value codec, while `codecs::decode` of the same format and text still allocates. The +owner's decision 23 of that change gave every crypto value codec a decode bound of its own, +`max_decode_input_size`, the longest encoded input its decoder accepts (equal to +`max_encoded_size` today: 48 for Ed25519's and X25519's `pkcs8`, 138 for P-256's; larger than it +once PKCS#8 v2 is accepted), so that the stack buffer is sized by what the decoder takes, not by +what the encoder writes. On 2026-11-30 the owner approved the plan's question Q1: codecs' `over` +decodes in place under the inner value codec's decode bound, as a small codecs change queued +right after `formats` and before `hpke`. This is that change. + +## What Changes + +- **The decode bound joins codecs' value codec contract.** `value_codec` MAY state + `static constexpr std::size_t max_decode_input_size`, the longest encoded input its `decode` + accepts, in bytes for a value codec of bytes and in characters for one of text; codecs adopts + crypto's name (crypto's R37). When a value codec states both bounds, `max_decode_input_size` + must not be below `max_encoded_size`, a check the core makes at compile time. +- **`over` decodes a value in place under that bound.** The intermediate of + `decode(over{outer, inner}, text)` is held in place, in the frame of `over`'s decode, + sized by the smallest bound known at compile time: the outer link's bound on a text of a static + size (unchanged), and the inner value codec's `max_decode_input_size` when it is at most 4096 + bytes. An intermediate whose exact size, which the outer link's `decoded_size` gives after it + checked the whole text, is past the decode bound is refused with `codecs::error::input_too_long` + before it is made or written, after the outer link's own errors, whether it would have been in + place or on the heap. With the intermediate in place the decode is `noexcept` when the links' + calls are, and allocates nothing. +- **Unchanged:** a value codec with no decode bound (the intermediate stays on the heap for a + text of a dynamic size); a decode bound above 4096 bytes (the heap, its allocation never above + the bound); the encode side, and its outer link's encode fault found after `prepare` with a + heap intermediate; the direct `decode(format, input)` of a value codec, which still + hands every input to the value codec and returns its errors; `over`'s own value codec, which + states no decode bound. +- **The lanes:** the constant-time lane gains the path of a secret value decoded through + `over{armor, ...}` from a text of a dynamic size, under memcheck and MemorySanitizer; the fuzz + lane gains a target, `over_value`, whose chains decode with no heap at all and agree with a + two-step reference. +- **The page:** composition's "Where the intermediate lives", writing a format's value codec + section, a new example `over_value.cpp`, the changelog's line. +- **crypto's follow-up, in the same stream:** crypto's change `pem-forward` + (`libraries/crypto/openspec/changes/pem-forward/`) removes the R24 workaround, so that + `crypto::decode` of a PEM format forwards to `codecs::decode` as every other format does; the + superproject moves both gitlinks together, since codecs' change alone changes what crypto's + `formats` tests assert of `codecs::decode` of a PEM format. + +## Capabilities + +### New Capabilities + +None. + +### Modified Capabilities + +- `codecs`: the value codec's optional decode bound, and `over`'s decode of a value in place + under it. + +## Impact + +- **Kind:** webcpp's own (`"port-of": null`), as codecs' genesis. +- **Breaking:** no API is removed. A decode through `over` of a value whose value codec states a + decode bound, from a text whose payload is past that bound, returns + `codecs::error::input_too_long` where it returned the value codec's own error (open question 1 + of the design); such a decode no longer allocates and becomes `noexcept`. +- **Implementation:** webcpporg/codecs (`include/webcpp/codecs/detail/core/over.hpp`, + `contract.hpp`, `secrecy.hpp`, `size_maximum.hpp`, `tokens.hpp`; tests, the constant-time and fuzz + lanes, the page, an example, the changelog's line), webcpporg/crypto through its change + `pem-forward`, the superproject (both gitlinks). The plan is `reference/plan.md`. +- **Status:** approved by the owner on 2026-11-30 (crypto `formats`' question Q1); accepted with + `reference/plan.md`, its two open questions answered by the owner before implementation. diff --git a/libraries/codecs/openspec/changes/over-in-place/reference/plan.md b/libraries/codecs/openspec/changes/over-in-place/reference/plan.md new file mode 100644 index 0000000..354a59d --- /dev/null +++ b/libraries/codecs/openspec/changes/over-in-place/reference/plan.md @@ -0,0 +1,548 @@ +# codecs over-in-place Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** `codecs::decode(over{outer, inner}, text)` holds its intermediate in place, with +no heap and `noexcept`, whenever the inner value codec states its decode bound +`max_decode_input_size` (at most 4096), whatever the text's type; a payload past the bound is +refused before any intermediate; then crypto's PEM decode becomes a forward to codecs. + +**Architecture:** four codecs tasks and one crypto task. Task 1 adds the member to the contract +(the core reads it, checks the order of the two bounds, and shares the 4096 threshold). Task 2 +changes `over`'s value decode alone (the middle bound, the refusal, `noexcept`), proven on a +value codec of the tests' own that mirrors crypto's PKCS#8 v1 and v2 shape. Task 3 adds the +constant-time path and a fuzz target. Task 4 is the page. crypto's Task P1 (in crypto's +`pem-forward` plan) removes crypto's two-step PEM decode. Task 5 moves both gitlinks; Task 6 is +the delivery. + +**Tech Stack:** C++20 header-only, b2 5.5.3, Boost 1.92 (System's `result`, Core's +LightweightTest), webcpp::secure (merged), webcpp::crypto (after `formats`), clang (Apple), gcc +15, wasi-sdk 34 (wasip2, wasip3), Emscripten 6.0.11, MSVC 14.3 and 14.5 (the owner's Windows 11 +ARM64 VM), Valgrind, clang 18's MemorySanitizer and libFuzzer (Linux container), dudect. + +**Spec:** this change, `libraries/codecs/openspec/changes/over-in-place/` of webcpporg/proposals +at the commit that adds this plan: `proposal.md`, `design.md` (owner decision 28, D1 to D8, R1 to +R15, binding), `specs/codecs/spec.md` (binding), `tasks.md`; crypto's change +`libraries/crypto/openspec/changes/pem-forward/` (its plan holds Task P1). Read both designs +before any task, and codecs' genesis design D4, D9 to D12 and D22 +(`libraries/codecs/openspec/changes/genesis/design.md`), crypto's `formats` design R24, R35, R37 +and owner decision 23. + +## Open for the owner + +The design's Q1 (the error of a payload past the bound; recommended `input_too_long`, in `over` +alone) and Q2 (the 4096 cap; recommended). This plan is written with both recommendations; the +places that change are marked "(Q1)" or "(Q2)". With Q1's B, Task 2 also adds the check to the +core's direct value decode (`detail::value_decode`) and crypto's P1 changes its DER tests; with +Q1's C, Task 1 adds the optional member `decode_input_too_long` and crypto's P1 states it, its +errors then unchanged; with Q2's B, Task 2 drops the cap's condition and its test. + +**Paths:** `$W` is the owner's workspace directory, the folder that holds `heavy.sh`, +`msvc-lane/`, `linux-lint/` and this stream's folder `codecs-over/` (a plan in the proposals +repository names no machine path). `$S` is `$W/codecs-over/webcpp`, the superproject worktree on +branch `codecs/over-in-place`; its `libs/codecs` is on branch `codecs/over-in-place` of +webcpporg/codecs and its `libs/crypto` on branch `crypto/pem-forward` of webcpporg/crypto; +`libs/secure`, `libs/config` and `libs/hash` stay at the superproject's gitlinks and are never +touched. Every command runs from `$S`. Never create another worktree or tree. + +**Commands:** `B2` means +`env -u CPATH -u CPLUS_INCLUDE_PATH -u C_INCLUDE_PATH b2 --user-config=.local/user-config.jam`. +The lanes: +- native: `B2 toolset=clang `; `B2 toolset=gcc-15 ` +- wasip2: `B2 toolset=clang-wasip2 testing.launcher=tools/boost/asio-wasip2/run.sh ` +- wasip3: `B2 toolset=clang-wasip3 testing.launcher=tools/boost/asio-wasip3/run.sh ` +- Emscripten: `B2 toolset=emscripten ` +- "the five local lanes" means all of the above over the task's targets (incremental while + iterating; `-a` only in the delivery). +- the doc: `B2 doc` (the guide of every library, its examples' tagged regions checked). +- MSVC, the essential set (owner's rule): `$W/heavy.sh codecs-over $W/msvc-lane/run-lane.sh <14.3|14.5> --tree $W/codecs-over/lane-tree [--arch arm64] -- `, + read with `$W/msvc-lane/summarize.sh <14.3|14.5> ` (`new failures:` empty): x64 debug + on 14.3 and 14.5 over the task's targets; arm64 on 14.5 only for crypto's DIT and timing tests + (Task P1, the delivery); no release. Commit, then `$W/codecs-over/refresh-tree.sh`, before a + run: the lane tree is built from committed heads. +- The constant-time and fuzz lanes on Linux: `$W/heavy.sh codecs-over $W/codecs-over/ct-run/linux.sh `; + natively on this Mac, the dudect programs of the library a task names + (`B2 toolset=clang variant=release libs/codecs/test/constant_time//dudect`). +- A whole library from scratch, the full lints and the MSVC lane are heavy: only through + `$W/heavy.sh codecs-over `. + +**Which lanes a task runs (owner's rule):** a task's first implementation runs the five local +lanes over its targets, the doc when it changed a header's Doc Comment or a page, MSVC 14.3 and +14.5 x64 debug over its targets, and the constant-time, fuzz or arm64 lanes its "Lanes" line +names. A fix round (review findings, a failing lane) runs only the affected tests on one lane +(native clang debug) and the lint, plus a special lane (MSVC, constant-time, fuzz) only when the +fix changed that lane's subject. Every lane runs again on the final head (Task 6). + +**The lint step of every task:** commit, then +`$W/codecs-over/lint.sh $W/codecs-over/lint-task.log ` +(the macOS half, clang-format's check and clang-tidy from `.local/wasi-sdk/bin/` over the files' +translation units of the compilation database, then the Linux lint, `$W/linux-lint/run.sh --files` +on the lane tree, through heavy.sh); fix every finding of one run in the task's own commit +(`codecs: ... lint fix`), run once more; a task reaches review lint-clean. Format C++ first with +`.local/wasi-sdk/bin/clang-format -i `. Deleted files are not passed. + +## Preflight (the controller, before Task 1) + +- [ ] crypto's `formats` is merged: `git -C $W/webcpp fetch origin` shows the superproject's + `origin/main` with `libs/crypto` at crypto's merged `main` holding `include/webcpp/crypto/formats.hpp` + and its `detail::decode_pem`, and `libs/codecs` at `80d90d0` or later. +- [ ] `$S`: `git -C $W/webcpp worktree add $W/codecs-over/webcpp -b codecs/over-in-place origin/main`; + `git -C $S submodule update --init libs/config libs/secure libs/codecs libs/hash libs/crypto` + and the third-party submodules crypto's and codecs' tests name (`third_party/libs/openssl`, + `bitcoin`, `wycheproof`, `bips`, `secp256k1`, `bearssl`, `libsodium`, `ed25519-speccheck`, + `xkcp`, Boost); `ln -sfn $W/webcpp/.local $S/.local`; + `git -C $S/libs/codecs switch -c codecs/over-in-place`; + `git -C $S/libs/crypto switch -c crypto/pem-forward`. +- [ ] Record in a new `reference/STATUS.md` of this change the base SHAs: superproject, codecs, + crypto, hash, secure, config. +- [ ] The stream's tools (not committed), copied from `$W/formats/` with `formats` -> + `codecs-over`: `refresh-tree.sh` (its loop over `codecs` and `crypto`), `lint.sh`, and + `ct-run/linux.sh` and `inside.sh` (container `ct-codecs-over`, volume `ct-codecs-over-work`; the + first argument names the library, the second the lane). Check `lint.sh` on Task 1's files + before dispatching Task 2. +- [ ] Read crypto's merged `formats.hpp`, `test/formats_pem_test.cpp` and the curves' PEM tests: + where `formats` was built with other names than its plan's (`detail::decode_pem`, the toy's + names, the counter's), Task P1 uses the built ones and records the difference in + `reference/STATUS.md`. + +## Global Constraints + +- English in files; never the em dash character, use "-"; commit messages with no trailer at all; + never hand-edit CHANGELOG.md or generated files (crypto's `doc/generated/*`, `doc/llms.txt`, its + capability tables: change `doc/tables/crypto.json` or the generator and run it); + "Copyright (c) 2026 WebCpp.org" BSL-1.0 headers; heavy work only through heavy.sh; flaky tests + and lint warnings are defects to fix; measurements only from release builds (this change makes + none); never contact upstream projects; merge origin/main into branches, never rebase; no + GitHub CI run until the final one. +- Commit subjects in each repository's style: `codecs: ...`, `crypto: ...`; superproject + `libs/codecs: the gitlink at ()`, `libs/crypto: ...`. Never `git add -A` or + `git add libs` in the superproject. +- Scope: `over`'s decode of a value and the contract's member. The encode side of `over`, its + outer link's encode fault after `prepare` with a heap intermediate (design R12), `codec`'s + contract, `over`'s bytes decode (`over_decode`, `over_decoded_size`) and the streams are not + changed. No public name is added to codecs (R15). +- Names, verbatim from the design: the member `max_decode_input_size`; detail + `has_decode_input_bound`, `value_decode_bound`, `value_bounds_ordered`, `check_value_bounds`, + `over_value_middle_bound`, `in_place_scratch_limit` (moved, not renamed); the error + `codecs::error::input_too_long` (Q1); the fuzz target `over_value`; the example + `over_value.cpp`; the message test `decode_bound_below_encoded`. +- Exceptions (owner decision 24 and the owner's standing rule): codecs throws nothing of its own; + an allocator's exception propagates out of the allocating forms, which are not `noexcept`; + every test runs with exceptions on and off (`codecs-run`, `codecs-compile`, `crypto-run`). +- Secrets: every intermediate of a secret chain is wiped by `secure::erase_secret`; every secret + operation holds `secure::timing_guard` (the core's, as today); codecs keeps no guard, wipe or + constant-time primitive of its own. +- `nodiscard-results` (codecs' and crypto's `meta/lint.json`): every function of `include/` that + returns `boost::system::result` is `[[nodiscard]]`. +- Every header survives a bare `` before it: `(std::min)(...)`, `(std::max)(...)`. +- The owner's VM: never shut it down, suspend or reconfigure it; `$W/msvc-lane/known-failures.txt` + is never edited. + +## Review Focus + +1. **The bound's edges, dynamic and static.** A run-time text whose payload is 0, 12, 16 and 17 + bytes through `over{hex, bounded}` and `over{armor("RECORD"), bounded}`, and the same as + `text` of a static size smaller and larger than 16. Expected: 12 and 16 decode with no + heap, 0 is the value codec's `invalid_length`, 17 is `input_too_long` with no heap and the + value codec not called. Task 2 pins it. +2. **The outer link's error past the bound.** A 35-character hex text whose last character is + `g`; an armor whose 17-byte payload has a bad base64 symbol. Expected: the outer link's + `invalid_character` (or `invalid_length` for the odd hex), never `input_too_long`. Task 2. +3. **A secret intermediate on every path.** A secret record decoded through `over` from a + `std::string_view`: valid, refused by the value codec, refused by the outer link, past the + bound. Expected: the wipe seam sees the written bytes erased on the first two; the last two + make no intermediate (the outer link's `decoded_size` checks the whole text before it is + made), so nothing secret is left. Task 2. +4. **The cap.** A bound of 4097 and 4096 bytes with an arena allocator. Expected: 4096 in place + (arena untouched), 4097 one allocation of the exact size, 4098 bytes `input_too_long` with no + allocation. Task 2. +5. **crypto's PEM after the forward.** An RSA public key's PEM under `PUBLIC KEY` (294 bytes of + DER) given to `crypto::decode(pem(spki), text)` and to `codecs::decode` of + the same. Expected: both `codecs::error::input_too_long` (Q1), neither allocates, no write past + 138 bytes. Task P1. + +## The files + +| File | Holds | Task | +| --- | --- | --- | +| `include/webcpp/codecs/detail/core/size_maximum.hpp` | `in_place_scratch_limit`, moved from tokens.hpp | 1 | +| `include/webcpp/codecs/detail/core/contract.hpp` | `value_codec`'s Doc Comment (the member), `has_encoded_bound` (moved from operations.hpp), `has_decode_input_bound`, `value_decode_bound` | 1 | +| `include/webcpp/codecs/detail/core/secrecy.hpp` | `value_bounds_ordered`, `check_value_bounds`, called by `value_encoded_size`, `value_encode`, `value_decode` | 1 | +| `include/webcpp/codecs/detail/core/over.hpp` | `over_value_middle_bound`, `over_value_decode`'s refusal, `over_value_decode_is_noexcept`, the Doc Comments | 2 | +| `test/support/bounded_records.hpp` | the format `bounded` and its records | 1, 2, 3 | +| `test/over_test.cpp`, `test/allocation_test.cpp`, `test/noexcept_test.cpp`, `test/value_codec_test.cpp` | the cases | 1, 2 | +| `test/messages/decode_bound_below_encoded/` | the message test | 1 | +| `test/constant_time/paths.hpp` | the path `over_value_paths` | 3 | +| `test/fuzz/over_value_fuzz.cpp`, `test/fuzz/corpus/over_value/` | the fuzz target | 3 | +| `doc/composition.adoc`, `doc/writing_a_format.adoc`, `doc/allocators.adoc`, `doc/changelog.adoc`, `example/over_value.cpp` | the page | 4 | + +--- + +### Task 1: The decode bound in the value codec contract + +Model tier: standard. Size: M. + +**Files:** +- Modify: `libs/codecs/include/webcpp/codecs/detail/core/size_maximum.hpp`, `tokens.hpp`, + `contract.hpp`, `operations.hpp`, `secrecy.hpp` +- Create: `libs/codecs/test/support/bounded_records.hpp`, + `libs/codecs/test/messages/decode_bound_below_encoded/{Jamfile,decode_bound_below_encoded.cpp}` +- Modify: `libs/codecs/test/value_codec_test.cpp`, `libs/codecs/test/messages/Jamfile` + +**Interfaces:** + +```cpp +// size_maximum.hpp, moved from tokens.hpp with its Doc Comment widened: the most elements a +// scratch of assign_to, or an intermediate of over sized by a value codec's decode bound, holds +// in place (the owner's ruling of 2026-11-26, design R5 of over-in-place). +namespace webcpp::codecs::detail { +inline constexpr std::size_t in_place_scratch_limit = 4096; +} + +// contract.hpp, beside value_codec's declaration (its Doc Comment's listing gains the member: +// "static constexpr std::size_t max_decode_input_size = 138; // optional; the longest input decode accepts") +namespace webcpp::codecs::detail { +template +concept has_encoded_bound = requires { // moved from operations.hpp, unchanged + { Codec::max_encoded_size } -> std::convertible_to; +}; +template +concept has_decode_input_bound = requires { + { Codec::max_decode_input_size } -> std::convertible_to; +}; +// The decode bound value_codec states, or std::dynamic_extent (equal to SIZE_MAX) when none. +template +[[nodiscard]] consteval std::size_t value_decode_bound() noexcept; +} + +// secrecy.hpp, beside check_secret_value_overloads +namespace webcpp::codecs::detail { +// True unless value_codec states both bounds and max_decode_input_size < max_encoded_size. +template +inline constexpr bool value_bounds_ordered = /* as said */; +template +constexpr void check_value_bounds() noexcept { + static_assert(webcpp::codecs::detail::value_bounds_ordered, + "webcpp::codecs: a value codec's max_decode_input_size is below its " + "max_encoded_size, so its decode would refuse its own longest encoding"); +} +// value_encoded_size, value_encode and value_decode call check_value_bounds() next to +// check_secret_value_overloads(). +} +``` + +`test/support/bounded_records.hpp`, namespace `webcpp::codecs::test`: the format `bounded_t` +(`name` "bounded") and `inline constexpr bounded_t bounded{}`; three values, each with its +`value_codec` of `output_kind::bytes`, every function `noexcept`: +- `short_record` (8 bytes, `operator==`): `max_encoded_size = 12`, `max_decode_input_size = 16`; + encode writes `30 0a 02 00` and the 8 bytes; decode accepts that 12-byte form and a 16-byte + form, `30 0e 02 01`, the 8 bytes, `a1 02` and the first 2 of the 8 bytes again; any other + length `codecs::error::invalid_length`, any other byte `codecs::error::invalid_prefix` (the + shape of crypto's PKCS#8 v1 and the deferred v2). +- `sealed_record`: the same codec with `secret = true` (its bytes in a `secure::secret<8>`). +- `wide_record` (a count): decode only, `max_decode_input_size = 4097`, any length up to 4097 + accepted (the count of bytes), longer `invalid_length`. + +- [ ] **Step 1: Write the failing tests.** + - `value_codec_test.cpp`: `detail::value_decode_bound() == 16`, + `== std::dynamic_extent` for the `be16` number; `value_bounds_ordered` true for the three + records and the number; `codecs::decode(bounded, bytes)` of the 12-byte and + 16-byte forms gives the record, and of 17 bytes the value codec's own `invalid_length` (a + direct decode is the value codec's, spec scenario); the 12-byte form encodes back with + `codecs::encode(bounded, record)` as `bytes<12>`. + - `test/messages/decode_bound_below_encoded/`: a value codec of the file's own with + `max_encoded_size = 12` and `max_decode_input_size = 8`, decoded with `codecs::decode`; + `// expected-error@webcpp/codecs/detail/core/secrecy.hpp:* {{static assertion failed due to requirement 'webcpp::codecs::detail::value_bounds_ordered<...>': webcpp::codecs: a value codec's max_decode_input_size is below its max_encoded_size, so its decode would refuse its own longest encoding}}` + (the requirement's text as clang prints it, read from the first failing run); its Jamfile as + `refused_size`'s (`compile-diagnostic ... : native wasip2 wasip3 : alone` and the + `compile-fail` twin on native and Emscripten); `build-project` in `test/messages/Jamfile`. +- [ ] **Step 2: Run, expect failure.** `B2 toolset=clang libs/codecs/test//value_codec libs/codecs/test/messages/decode_bound_below_encoded`: + `bounded_records.hpp` names a `value_decode_bound` that does not exist; the message test + compiles. +- [ ] **Step 3: Implement** the interfaces above; `tokens.hpp` reads `in_place_scratch_limit` + from `size_maximum.hpp` (it includes it already, or gains the include); `operations.hpp` reads + `has_encoded_bound` from `contract.hpp`. +- [ ] **Step 4: Run.** The five local lanes over `libs/codecs/test`; the doc; MSVC 14.3 and 14.5 + x64 debug over `libs/codecs/test//value_codec libs/codecs/test//tokens libs/codecs/test//over libs/codecs/test/messages/decode_bound_below_encoded`. + Expected: pass. +- [ ] **Step 5: Commit, lint.** `codecs: a value codec may state max_decode_input_size, the longest input its decode accepts, never below max_encoded_size`. Lint step. + +**Lanes:** the five local lanes, the doc, MSVC 14.3 and 14.5 x64 debug. + +--- + +### Task 2: `over` decodes a value in place under the decode bound + +Model tier: most capable (the core's `noexcept` and secret paths). Size: L. + +**Files:** +- Modify: `libs/codecs/include/webcpp/codecs/detail/core/over.hpp` +- Modify: `libs/codecs/test/over_test.cpp`, `libs/codecs/test/allocation_test.cpp`, + `libs/codecs/test/noexcept_test.cpp`, `libs/codecs/test/support/bounded_records.hpp` + +**Interfaces:** + +```cpp +namespace webcpp::codecs::detail { +// The bound the intermediate of a decode of View into a Value through Outer over Inner is held +// in place under (design D2): the smaller of the outer link's bound on a text of a static size +// and the inner value codec's decode bound when it is at most in_place_scratch_limit (Q2); +// std::dynamic_extent when neither is known. std::dynamic_extent is SIZE_MAX, so the smaller of +// two is (std::min) of them. +template +[[nodiscard]] consteval std::size_t over_value_middle_bound() noexcept; + +// over_value_decode_is_noexcept: middle_bound is over_value_middle_bound<...>(); the rest as today. + +// over_value_decode, in this order (design D3): +// middle_size = codec_decoded_size(outer, text) -> the outer link's error first +// if (middle_size > value_decode_bound()) -> error::input_too_long (Q1) +// if (past_bound(middle_size)) -> error::input_too_long (genesis) +// over_intermediate middle{...} -> in place, or the allocator +// codec_decode(outer, text, middle.bytes()), then value_decode(inner, next_bytes/next_text) +} +``` + +The Doc Comments of `over` (the paragraph "The intermediate ... is held in place when its bound +is known at compile time"), of `value_codec, Value>` and of `over_value_decode` say the +decode bound, the cap, the refusal and that `over`'s own value codec states no decode bound +(R8). `bounded_records.hpp` gains `edge_record`, a copy of `wide_record` with +`max_decode_input_size = 4096`. + +- [ ] **Step 1: Write the failing tests.** In `over_test.cpp` (its Jamfile line already defines + `WEBCPP_SECURE_TEST_WIPE_RECORD`), one function per Review Focus item and spec scenario: + - `a_value_from_a_run_time_text_has_no_heap`: `over{formats::hex, test::bounded}` and + `over{formats::armor("RECORD"), test::bounded}` decode the 12-byte and 16-byte forms of a + `short_record` from a `std::string_view` (and from a `std::string`) to the record, under + `test/support/counting.hpp`'s counter: zero; `static_assert(noexcept(codecs::decode(chain, std::string_view{})))`; + the armor's text with CRLF lines and without its final line feed too. + - `a_payload_past_the_bound_is_refused_before_the_intermediate`: 17 bytes (34 hex digits; an + armor of 17 bytes) `input_too_long`, counter zero, and the value codec not called (the test's + `bounded_records.hpp` counts its `decode` calls in a test-only counter); 0 bytes is the value + codec's `invalid_length`. + - `the_outer_link_errs_first`: 35 hex characters ending in `g` is `invalid_character`, 35 + valid hex digits `invalid_length`; an armor of 17 bytes whose last base64 symbol is `*` is + the armor's `invalid_character` (Review Focus 2). + - `a_static_text_takes_the_smaller_bound`: `codecs::text<24>` and `codecs::text<64>` of hex + (bounds 12 and 32) decode the 12-byte form; the second gives 34 digits `input_too_long`; + both allocate nothing. + - `a_secret_intermediate_is_wiped_on_every_path` (Review Focus 3): `sealed_record` through + `over{formats::hex, test::bounded}` from a `std::string_view`: valid (the wipe record holds + one erase of 16 bytes for the 16-byte form, 12 for the 12-byte form), a wrong prefix (the + value codec's `invalid_prefix`, the erase recorded), a hex text whose last digit is bad (the + outer link's `invalid_character`, found by its `decoded_size`: no intermediate, no erase), 17 + bytes (`input_too_long`, no intermediate, no erase); the same chain over `short_record`, a + public value, records no erase. + - `a_bound_above_the_cap_takes_the_allocator` (Review Focus 4, Q2): `over{formats::hex, + test::bounded, std::pmr::polymorphic_allocator{&arena}}` (`test/support/arena.hpp`) + decodes a `wide_record` of 4097 bytes from a `std::string` (one arena allocation of 4097 + bytes), of 4098 bytes (`input_too_long`, no arena allocation), and an `edge_record` of 4096 + bytes (no arena allocation, in place); `noexcept` false for `wide_record`'s chain, true for + `edge_record`'s. + - `a_value_codec_with_no_decode_bound_is_unchanged`: the `be16` number through + `over{formats::hex, test::be16, arena allocator}` from a `std::string_view`: one arena + allocation, as before this change (spec scenario). + - `a_chain_of_chains`: `over{formats::hex, over{formats::armor("RECORD"), test::bounded}}` + decodes a `short_record` from a `std::string_view` with an arena in the outer chain: one + arena allocation (the outer level's intermediate, R8), none from the inner level. + - `allocation_test.cpp`: the value chain over hex and over the armor, both forms, under the + global counter: zero (the spec's Allocation requirement). + - `noexcept_test.cpp`: the `static_assert`s of the chains above, and that + `value_codec, short_record>` has no `max_decode_input_size` (R8). +- [ ] **Step 2: Run, expect failure.** `B2 toolset=clang libs/codecs/test//over`: the counter + is not zero, the `noexcept` assertions fail, 17 bytes reach the value codec. +- [ ] **Step 3: Implement** the interfaces and Doc Comments above. +- [ ] **Step 4: Run.** The five local lanes over `libs/codecs/test`; the doc; MSVC 14.3 and 14.5 + x64 debug over `libs/codecs/test//over libs/codecs/test//allocation libs/codecs/test//noexcept libs/codecs/test//secret_operation libs/codecs/test//typed_decode`. + Expected: pass, every test with its `_no_exceptions` twin. +- [ ] **Step 5: Commit, lint.** `codecs: over decodes a value in place under the inner value codec's decode bound, refusing a longer intermediate before it is made`. Lint step. + +**Lanes:** the five local lanes, the doc, MSVC 14.3 and 14.5 x64 debug. + +--- + +### Task 3: The constant-time path and the fuzz target + +Model tier: standard. Size: M. + +**Files:** +- Modify: `libs/codecs/test/constant_time/paths.hpp`, `libs/codecs/test/support/bounded_records.hpp` +- Create: `libs/codecs/test/fuzz/over_value_fuzz.cpp`, `libs/codecs/test/fuzz/corpus/over_value/*` +- Modify: `libs/codecs/test/fuzz/Jamfile` + +**Interfaces:** + +```cpp +// bounded_records.hpp gains, for the constant-time lane: +// secret_blob: secret = true, max_encoded_size = 16, max_decode_input_size = 16; decode accepts +// any length up to 16 (a public check of the length alone) and copies the bytes into its +// secure::secret<16> and a public size; no branch and no index on a byte. +// paths.hpp: +template +int over_value_paths(); // added to format_paths() +``` + +- [ ] **Step 1: The constant-time path.** `over_value_paths`: a 16-byte secret payload armored + with `formats::armor("TEST SECRET")` into a `std::string`, the payload's characters marked by + `Checker`; `codecs::decode(over{formats::armor("TEST SECRET"), test::bounded}, std::string_view{text})`; + the result's bytes `traced_and_equal` to the payload; the same with CRLF lines; a 17-byte + payload `input_too_long` (its verdict on the length, public). Run natively under the replay + (`B2 toolset=clang libs/codecs/test/constant_time`) first: it passes without the checker. +- [ ] **Step 2: The fuzz target.** `over_value_fuzz.cpp` (D7): the input's first byte, even or + odd, chooses `over{formats::hex, test::bounded}` or `over{formats::armor("RECORD"), + test::bounded}`; the rest is the text as a `std::string_view`. Per input: the reference, outside + the counted region, is `codecs::decode(outer, text)` into a `std::vector`, then + `input_too_long` past 16 bytes, else `codecs::decode(test::bounded, bytes)`; + inside the region (`fuzz_allocations()` before and after equal) the chain's + `codecs::decode` and `codecs::decode`; both equal the reference, + value or error (the error's value and category); a decoded record encodes through the chain to + a text that decodes to the same record. The corpus: empty, the 12-byte and 16-byte forms in + each outer link, 17 bytes, 35 hex digits ending in `g`, an armor with CRLF lines, an armor + with a 17-byte payload whose last symbol is bad; the Jamfile line `codecs-fuzz over_value ;` + with its comment, as `over`'s. +- [ ] **Step 3: Run.** The five local lanes over `libs/codecs/test/fuzz` (the replay) and + `libs/codecs/test/constant_time`; `$W/heavy.sh codecs-over $W/codecs-over/ct-run/linux.sh codecs constant-time` + (memcheck and MemorySanitizer report nothing on the new path, the planted leak still fails); + `$W/heavy.sh codecs-over $W/codecs-over/ct-run/linux.sh codecs fuzz` (every target, 60 seconds, + no finding); MSVC 14.3 and 14.5 x64 debug over `libs/codecs/test/fuzz//over_value_replay`. + Expected: pass. +- [ ] **Step 4: Commit, lint.** `codecs: the constant-time path and the fuzz target of a value decoded through over under its decode bound`. Lint step. + +**Lanes:** the five local lanes over the replay and the constant-time programs, codecs' +constant-time lane (no dudect case is added, design R10; the lane's dudect runs as it does), the +fuzz lane, MSVC 14.3 and 14.5 x64 debug over the replay. + +--- + +### Task 4: The page + +Model tier: standard. Size: S. + +**Files:** +- Modify: `libs/codecs/doc/composition.adoc`, `libs/codecs/doc/writing_a_format.adoc`, + `libs/codecs/doc/allocators.adoc`, `libs/codecs/doc/changelog.adoc`, `libs/codecs/example/Jamfile` +- Create: `libs/codecs/example/over_value.cpp`, `libs/codecs/example/over_value.expected` + +- [ ] **Step 1: The example.** `over_value.cpp`: a value of its own (a 12-byte record, as the + tests' `short_record` but the example's), its `value_codec` with `max_encoded_size = 12` and + `max_decode_input_size = 16`, encoded through `over{formats::armor("RECORD"), format}`, + printed, decoded from a `std::string` (the tagged region `example`), the 16-byte form decoded, + a 17-byte payload refused (`input_too_long`), and the line `decoded with no heap: yes` from + `noexcept(codecs::decode(chain, std::string_view{}))`; its `.expected`; its + `example/Jamfile` line. +- [ ] **Step 2: The chapters.** composition's "Where the intermediate lives": a third case, the + decode of a value whose value codec states `max_decode_input_size`, in place under it up to + 4096 bytes, the smaller of it and a static text's bound, refused past it; the region of + `over_value.cpp`; its "Errors": the order of D3; its "Pitfalls": a chain of chains is in place + only at the level whose inner link is a bounded value codec. writing_a_format's value codec + section: the member, what it promises (decode refuses every longer input), never below + `max_encoded_size` (the build stops), and that it sizes `over`'s intermediate while a direct + decode still gives the value codec every input. allocators: `over`'s allocator is no longer + used for a decode under a decode bound of at most 4096. Each sentence says what the headers' + Doc Comments say (codecs' AGENTS.md). +- [ ] **Step 3: The changelog's line** under "Unreleased": `* Changed over: a value decodes in place under its value codec's max_decode_input_size, with no heap.` +- [ ] **Step 4: Run.** The five local lanes over `libs/codecs/example`; the doc; MSVC 14.3 and + 14.5 x64 debug over `libs/codecs/example//over_value`. Expected: pass, the doc build clean. +- [ ] **Step 5: Commit, lint.** `codecs: the page says where a value's intermediate lives under its decode bound, with an example`. Lint step. + +**Lanes:** the five local lanes over the examples, the doc, MSVC 14.3 and 14.5 x64 debug. + +--- + +### Task P1: crypto's PEM decode forwards to codecs + +In crypto's plan, `libraries/crypto/openspec/changes/pem-forward/reference/plan.md`. Size: M. +Runs after Task 4, in `$S/libs/crypto` on branch `crypto/pem-forward`, over Tasks 1 to 4's codecs +at its branch head. + +--- + +### Task 5: The superproject + +Model tier: standard. Size: S. + +- [ ] **Step 1:** `libs/codecs` and `libs/crypto` gitlinks at their branch heads (moved to the + merged `main`s in the delivery); commits `libs/codecs: the gitlink at over-in-place ()`, + `libs/crypto: the gitlink at pem-forward ()`. +- [ ] **Step 2:** The superproject's own files: none is expected (no new target, no new + dependency, no new third-party file); `python3 tools/test/crypto_jamfiles_test.py`, + `crypto_jamfiles_format_test.py`, `doc_test.py` and `python3 tools/ci/matrix_test.py` pass. If + one names codecs' fuzz targets or examples in a fixture, add `over_value` there in this task. +- [ ] **Step 3:** Commit, lint (the files touched, if any). + +**Lanes:** the tools' tests above. + +--- + +### Task 6: The delivery (a checklist the controller runs) + +Model tier: the controller; the final review by the most capable model. + +- [ ] Every repository: `git fetch origin`; if `origin/main` moved (codecs, crypto, superproject, + proposals), merge it into the branch (never rebase), re-run the lanes it touches, commit. +- [ ] Commit everything; `$W/codecs-over/refresh-tree.sh`. +- [ ] Lanes, each from scratch, one build directory each, through heavy.sh, over + `libs/codecs/test libs/codecs/example libs/codecs/test/fuzz libs/crypto/test libs/crypto/example libs/crypto/test/fuzz`: + +```bash +B2="env -u CPATH -u CPLUS_INCLUDE_PATH -u C_INCLUDE_PATH b2 --user-config=.local/user-config.jam" +H="$W/heavy.sh codecs-over"; T="libs/codecs/test libs/codecs/example libs/codecs/test/fuzz libs/crypto/test libs/crypto/example libs/crypto/test/fuzz" +$H $B2 -a --dump-tests --build-dir=bin/lane-clang --out-xml=clang.over.xml toolset=clang $T +$H $B2 -a --dump-tests --build-dir=bin/lane-gcc-15 --out-xml=gcc-15.over.xml toolset=gcc-15 $T +$H $B2 -a --dump-tests --build-dir=bin/lane-wasip2 --out-xml=wasip2.over.xml toolset=clang-wasip2 testing.launcher=tools/boost/asio-wasip2/run.sh $T +$H $B2 -a --dump-tests --build-dir=bin/lane-wasip3 --out-xml=wasip3.over.xml toolset=clang-wasip3 testing.launcher=tools/boost/asio-wasip3/run.sh $T +$H $B2 -a --dump-tests --build-dir=bin/lane-emscripten --out-xml=emscripten.over.xml toolset=emscripten $T +$H $B2 doc +``` + (wasip2 and wasip3 with `WEBCPP_WASIP2_TEST_TIMEOUT=1800 WEBCPP_WASIP3_TEST_TIMEOUT=1800`); + every test with its `_no_exceptions` twin. +- [ ] The own lanes: `$H $W/codecs-over/ct-run/linux.sh codecs constant-time`, + `$H $W/codecs-over/ct-run/linux.sh codecs fuzz`, `$H $W/codecs-over/ct-run/linux.sh crypto constant-time`, + `$H $W/codecs-over/ct-run/linux.sh crypto fuzz`; natively on this Mac the dudect programs of + codecs and crypto (release). +- [ ] MSVC on the VM, the essential set: `run-lane.sh 14.3` and `14.5`, x64 debug, over + `libs/codecs/test libs/codecs/example libs/crypto/test libs/crypto/example`; `14.5 --arch arm64` + debug over crypto's timing set (`libs/crypto/test//timing libs/crypto/test//timing_sodium libs/crypto/test//timing_coverage_sodium libs/crypto/test//timing_coverage_bearssl libs/crypto/test//timing_coverage_secp256k1 libs/crypto/test//timing_coverage_openssl libs/crypto/test/constant_time//dudect`, + as built after `formats`). Each `summarize.sh`: `new failures:` empty. +- [ ] Docs and tools: crypto's `generate.py --check` and `generate_test.py`; + `python3 tools/test/crypto_jamfiles_test.py`, `crypto_jamfiles_format_test.py`, `doc_test.py`; + `python3 tools/ci/matrix_test.py`. +- [ ] The report: `python3 tools/report/report.py` over the XML files, every cell green. +- [ ] Lints: macOS full `$H tools/lint/lint.sh --clang-format .local/wasi-sdk/bin/clang-format --clang-tidy .local/wasi-sdk/bin/clang-tidy`; + Linux full `$H $W/linux-lint/run.sh --full $W/codecs-over/lane-tree`. Clean. +- [ ] The final whole-branch review (most capable model) over codecs, crypto and the + superproject; fixes in their own commits; the lanes a fix touches re-run (scoped), then the + final head's lanes above again if a fix touched a header. +- [ ] The proposals: this change's and crypto's `pem-forward` `tasks.md` ticked, `.openspec.yaml` + status `implementing` with `implementation:` the repositories, design and spec true to the + build, `reference/STATUS.md` dated; `python3 tools/proposals.py readme` and `check` (0 + problems); OpenSpec 1.10.0's `openspec validate --all --strict` in `libraries/codecs` and + `libraries/crypto`. +- [ ] Pull requests, in merge order: codecs (`codecs/over-in-place`), crypto + (`crypto/pem-forward`), the superproject (both gitlinks at the merged `main`s, in one pull + request, design R13), then the proposals; each merged with a merge commit by the stream under + the owner's autopilot instruction; no CI gates them; one CI at the end on the superproject's + `main`, every job green, and its failures fixed in follow-up commits as the autopilot rule + says. +- [ ] HANDBACK: `$W/codecs-over/HANDBACK.md` with the merged SHAs, the lanes' results, the + findings of the final review and their fixes, the owner's answers to Q1 and Q2 as built, and a + line for the `hpke` stream: `codecs::decode` of a PEM format no longer allocates, and crypto's + verbs are forwards. + +## Self-review (the planner's) + +- Spec coverage: the value codec's member and its order check (Task 1); `over`'s in-place decode, + the refusal and its order, `noexcept`, the wipe, the cap and the fallback, `over`'s own value + codec without a decode bound (Task 2); the constant-time path and the fuzz target (Task 3); the + page (Task 4); crypto's forward (Task P1). No requirement without a task. +- Names checked against codecs' `main` at `80d90d0`: `over_value_decode`, + `over_value_decode_is_noexcept`, `decoded_bound`, `past_bound`, `in_place_intermediate`, + `heap_intermediate`, `over_intermediate`, `next_bytes`, `next_text`, `value_decode`, + `check_secret_value_overloads`, `has_encoded_bound` (operations.hpp), `in_place_scratch_limit` + (tokens.hpp), `size_maximum`, `error::input_too_long`, `fuzz_allocations`, `format_paths`, + `traced_and_equal`, `test/support/arena.hpp`, `counting.hpp`, `be16.hpp`, the message test + layout of `refused_size`; against crypto's `formats` plan: `detail::decode_pem`, + `max_decode_input_size`, `test/support/formats_toy.hpp`, `formats_pem_test.cpp` + (the preflight re-reads them as built). +- The encode side, the bytes decode of `over` and the streams are untouched (R12, Global + Constraints' scope). diff --git a/libraries/codecs/openspec/changes/over-in-place/specs/codecs/spec.md b/libraries/codecs/openspec/changes/over-in-place/specs/codecs/spec.md new file mode 100644 index 0000000..4dc2a7e --- /dev/null +++ b/libraries/codecs/openspec/changes/over-in-place/specs/codecs/spec.md @@ -0,0 +1,63 @@ +## ADDED Requirements + +### Requirement: Composition: over decodes a value in place under its decode bound +A decode of a `Value` through `codecs::over`, where `value_codec` states `max_decode_input_size` `D`, SHALL hold its intermediate in place, with no heap, when `D` is at most 4096, whatever the text's type: its size is the smallest bound known at compile time among `D` and the outer link's `max_decoded_size` of a text of a static size. Above 4096, and when the inner value codec states no decode bound, the intermediate MUST be held as the requirement "Composition: over" says (in place for a text of a static size, else from `over`'s allocator). In every case the decode MUST check, in this order: the chain's configuration, the outer link's whole text (its `decoded_size`, whose error is returned first), then the exact size of the intermediate against `D`, returning `codecs::error::input_too_long` when it is past `D` before any intermediate is made, allocated or written, so that the inner value codec never receives more than `D` elements from `over`; then the outer link's decode into the intermediate and the inner value codec's decode, whose errors reach the caller unchanged. With the intermediate in place the decode MUST be `noexcept` when the links' calls are, the typed `decode` with it. A secret operation MUST wipe the intermediate's written bytes by `secure::erase_secret` on every path. The direct `decode(Inner, input)` MUST hand every input to the value codec, whatever its size. `over`'s own value codec MUST NOT state `max_decode_input_size`. + +#### Scenario: A value from a run-time text with no heap +- **WHEN** a value codec of the test's own states `max_encoded_size = 12` and `max_decode_input_size = 16`, and its 12-byte and 16-byte forms are decoded with `codecs::decode(codecs::over{codecs::formats::hex, format}, text)` and through `codecs::over{codecs::formats::armor("RECORD"), format}`, `text` a `std::string_view`, under a counting `operator new` +- **THEN** both forms decode to the value, the counter is zero, and `noexcept(codecs::decode(chain, text))` is true + +#### Scenario: A payload past the bound +- **WHEN** the same chains decode a text whose payload is 17 bytes, and a hex text of 35 characters whose last character is not a hex digit +- **THEN** the first is `codecs::error::input_too_long` with nothing allocated and the value codec not called, and the second is the outer link's `invalid_character`, the outer link's error first + +#### Scenario: A secret value's intermediate is wiped +- **WHEN** a secret value codec with a decode bound of 16 decodes, through `over` from a `std::string_view`, a valid text, a text the inner value codec refuses and a text past the bound, with secure's wipe seam recording +- **THEN** the intermediate's written bytes are erased after the first two, and the third makes no intermediate + +#### Scenario: A bound above the cap +- **WHEN** a value codec states `max_decode_input_size = 4097` and a chain over it with an arena's allocator decodes a run-time text of 4097 bytes, then one of 4098 +- **THEN** the first allocates once from the arena, exactly 4097 bytes, and the second is `input_too_long` with no allocation + +#### Scenario: The fuzz target of the value chain +- **WHEN** the fuzz target `over_value` runs for its bounded time from its corpus +- **THEN** no input crashes or allocates, and every result, value or error, equals the two-step reference's + +## MODIFIED Requirements + +### Requirement: Contract: value_codec for typed values +`codecs::value_codec` SHALL be declared and not defined by the core; a library MUST be able to specialize it for a format and a type it owns with `output` (`output_kind::bytes` or `output_kind::text`), optionally `secret`, a static `max_encoded_size` (the longest encoding its `encode` writes) and a static `max_decode_input_size` (the longest input its `decode` accepts, in the elements it reads: bytes for `output_kind::bytes`, characters for `output_kind::text`; a promise that `decode` refuses every longer input), `encoded_size(format, value)`, `encode(format, value, output_span)` and `decode(format, input) -> result`, encoding only, decoding only, or both, and MAY add overloads of `encoded_size`, `encode` and `decode` taking `detail::secret_tag` first, which the core MUST call in a secret operation, `over` included. A value codec that states both bounds with `max_decode_input_size` below `max_encoded_size` MUST stop the build with a message that its decode would refuse its own longest encoding. Its errors MUST reach the caller unchanged. + +#### Scenario: A typed value round-trips +- **WHEN** a test specializes `value_codec` for a format of its own and a type holding a 16-bit number written as two big-endian bytes, then calls `codecs::encode(format, value)` and `codecs::decode(format, bytes)` +- **THEN** the encoding is `bytes<2>` (the value codec states `max_encoded_size = 2`) and the decode gives the value back + +#### Scenario: A decode bound below the encoded bound +- **WHEN** a program decodes with a value codec that states `max_encoded_size = 12` and `max_decode_input_size = 8` +- **THEN** compilation stops with the core's message that the value codec's `max_decode_input_size` is below its `max_encoded_size` + +#### Scenario: A direct decode is the value codec's +- **WHEN** a value codec with `max_decode_input_size = 16` is given 17 bytes by `codecs::decode(format, bytes)` +- **THEN** the value codec is called and its own error is returned + +### Requirement: Composition: over +`codecs::over` SHALL be a format whose encode encodes with `Inner` and then with `Outer`, and whose decode decodes with `Outer` and then with `Inner`; `Inner` MAY be a codec or a value codec's format, `Outer` MUST be a codec, text feeding `Outer` as bytes. Its `name` MUST be `Outer`'s, `" over "` and `Inner`'s; it MUST be constructible from values by class template argument deduction; it MUST be constant time when every link is and secret when any link's operation is; its intermediate MUST be held in place when its bound is known at compile time: the input's static size (with no cap; the stack it costs is documented), the inner value codec's `max_encoded_size` for an encode, or the inner value codec's `max_decode_input_size` when it is at most 4096 for a decode of a value (the requirement "Composition: over decodes a value in place under its decode bound"); it MUST otherwise come from `over`'s allocator (a third template parameter, `std::allocator` by default, deduced from `over{outer, inner, allocator}`), and MUST be wiped when the chain is secret, each link's secret arithmetic running in a secret chain. With a heap intermediate its exact sizes, its encode and decode and the core's buffer forms over it run the inner link into the intermediate, allocate and MUST NOT be `noexcept`; with a static bound they MUST be `noexcept` and allocate nothing. A fault of a link's configuration MUST be the chain's, the outer link's first, before any data; a fault of a link's encode MUST be the chain's before any `prepare`, the inner link's always and the outer link's on an intermediate in place (with a heap intermediate the outer link's is found by its encode, after `prepare`, codecs' tokens being restored). An intermediate whose exact size is past its bound MUST be refused with `input_too_long` before it is made. `over` MUST stay one-shot. + +#### Scenario: Hex over base64 +- **WHEN** 16 bytes are encoded with `codecs::over{codecs::formats::hex, codecs::formats::base64}` and decoded back +- **THEN** the text is the hex of the base64 text, the bytes come back, and nothing is allocated + +#### Scenario: A value codec with no decode bound +- **WHEN** a value of a value codec that states no `max_decode_input_size` is decoded through `over` from a `std::string_view`, with an arena's allocator in the chain +- **THEN** the intermediate is allocated from the arena, as before this change + +### Requirement: Tests: vectors, fuzzing and lanes +The library's tests SHALL include RFC 7468's examples with OpenSSL's PEM as the armor's oracle, RFC 4648 section 10's vectors, BIP-173's and BIP-350's lists, Bitcoin Core's `base58_encode_decode.json` (read at run time from the superproject's submodule `third_party/libs/bitcoin`, never copied into the library, CODING-GUIDELINES chapter 10), Boost.URL's functions as the oracle of `percent`, the contract's tests (every token, Boost.URL's tokens, the default results' types, typed decodes, `over`, the concepts and the compile-time refusals), the allocation test, the wipe tests, the own lane `constant-time` (memcheck, MemorySanitizer where crypto runs it, dudect with an A/A control, a planted leak that must fail, over every constant-time format, base58's secret operations and a secret value decoded through `over{armor, ...}` from a text of a dynamic size) and the own lane `fuzz`, one target per decoder (the armor's included), one for `over` and one for `over` of a value codec with a decode bound (`over_value`), each asserting no crash, no heap in the buffer form, that what it encodes decodes back to the same bytes, that what decodes encodes back to the same text for the formats whose decode is canonical (case folded where decode takes either case; the armor after normalising its line endings; percent against Boost.URL's `decode`; `over` by bytes alone; `over_value` by value, with no heap at all and against a two-step reference), and that the stream form, split where a prefix the fuzzer controls chooses, gives the one-shot form's bytes and error; the stream tests (every format's stream equal to its one-shot form for every chunking, the protocol's states, a failing call writing nothing, configuration faults first, `pipe`, `drain`, `each`, `buffered`, the guards nesting in a secret pipe), the toy non-byte transformer test, and the allocator tests (an arena resource, a wiping-checking allocator). Every test MUST run on native, wasip2, wasip3 and Emscripten with its `_no_exceptions` twin, and on MSVC and Apple clang as the other libraries. + +#### Scenario: A fuzzed base64 decoder +- **WHEN** the fuzz target of `base64` runs for its bounded time from the vectors' corpus +- **THEN** no input crashes, the buffer form allocates nothing, every accepted text encodes back to itself and every chunking of it gives the one-shot form's bytes and error + +#### Scenario: A secret value through the armor under memcheck +- **WHEN** the constant-time lane marks undefined the payload of an armor decoded through `over` into a secret value of the test's own from a `std::string_view` +- **THEN** no conditional jump and no address depends on it in the armor, the bound's check or the intermediate diff --git a/libraries/codecs/openspec/changes/over-in-place/tasks.md b/libraries/codecs/openspec/changes/over-in-place/tasks.md new file mode 100644 index 0000000..7829270 --- /dev/null +++ b/libraries/codecs/openspec/changes/over-in-place/tasks.md @@ -0,0 +1,24 @@ +# Tasks + +Implemented after crypto's `formats` change merges and before crypto's `hpke`, with crypto's +change `pem-forward` (`libraries/crypto/openspec/changes/pem-forward/`) in the same stream +(design R13). Each task writes its tests first. The plan is `reference/plan.md`. + +## 1. The contract and over + +- [ ] 1.1 The decode bound in the value codec contract: `max_decode_input_size` read by the core, the bounds' order checked at compile time with its message test, `in_place_scratch_limit` shared (D1, R1, R2, R5) +- [ ] 1.2 `over` decodes a value in place under the decode bound: the middle bound of D2, the refusal of D3 before any intermediate, `noexcept` and no heap, the wipe on every path, the cap and the fallback unchanged (D2 to D5, R3 to R9) + +## 2. The own lanes + +- [ ] 2.1 The constant-time lane's path of a secret value through `over{armor, ...}` from a run-time text, and the fuzz target `over_value` with its corpus (D6, D7, R10, R11) + +## 3. The page + +- [ ] 3.1 Composition's intermediate and errors, writing a format's value codec, allocators, the example `over_value.cpp`, the changelog's line (D8, R14) + +## 4. crypto's follow-up, the superproject and the delivery + +- [ ] 4.1 crypto's `pem-forward`: `crypto::decode` of a PEM format forwards to codecs, `detail::decode_pem` removed, its tests and page (crypto's change, its Task P1; design R13) +- [ ] 4.2 The superproject: both gitlinks in one pull request +- [ ] 4.3 Every lane on the final head (native clang and gcc, wasip2, wasip3, Emscripten, the doc, MSVC 14.3 and 14.5 x64 debug, arm64 14.5's timing set for crypto, the constant-time and fuzz lanes of codecs and crypto, the macOS and Linux lints), pull requests in order (codecs, crypto, superproject, proposals), merges, one CI at the end From c68d15f0f705c1fc311deab4a92f55a6fc740105 Mon Sep 17 00:00:00 2001 From: R Date: Mon, 30 Nov 2026 19:49:10 -0300 Subject: [PATCH 02/10] crypto: pem-forward, PEM decodes through codecs' over in place, the two-step decode removed (design, spec, tasks, plan) --- README.md | 2 + .../changes/pem-forward/.openspec.yaml | 11 +++ .../openspec/changes/pem-forward/design.md | 70 +++++++++++++ .../openspec/changes/pem-forward/proposal.md | 50 ++++++++++ .../changes/pem-forward/reference/plan.md | 97 +++++++++++++++++++ .../changes/pem-forward/specs/crypto/spec.md | 24 +++++ .../openspec/changes/pem-forward/tasks.md | 13 +++ 7 files changed, 267 insertions(+) create mode 100644 libraries/crypto/openspec/changes/pem-forward/.openspec.yaml create mode 100644 libraries/crypto/openspec/changes/pem-forward/design.md create mode 100644 libraries/crypto/openspec/changes/pem-forward/proposal.md create mode 100644 libraries/crypto/openspec/changes/pem-forward/reference/plan.md create mode 100644 libraries/crypto/openspec/changes/pem-forward/specs/crypto/spec.md create mode 100644 libraries/crypto/openspec/changes/pem-forward/tasks.md diff --git a/README.md b/README.md index 78acd23..026da55 100644 --- a/README.md +++ b/README.md @@ -49,6 +49,7 @@ tag is placed. | beast | [genesis](libraries/beast/openspec/changes/genesis) | beast: existing Boost.Beast applications on WASIp2, WASIp3 and Emscripten | wrapper | implementing | | 2026-11-06 | [code](https://github.com/webcpporg/beast) | | cobalt | [genesis](libraries/cobalt/openspec/changes/genesis) | cobalt: existing Boost.Cobalt applications on native, browsers and WASIp2/P3 | wrapper | implementing | | 2026-11-06 | [code](https://github.com/webcpporg/cobalt) | | codecs | [genesis](libraries/codecs/openspec/changes/genesis) | codecs: one contract for turning bytes and values into text and back, one header per format, tokens like Boost.URL | own | implementing | | 2026-11-24 | [code](https://github.com/webcpporg/codecs) | +| codecs | [over-in-place](libraries/codecs/openspec/changes/over-in-place) | codecs: over decodes a value in place under the inner value codec's decode bound | own | accepted | | 2026-11-30 | | | config | [genesis](libraries/config/openspec/changes/archive/2026-10-09-genesis) | config: webcpp's configuration, the target, exceptions and version every library includes first | own | implemented | 0.1.0 | 2026-10-09 | [code](https://github.com/webcpporg/config/tree/2fad162) | | config | [timing-guard](libraries/config/openspec/changes/archive/2026-11-24-timing-guard) | config: one DIT timing guard for every webcpp library, moved from crypto and hash, Windows on ARM64 covered | own | withdrawn | | 2026-11-24 | | | crypto | [genesis](libraries/crypto/openspec/changes/genesis) | crypto: authenticated encryption, randomness and secp256k1 over C backends | wrapper | implementing | | 2026-10-11 | [code](https://github.com/webcpporg/crypto) | @@ -56,6 +57,7 @@ tag is placed. | crypto | [hpke](libraries/crypto/openspec/changes/hpke) | crypto: HPKE (RFC 9180) composed from crypto's own primitives, readable names, the mode from the arguments | wrapper | proposed | | 2026-11-23 | | | crypto | [formats](libraries/crypto/openspec/changes/formats) | crypto: one encode and one decode for every key and signature format, the format as a value | wrapper | accepted | | 2026-11-22 | | | crypto | [foundation](libraries/crypto/openspec/changes/foundation) | crypto: the cryptographic foundation, every backend in full, one default per family and a browser backend | wrapper | accepted | | 2026-11-14 | | +| crypto | [pem-forward](libraries/crypto/openspec/changes/pem-forward) | crypto: PEM decodes through codecs' over in place, crypto's two-step decode removed | wrapper | accepted | | 2026-11-30 | | | crypto | [api-gaps](libraries/crypto/openspec/changes/api-gaps) | crypto: the API gaps of version 0.2 closed, and dudect judged on hosted runners | wrapper | implementing | | 2026-11-20 | [code](https://github.com/webcpporg/crypto) | | crypto | [data-independent-timing](libraries/crypto/openspec/changes/data-independent-timing) | crypto: the library sets arm64's DIT around every cryptographic operation | wrapper | implementing | | 2026-11-20 | [code](https://github.com/webcpporg/crypto) | | crypto | [unified-sign](libraries/crypto/openspec/changes/unified-sign) | crypto: one sign and verify on every curve, the scheme always named, the key pair contract and four forms of each operation | wrapper | implementing | | 2026-11-22 | [code](https://github.com/webcpporg/crypto) | diff --git a/libraries/crypto/openspec/changes/pem-forward/.openspec.yaml b/libraries/crypto/openspec/changes/pem-forward/.openspec.yaml new file mode 100644 index 0000000..ce194a0 --- /dev/null +++ b/libraries/crypto/openspec/changes/pem-forward/.openspec.yaml @@ -0,0 +1,11 @@ +schema: spec-driven +created: 2026-11-30 +webcpp: + library: crypto + title: "crypto: PEM decodes through codecs' over in place, crypto's two-step decode removed" + kind: wrapper + port_of: null + status: accepted + release: null + implementation: null + decided: 2026-11-30 diff --git a/libraries/crypto/openspec/changes/pem-forward/design.md b/libraries/crypto/openspec/changes/pem-forward/design.md new file mode 100644 index 0000000..55af4dc --- /dev/null +++ b/libraries/crypto/openspec/changes/pem-forward/design.md @@ -0,0 +1,70 @@ +## Context + +After crypto's `formats` change (`libraries/crypto/openspec/changes/formats/`): `crypto::decode` +checks the pair and, for a `pem_t` format given a text, calls `detail::decode_pem`, +which holds `secure::timing_guard` for a secret pair, decodes the armor (`format.outer`) through +codecs' buffer form into `std::array>`, maps +codecs' `output_too_small` to `crypto::error::invalid_encoding`, decodes the DER through +`codecs::decode(format.inner, ...)` and wipes the buffer of a secret pair (R24). Every +other format forwards to `codecs::decode(format, input)`. `codecs::decode` of a PEM format +from a `std::string_view` allocates a heap intermediate, which `formats`' guide and tests state as +"the documented difference" (its Risks). + +codecs' change `over-in-place` makes `over`'s value decode hold its intermediate in place under +the inner value codec's `max_decode_input_size` (at most 4096; crypto's largest is 138), refuse an +intermediate past it before it is made, wipe it in a secret chain, and be `noexcept` when the +links' calls are. Both changes run in one stream (codecs' design R13). + +## Goals / Non-Goals + +**Goals:** one decode path for every crypto format; no heap and `noexcept` for PEM through both +verbs; the same values and errors through `crypto::decode` and `codecs::decode`. + +**Non-goals:** any change to the DER formats, their bounds, PKCS#8 v2 (still deferred, `formats`' +owner decision 23), the encode side. + +## Decisions + +- **R1. Ruling: `crypto::decode` forwards every format, PEM included, to + `codecs::decode(format, input)` after the pair's check; `detail::decode_pem` is removed; + `formats`' R24 is superseded** - why: codecs' `over` now does R24's two steps, in the same + order (the armor's configuration, its structure and base64, the bound, the DER) and with the + same wipe - cost if wrong: none; restoring the two steps is R24's 20 lines. +- **R2. Ruling: a PEM payload past the decode bound is `codecs::error::input_too_long` (codecs' + Q1, recommendation A)** - why: it is codecs' refusal of `over`'s intermediate, and one error + through both verbs keeps `formats`' rule that `crypto::decode` and `codecs::decode` give the + same values and errors; with Q1's C, crypto's value codecs state + `decode_input_too_long = crypto::error::invalid_encoding` instead and this ruling's error stays + `invalid_encoding` - cost if wrong: the sentence of the spec and three assertions. +- **R3. Ruling: `crypto::decode` checks `noexcept(codecs::decode(format, input))` at compile + time** (`static_assert`, message "webcpp::crypto: a decode of a crypto format allocates nothing + and cannot throw: the inner format states max_decode_input_size") - why: the forward is + `noexcept` only because every crypto value codec states a bound of at most 4096; the check + keeps a later pair from silently allocating under a `noexcept` verb - cost if wrong: none. +- **R4. Ruling: crypto's own bound checks stay** (`formats`' R37: every crypto value codec that + decodes states `max_decode_input_size`, equal to `max_encoded_size` until a change rules + otherwise); its sentence that codecs ignores the member is superseded: codecs reads it - why: + crypto's equality is stricter than codecs' order check (codecs' R2) - cost if wrong: none. +- **R5. Ruling: the secret path keeps its guards and wipe through codecs** - why: codecs engages + `secure::timing_guard` for a secret operation and wipes `over`'s intermediate; crypto's value + codecs hold their own guard (`formats`' R35); the timing coverage tests that named + `detail::decode_pem` drop it - cost if wrong: none. +- **R6. Ruling: this change runs in codecs' `over-in-place` stream as its Task P1, merged right + after codecs, the superproject moving both gitlinks in one pull request** - why: codecs' change + alone makes `formats`' tests of `codecs::decode` of a PEM fail (it no longer allocates, and the + error of a long payload changes) - cost if wrong: none. + +## Risks / Trade-offs + +- **The error of an over-long PEM payload changes** (R2), for a program that compared it with + `invalid_encoding`. The guide's errors page says it. + +## Migration Plan + +codecs' `over-in-place` Tasks 1 to 4, then this change's Task P1 on branch `crypto/pem-forward` of +webcpporg/crypto, then the superproject's gitlinks and the delivery of codecs' plan (its Tasks 5 +and 6). + +## Open Questions + +None of its own: R2 follows codecs' Q1. diff --git a/libraries/crypto/openspec/changes/pem-forward/proposal.md b/libraries/crypto/openspec/changes/pem-forward/proposal.md new file mode 100644 index 0000000..87c6e98 --- /dev/null +++ b/libraries/crypto/openspec/changes/pem-forward/proposal.md @@ -0,0 +1,50 @@ +## Why + +crypto's `formats` change decodes a PEM format in two steps of its own (its design R24): the armor +through codecs' buffer form into a stack buffer of the inner format's decode bound, +`max_decode_input_size`, then the inner value codec, because codecs' `over` put the DER on the heap +for a PEM text of a dynamic size. codecs' change `over-in-place` +(`libraries/codecs/openspec/changes/over-in-place/`, owner decision 28 there, approved +2026-11-30 as crypto `formats`' question Q1) makes `over` decode a value in place under exactly +that bound, so crypto's two steps are now what codecs does: R24's cost line said the path then +becomes a forward. This change makes it one. + +## What Changes + +- **`crypto::decode` of a PEM format forwards to `codecs::decode(format, text)`**, as it + does for every other format; `detail::decode_pem` and its stack buffer are removed. The check of + the pair (crypto's list, the curves' headers, the refusal reasons) is unchanged. +- **The verb states its promise**: `crypto::decode` checks at compile time that the codecs call it + forwards to is `noexcept`, so that a crypto pair whose decode would allocate stops the build. +- **The error of a PEM payload past the decode bound** is codecs' `input_too_long` (codecs' + design Q1, recommendation A) through both `crypto::decode` and `codecs::decode`, where `formats` + said `invalid_encoding`; the DER formats' errors are unchanged. +- **Tests:** `formats_pem_test` and the curves' PEM cases: `codecs::decode` of a PEM text + allocates nothing (it allocated: the documented difference is gone), the toy's 17 bytes and + an RSA public key's PEM under `PUBLIC KEY` are `input_too_long`, the DER buffer's wipe is now + codecs' intermediate's. +- **The page:** the formats chapter and the errors page lose the documented difference and gain + the error; the changelog's source entry. + +## Capabilities + +### New Capabilities + +None. + +### Modified Capabilities + +- `crypto`: PEM's decode through codecs' `over`, in place, with codecs' error past the bound. + +## Impact + +- **Kind:** a wrapper (`"port-of": null`), as crypto's genesis. +- **Breaking:** a PEM whose payload is longer than the inner format's decode bound is + `codecs::error::input_too_long` instead of `crypto::error::invalid_encoding` (with codecs' Q1 + answered A); no API is removed but the private `detail::decode_pem`. +- **Implementation:** webcpporg/crypto (`include/webcpp/crypto/formats.hpp`, its tests, the + guide, the changelog's source entry), with codecs' `over-in-place` in the same stream and one + superproject pull request for both gitlinks. The task is `reference/plan.md`'s Task P1, run in + codecs' `over-in-place` stream after its Task 4. +- **Status:** follows the owner's approval of 2026-11-30 (crypto `formats`' Q1: "after which + crypto's two steps become a forward"); accepted with `reference/plan.md`. diff --git a/libraries/crypto/openspec/changes/pem-forward/reference/plan.md b/libraries/crypto/openspec/changes/pem-forward/reference/plan.md new file mode 100644 index 0000000..8379d83 --- /dev/null +++ b/libraries/crypto/openspec/changes/pem-forward/reference/plan.md @@ -0,0 +1,97 @@ +# crypto pem-forward Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** `crypto::decode` of a PEM format forwards to `codecs::decode`, which after codecs' +`over-in-place` decodes in place with no heap; crypto's two-step `detail::decode_pem` goes. + +**Architecture:** one task, Task P1, run in codecs' `over-in-place` stream after its Task 4 and +before its Tasks 5 (the superproject) and 6 (the delivery), which deliver this change too. The +stream's paths, commands, lanes, lint step, preflight and Global Constraints are codecs' plan's +(`libraries/codecs/openspec/changes/over-in-place/reference/plan.md`), binding here. + +**Tech Stack:** as codecs' plan, plus crypto's backends (libsodium, BearSSL, OpenSSL 3.5.9, +libsecp256k1, the superproject's pins) and node's WebCrypto on Emscripten. + +**Spec:** this change, `libraries/crypto/openspec/changes/pem-forward/` (`design.md` R1 to R6, +`specs/crypto/spec.md`, binding), codecs' `over-in-place` (its design D2, D3, D5, Q1), crypto's +`formats` design R24, R35, R37. + +**Open for the owner:** codecs' Q1. This plan follows its recommendation A: a PEM payload past the +bound is `codecs::error::input_too_long`. With Q1's C, Step 3 also adds +`static constexpr crypto::error decode_input_too_long = crypto::error::invalid_encoding;` to every +crypto value codec that decodes (its curves' `formats.hpp`, the toy) and the tests below keep +`invalid_encoding`; with B, the DER tests that refuse an input longer than the bound change to +`input_too_long` as well (P-256's 150-byte PKCS#8 among them). + +--- + +### Task P1: crypto's PEM decode forwards to codecs + +Model tier: standard. Size: M. + +**Files:** (as `formats` built them; the codecs plan's preflight re-reads them) +- Modify: `libs/crypto/include/webcpp/crypto/formats.hpp` +- Modify: `libs/crypto/test/formats_pem_test.cpp`, the curves' PEM cases (Ed25519's + `pem_variants`, P-256's Review Focus 5 case of `formats`' Task 8), `test/support/format_checks.hpp` + if it states the heap difference, the timing coverage tests that name `decode_pem` +- Modify: the guide's formats chapter and errors page, the changelog's source entry, and + `doc/tables/crypto.json` if it lists `decode_pem`; the generated files rerun + +**Interfaces:** + +```cpp +namespace webcpp::crypto { +// Checks the pair as before (formats' Task 4), then: +template +[[nodiscard]] codecs::result decode(Format const& format, Input const& input) noexcept { + // ... the pair's check, unchanged ... + static_assert(noexcept(codecs::decode(format, input)), + "webcpp::crypto: a decode of a crypto format allocates nothing and cannot throw: " + "the inner format states max_decode_input_size"); + return codecs::decode(format, input); +} +} +// Removed: crypto::detail::decode_pem. +``` + +- [ ] **Step 1: Write the failing tests.** + - `formats_pem_test.cpp` over the toy: under the counter, `codecs::decode(pem(spki), + std::string_view)` and `codecs::decode(pem(pkcs8), std::string_view)` allocate + nothing (the assertion that it allocated, "the documented difference", is removed); the + 16-byte "version 2" `pkcs8` decodes through both verbs; 17 bytes are + `codecs::error::input_too_long` through both (Q1); the 294-byte payload under `PUBLIC KEY` + `input_too_long` through both, the counter zero; the armor of no bytes still the toy's + `invalid_encoding` (the value codec's own refusal of 0 bytes); `pem(pkcs8)`'s decode records + the erase of codecs' intermediate (12 or 16 bytes) through secure's + `WEBCPP_SECURE_TEST_WIPE_RECORD`; `crypto::decode` and `codecs::decode` give the same values + and errors on every text of the test (unchanged rule); + `static_assert(noexcept(codecs::decode(formats::pem(formats::spki), std::string_view{})))`. + - The curves' PEM cases: P-256's RSA public key PEM (Review Focus 5) `input_too_long` through + both verbs with no heap; Ed25519's OpenSSL PEM of a private key through `codecs::decode` with + no heap (the spec's scenario). + - A message test `decode_not_noexcept` (crypto's message layout, its `crypto.json` entry and + MSVC twin where crypto builds one): a toy pair of the test's own whose value codec states no + `max_decode_input_size`, its `pem_t` decoded through `crypto::decode` from a + `std::string_view`, stops at R3's `static_assert` (if `formats`' R37 check fires first for such + a pair, the test pins the order: R37's message first, and R3's is then pinned with a pair + whose bound is above 4096). +- [ ] **Step 2: Run, expect failure.** `B2 toolset=clang libs/crypto/test//formats_pem`: with + codecs' Tasks 1 to 4 in place the heap assertions already flip, while the errors still come + from `detail::decode_pem` (`invalid_encoding`) and the message test compiles. +- [ ] **Step 3: Implement** the forward and the `static_assert`; delete `detail::decode_pem` and + every name only it used; the guide (formats chapter: PEM decodes in place through codecs, the + "documented difference" removed; errors page: `codecs::error::input_too_long` for a PEM payload + past the bound), the changelog's source entry (`* Changed PEM decode: through codecs' over, in + place; a payload past the bound is codecs' input_too_long.`), `crypto.json` and its generated + files through `generate.py`. +- [ ] **Step 4: Run.** The five local lanes over `libs/crypto/test libs/crypto/example`; the doc; + `generate.py --check`; MSVC 14.3 and 14.5 x64 debug over `libs/crypto/test//formats_pem` and + the curves' formats tests; arm64 14.5 over crypto's timing set (a guarded function removed); + `$W/heavy.sh codecs-over $W/codecs-over/ct-run/linux.sh crypto constant-time` (the secret PEM + paths now through codecs' `over`) and `... crypto fuzz` (the PEM targets; a target that + asserted `invalid_encoding` for a long payload asserts `input_too_long`). Expected: pass. +- [ ] **Step 5: Commit, lint.** `crypto: PEM decodes through codecs' over in place; the two-step decode_pem removed`. Lint step. + +**Lanes:** the five local lanes, the doc, MSVC 14.3 and 14.5 x64 debug, arm64 14.5's timing set, +crypto's constant-time and fuzz lanes. diff --git a/libraries/crypto/openspec/changes/pem-forward/specs/crypto/spec.md b/libraries/crypto/openspec/changes/pem-forward/specs/crypto/spec.md new file mode 100644 index 0000000..7a306a3 --- /dev/null +++ b/libraries/crypto/openspec/changes/pem-forward/specs/crypto/spec.md @@ -0,0 +1,24 @@ +## MODIFIED Requirements + +### Requirement: Formats: PEM is codecs' armor over a DER format +`crypto::formats::pem(F)` SHALL encode RFC 7468's armor of `F`'s DER through codecs' `formats::armor`: lines of 64 characters, each ended by a line feed, the label of `F`. Decoding SHALL accept what codecs' armor accepts (lines ended by a line feed or by a carriage return and a line feed, the last line ending optional, nothing before the BEGIN line or after the END line), refuse the armor's faults with codecs' errors (`invalid_prefix` for a boundary or a label other than `F`'s, `invalid_length` for a line, `invalid_character` and `invalid_padding` for the base64), and refuse a DER that `F`'s decoder refuses with crypto's error. `crypto::decode` of a PEM format MUST forward to `codecs::decode(format, text)` after the pair's check, as for every format, and both MUST decode in place, with no heap and `noexcept`, through codecs' `over`, whose intermediate holds the DER under `F`'s decode bound, `max_decode_input_size`, and is wiped after a `pkcs8`; a payload longer than that bound MUST be `codecs::error::input_too_long` through both, before the DER is written. `crypto::decode` MUST stop the build when the codecs call it forwards to is not `noexcept`, and `crypto::detail::decode_pem` MUST NOT exist. ``, the namespace `crypto::pem`, the family `families::pem` and the target `/webcpp/crypto//pem-default` MUST NOT exist. + +#### Scenario: OpenSSL's PEM +- **WHEN** the PEM texts OpenSSL writes for an Ed25519, an X25519, a P-256 and a secp256k1 key, public and private, are decoded with `crypto::decode` and encoded again +- **THEN** each decodes, and encoding gives OpenSSL's text byte for byte + +#### Scenario: CRLF lines +- **WHEN** a P-256 public key's PEM is decoded with every line feed replaced by a carriage return and a line feed +- **THEN** it decodes to the same key + +#### Scenario: A certificate given as a key +- **WHEN** a text whose label is `CERTIFICATE` is decoded with `crypto::formats::pem(crypto::formats::spki)` +- **THEN** it returns `codecs::error::invalid_prefix` + +#### Scenario: An RSA key's PEM given as a P-256 key +- **WHEN** the PEM of an RSA public key (294 bytes of DER) under `PUBLIC KEY` is decoded with `crypto::decode(crypto::formats::pem(crypto::formats::spki), text)` and with `codecs::decode` of the same format and text, `text` a `std::string_view`, under a counting `operator new` +- **THEN** both return `codecs::error::input_too_long`, nothing is allocated and nothing is written past 138 bytes + +#### Scenario: codecs' decode of a PEM allocates nothing +- **WHEN** `codecs::decode(crypto::formats::pem(crypto::formats::pkcs8), text)` decodes OpenSSL's PEM of an Ed25519 private key from a `std::string_view` under a counting `operator new` +- **THEN** it gives the key pair crypto's verb gives, the counter is zero, and the 48-byte intermediate is wiped diff --git a/libraries/crypto/openspec/changes/pem-forward/tasks.md b/libraries/crypto/openspec/changes/pem-forward/tasks.md new file mode 100644 index 0000000..4d07da8 --- /dev/null +++ b/libraries/crypto/openspec/changes/pem-forward/tasks.md @@ -0,0 +1,13 @@ +# Tasks + +Run in codecs' `over-in-place` stream after its Task 4, merged right after codecs, the +superproject moving both gitlinks together (design R6). The task writes its tests first. The plan +is `reference/plan.md`. + +## 1. The forward + +- [ ] 1.1 `crypto::decode` forwards PEM to codecs, `detail::decode_pem` removed, the `noexcept` check; the PEM tests of the toy and the curves (no heap through `codecs::decode`, `input_too_long` past the bound, codecs' wipe); the guide, the errors page and the changelog's source entry (R1 to R5) + +## 2. The delivery + +- [ ] 2.1 Delivered by codecs' `over-in-place` plan, its Tasks 5 and 6: crypto's pull request after codecs', the superproject's with both gitlinks From 09359ea743224c6e604045cfd567130c55fcc793 Mon Sep 17 00:00:00 2001 From: R Date: Mon, 30 Nov 2026 21:45:59 -0300 Subject: [PATCH 03/10] codecs: over-in-place records owner decision 29, the decode bound enforced by the core on every path (input_too_long), its acceptance contract and the direct-path tests --- .../openspec/changes/over-in-place/design.md | 114 ++++++++-------- .../changes/over-in-place/proposal.md | 30 +++-- .../changes/over-in-place/reference/plan.md | 125 +++++++++++++----- .../over-in-place/specs/codecs/spec.md | 31 ++++- .../openspec/changes/over-in-place/tasks.md | 2 +- 5 files changed, 197 insertions(+), 105 deletions(-) diff --git a/libraries/codecs/openspec/changes/over-in-place/design.md b/libraries/codecs/openspec/changes/over-in-place/design.md index 24fb7ad..7c7ed4b 100644 --- a/libraries/codecs/openspec/changes/over-in-place/design.md +++ b/libraries/codecs/openspec/changes/over-in-place/design.md @@ -1,31 +1,11 @@ ## Open questions for the owner -Two choices change the public contract and nothing decided so far answers them. The plan is -written with the recommendation of each; the places that change with the answer are marked -"(Q1)" or "(Q2)" in the plan. - -1. **Q1. The error of a payload past the decode bound.** The intermediate of `over` cannot hold - more than the inner value codec's decode bound, so a text whose payload is longer is refused - by codecs before the inner value codec sees a byte; codecs must name that error. - - **A (recommended): `codecs::error::input_too_long`, in `over` alone.** It is what `over` - already returns for an intermediate past a bound known at compile time (over.hpp's - `past_bound`, for a text of a static size), and the error's own message, "the input is - longer than the format or the buffer allows". The direct `decode(format, bytes)` - still hands every input to the value codec. Cost: crypto's PEM of a payload past the bound - becomes `codecs::error::input_too_long` where crypto's `formats` spec says - `invalid_encoding`; crypto's `pem-forward` changes that sentence and its tests (an RSA - public key's PEM under `PUBLIC KEY`, the toy's 17 bytes), and the DER formats keep their - errors. - - **B: `input_too_long`, enforced by the core in every decode of a value codec that states a - bound,** the direct one too. One rule everywhere; but crypto's DER errors change as well (a - P-256 PKCS#8 of 150 bytes, refused today with `invalid_encoding` by crypto's spec, would be - `input_too_long`), a larger churn in crypto for no gain in `over`. - - **C: the value codec names its refusal**, an optional - `static constexpr` error enumerator `decode_input_too_long` (any enumeration that is a - `boost::system` error code enumeration), `input_too_long` when absent; crypto states its - `invalid_encoding`, and its errors do not change at all. Cost: one more optional member in - the contract, for one error. -2. **Q2. The cap on the in-place intermediate of a decode bound.** The genesis puts an +One choice changes the public contract and nothing decided so far answers it. The plan is +written with its recommendation; the places that change with the answer are marked "(Q2)" in the +plan. (Q1, the error of an input past the decode bound, was answered by the owner on 2026-11-30: +owner decision 29.) + +1. **Q2. The cap on the in-place intermediate of a decode bound.** The genesis puts an intermediate of a static bound in place with no cap (its R3): the caller chose a static input and can pass a view of a dynamic extent to reach the heap. A decode bound is the format author's, and the caller has no such escape; a value codec of a certificate or of a JSON @@ -79,7 +59,8 @@ guide and tests state as "the documented difference". ## Goals / Non-Goals -**Goals:** `codecs::decode(over{outer, inner}, text)` of a text of a dynamic size, when the +**Goals:** one error, codecs' `input_too_long`, for every input past a value codec's decode +bound, on every path (owner decision 29); `codecs::decode(over{outer, inner}, text)` of a text of a dynamic size, when the inner value codec states a decode bound, holds its intermediate in place, allocates nothing and is `noexcept` when the links' calls are; the inner value codec never receives more than its decode bound from `over`; a secret intermediate is wiped on every path; crypto's PEM decode becomes a @@ -93,8 +74,8 @@ codec's `over` (decision 17 of the genesis: a value codec has no transformer); P stays deferred (crypto's owner decision 23). **Anti-goals:** a heap allocation where the decode bound is known and small; a stack array sized -by a bound the caller cannot see or escape; a secret byte of the intermediate left unwiped; a -change of the errors a value codec returns to a direct decode. +by a bound the caller cannot see or escape; a secret byte of the intermediate left unwiped; two +errors for one input past the bound depending on the path it took. ## Owner decisions (binding) @@ -107,6 +88,14 @@ change of the errors a value codec returns to a direct decode. bound is refused before it is written, as no inner decoder accepts it; codecs adopts crypto's name for the member, after which crypto's two steps become a forward. +29. **The decode bound is enforced by the core on every path** (2026-11-30, this design's + question Q1, option B): the error code must always be the same + whatever the path, so the same file read as PEM or as direct DER gives the same error. + `codecs::decode` of a value codec that states `max_decode_input_size` refuses an input longer + than it with `codecs::error::input_too_long` before the value codec sees it, directly + (`decode(format, input)`, every input type a caller's buffer can be, public and + secret) and through `over` alike. + The numbers 1 to 27 are the genesis'; this change continues them. ## Decisions @@ -125,7 +114,12 @@ template <> struct value_codec`, and `detail::value_decode_bound()` (the bound, or `std::dynamic_extent` when absent); there is no public reader, as there is none for `max_encoded_size` (R1). When a value codec states both @@ -150,17 +144,31 @@ case. ### D3. The refusal past the bound -The order of a value decode through `over` becomes: +**Directly** (owner decision 29): `decode(format, input)` of a value codec with a bound +checks, in this order, the format's configuration, then the input's size against the bound +(`input_too_long`, the value codec not called), then calls the value codec. The check lives in +the core's one funnel of every value decode, `detail::value_decode` (secrecy.hpp), so the typed +decode of bytes or of text, of an input of a dynamic or a static size (a `std::span`, a +`std::vector`, a `std::array`, a byte array, a `secure::secret`, `text`, `bytes`), public or +secret (by the value, the value codec, or the requested type), and `over`'s call of its inner value +codec all pass it; an input whose static size is at most the bound skips it at compile time. The +core has no buffer form that decodes into a value: a value decode's buffer is the caller's input, +each of whose types above is tested; the buffer forms of a codec (`decode(format, text, +std::span)`) have no value codec and are unchanged. + +**Through `over`**, the order of a value decode becomes: 1. the chain's configuration (the outer link's first), as the genesis; 2. the outer link's `decoded_size`, which checks the whole text and returns the outer link's data error (outer before inner, the genesis' B23); -3. **new:** an exact size past the inner value codec's decode bound is `input_too_long` (Q1); +3. **new:** an exact size past the inner value codec's decode bound is `input_too_long` (owner + decision 29, the same error as the direct path); 4. an exact size past the intermediate's bound known at compile time is `input_too_long` (genesis; with D2 this can now only be the static text's own bound, which an exact size never passes, so it stays as a guard); 5. the intermediate is made (in place, or from the allocator) and the outer link decodes into it; -6. the inner value codec decodes the written bytes and its errors reach the caller unchanged. +6. the inner value codec decodes the written bytes (through `detail::value_decode`, whose check + cannot fail there) and its errors reach the caller unchanged. Nothing is written, allocated or wiped before step 5, so a refusal at step 3 costs no allocation, even where the intermediate would have been on the heap. @@ -186,14 +194,15 @@ and runs both links' secret arithmetic (genesis R7) as before. ### D6. Constant time -The one new branch compares the outer link's exact decoded size, a length, with a constant. +The two new branches compare a length with a constant: the direct input's size, and the outer link's exact decoded size. Lengths are public in codecs' model (the genesis' D12 and the spec's constant-time requirement: "the input's length, the output's length ... MAY be public"), and the size is computed by the outer link's `decoded_size` as before. The constant-time lane gains the path that exercises it with a secret: a secret test value decoded through `over{formats::armor("TEST SECRET"), ...}` from a `std::string_view`, its payload marked undefined, under memcheck and MemorySanitizer, which checks that no branch and no address depends on the payload in the outer link, in the bound's -check and in the copy into the intermediate. No dudect case is added: the code timed is the +check and in the copy into the intermediate; and the direct secret decode of the same value from +bytes of 16 and of 17 (refused) bytes. No dudect case is added: the code timed is the armor's decode, which the lane's armor case already measures; the inner value codec is the test's own. @@ -205,8 +214,8 @@ with a decode bound of 16 and an encoded bound of 12, the rest is the text, give `std::string_view`. Each input checks: no crash; no allocation at all (the global counter, since the intermediate is in place; under AddressSanitizer a write past the 16 bytes is the sanitizer's); the result equals a two-step reference (the outer link's own decode into a -`std::vector`, then `input_too_long` past 16 bytes, else the value codec's own decode of those -bytes), value or error; the secret twin of the value gives the same; what decodes encodes back to +`std::vector`, then `input_too_long` past 16 bytes, else a model of the value codec written in the +target), value or error, and the direct decode of the reference's bytes gives the same; the secret twin of the value gives the same; what decodes encodes back to a text that decodes to the same value. Its corpus seeds: the empty text, the 12-byte and the 16-byte forms, 17 bytes, an outer error past the 16th byte, an armor with CRLF lines. @@ -235,13 +244,14 @@ lane as every example. The changelog's line under "Unreleased". if wrong: a value codec that writes encodings it cannot read would need the check removed. - **R3. Ruling: the middle bound is D2's table** - why: owner decision 28, and the smaller bound is always the safer stack - cost if wrong: none for crypto's bounds. -- **R4. Ruling: a size past the bound is refused after the outer link's errors and before the - intermediate is made, with `input_too_long` (Q1, recommendation A), in `over` alone; the direct - decode of a value codec is unchanged** - why: the intermediate cannot be written past its - bound, and refusing before the allocation also bounds the heap path; `over` already answers an - intermediate past a compile-time bound with `input_too_long`; a direct decode gives the value - codec the bytes and has no reason to override its error - cost if wrong: the error changes in - one function, and crypto's `pem-forward` sentence and tests follow (Q1's B or C). +- **R4. Ruling: an input past the bound is `input_too_long` on every path (owner decision 29): + directly in `detail::value_decode`, before the value codec; through `over` after the outer + link's errors and before the intermediate is made** - why: the owner wants one error whatever + the path; `over` already answers an intermediate past a compile-time bound with + `input_too_long`, the error's message is "the input is longer than the format or the buffer + allows", and refusing before the allocation also bounds the heap path - cost if wrong: the check + is one comparison in one funnel; crypto's `pem-forward` changes its tests and spec for the + over-long inputs of its DER, raw and PEM formats. - **R5. Ruling: a decode bound above 4096 bytes keeps the heap intermediate (Q2, recommendation A), reusing `detail::in_place_scratch_limit`, moved from tokens.hpp to size_maximum.hpp so that `over.hpp` and `tokens.hpp` share it** - why: the owner's own threshold for `assign_to`'s @@ -302,13 +312,13 @@ lane as every example. The changelog's line under "Unreleased". ## Risks / Trade-offs -- **The error of a long PEM payload changes** for a caller of `codecs::decode` (Q1): from the - inner value codec's error to `input_too_long`. Only crypto's PEM exists today, and crypto's - `pem-forward` changes with it. -- **A decode bound is a promise the core now relies on for memory**: a value codec that states - a bound and accepts a longer input through its direct decode is inconsistent; through `over` - it simply refuses the longer one. The spec states the promise; crypto's toy and its pairs are - checked by their tests. +- **The error of an input past a decode bound changes** (owner decision 29): from the value + codec's own error to `input_too_long`, directly and through `over`. Only crypto's value codecs + state a bound today, and crypto's `pem-forward` changes with it (its over-long DER, raw and PEM + inputs). +- **A decode bound is an acceptance contract**: a bound below the longest valid input refuses + that input on every path, without the value codec seeing it. Codecs' tests and crypto's + `pem-forward` pin, per value codec, that the largest valid input decodes. - **The stack**: up to 4096 bytes per level of a chain whose inner value codec states a bound, in the frame of the decode; crypto's largest is 138. @@ -323,4 +333,4 @@ stream under the owner's standing instruction, one CI at the end. Then `hpke`. ## Open Questions -Q1 and Q2, at the top of this design. Nothing else is open. +Q2, at the top of this design. Q1 is answered (owner decision 29). Nothing else is open. diff --git a/libraries/codecs/openspec/changes/over-in-place/proposal.md b/libraries/codecs/openspec/changes/over-in-place/proposal.md index a82c915..bb59d40 100644 --- a/libraries/codecs/openspec/changes/over-in-place/proposal.md +++ b/libraries/codecs/openspec/changes/over-in-place/proposal.md @@ -22,11 +22,16 @@ right after `formats` and before `hpke`. This is that change. ## What Changes -- **The decode bound joins codecs' value codec contract.** `value_codec` MAY state - `static constexpr std::size_t max_decode_input_size`, the longest encoded input its `decode` - accepts, in bytes for a value codec of bytes and in characters for one of text; codecs adopts - crypto's name (crypto's R37). When a value codec states both bounds, `max_decode_input_size` - must not be below `max_encoded_size`, a check the core makes at compile time. +- **The decode bound joins codecs' value codec contract, enforced on every path.** + `value_codec` MAY state `static constexpr std::size_t max_decode_input_size`, the + longest encoded input its `decode` accepts, in bytes for a value codec of bytes and in + characters for one of text; codecs adopts crypto's name (crypto's R37). The core refuses every + longer input with `codecs::error::input_too_long` before the value codec sees it, in the direct + `decode(format, input)` (any input type, public or secret) and through `over` alike, so + that the error is the same whatever the path (owner decision 29, 2026-11-30): the bound is the + value codec's acceptance contract. When a value codec states both bounds, + `max_decode_input_size` must not be below `max_encoded_size`, a check the core makes at compile + time. - **`over` decodes a value in place under that bound.** The intermediate of `decode(over{outer, inner}, text)` is held in place, in the frame of `over`'s decode, sized by the smallest bound known at compile time: the outer link's bound on a text of a static @@ -39,9 +44,7 @@ right after `formats` and before `hpke`. This is that change. - **Unchanged:** a value codec with no decode bound (the intermediate stays on the heap for a text of a dynamic size); a decode bound above 4096 bytes (the heap, its allocation never above the bound); the encode side, and its outer link's encode fault found after `prepare` with a - heap intermediate; the direct `decode(format, input)` of a value codec, which still - hands every input to the value codec and returns its errors; `over`'s own value codec, which - states no decode bound. + heap intermediate; `over`'s own value codec, which states no decode bound. - **The lanes:** the constant-time lane gains the path of a secret value decoded through `over{armor, ...}` from a text of a dynamic size, under memcheck and MemorySanitizer; the fuzz lane gains a target, `over_value`, whose chains decode with no heap at all and agree with a @@ -68,13 +71,14 @@ None. ## Impact - **Kind:** webcpp's own (`"port-of": null`), as codecs' genesis. -- **Breaking:** no API is removed. A decode through `over` of a value whose value codec states a - decode bound, from a text whose payload is past that bound, returns - `codecs::error::input_too_long` where it returned the value codec's own error (open question 1 - of the design); such a decode no longer allocates and becomes `noexcept`. +- **Breaking:** no API is removed. A decode of a value whose value codec states a decode bound, + given an input past that bound, returns `codecs::error::input_too_long` where it returned the + value codec's own error, directly and through `over` (owner decision 29); through `over` such a + decode no longer allocates and becomes `noexcept`. - **Implementation:** webcpporg/codecs (`include/webcpp/codecs/detail/core/over.hpp`, `contract.hpp`, `secrecy.hpp`, `size_maximum.hpp`, `tokens.hpp`; tests, the constant-time and fuzz lanes, the page, an example, the changelog's line), webcpporg/crypto through its change `pem-forward`, the superproject (both gitlinks). The plan is `reference/plan.md`. - **Status:** approved by the owner on 2026-11-30 (crypto `formats`' question Q1); accepted with - `reference/plan.md`, its two open questions answered by the owner before implementation. + `reference/plan.md`; the error past the bound decided by the owner on 2026-11-30 (owner + decision 29), the 4096 cap (design Q2) still open. diff --git a/libraries/codecs/openspec/changes/over-in-place/reference/plan.md b/libraries/codecs/openspec/changes/over-in-place/reference/plan.md index 354a59d..0eddc08 100644 --- a/libraries/codecs/openspec/changes/over-in-place/reference/plan.md +++ b/libraries/codecs/openspec/changes/over-in-place/reference/plan.md @@ -2,14 +2,17 @@ > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. -**Goal:** `codecs::decode(over{outer, inner}, text)` holds its intermediate in place, with -no heap and `noexcept`, whenever the inner value codec states its decode bound -`max_decode_input_size` (at most 4096), whatever the text's type; a payload past the bound is -refused before any intermediate; then crypto's PEM decode becomes a forward to codecs. +**Goal:** a value codec's decode bound `max_decode_input_size` is enforced by the core on every +path, an input past it being `codecs::error::input_too_long` before the value codec sees it, +directly and through `over` (owner decision 29); `codecs::decode(over{outer, inner}, text)` +holds its intermediate in place, with no heap and `noexcept`, under that bound (at most 4096), +whatever the text's type; then crypto's PEM decode becomes a forward to codecs and crypto's +over-long inputs take the core's error. **Architecture:** four codecs tasks and one crypto task. Task 1 adds the member to the contract -(the core reads it, checks the order of the two bounds, and shares the 4096 threshold). Task 2 -changes `over`'s value decode alone (the middle bound, the refusal, `noexcept`), proven on a +(the core reads it, refuses an input past it in its one funnel of every value decode, checks the +order of the two bounds, and shares the 4096 threshold). Task 2 +changes `over`'s value decode (the middle bound, the refusal, `noexcept`), proven on a value codec of the tests' own that mirrors crypto's PKCS#8 v1 and v2 shape. Task 3 adds the constant-time path and a fuzz target. Task 4 is the page. crypto's Task P1 (in crypto's `pem-forward` plan) removes crypto's two-step PEM decode. Task 5 moves both gitlinks; Task 6 is @@ -30,12 +33,10 @@ and owner decision 23. ## Open for the owner -The design's Q1 (the error of a payload past the bound; recommended `input_too_long`, in `over` -alone) and Q2 (the 4096 cap; recommended). This plan is written with both recommendations; the -places that change are marked "(Q1)" or "(Q2)". With Q1's B, Task 2 also adds the check to the -core's direct value decode (`detail::value_decode`) and crypto's P1 changes its DER tests; with -Q1's C, Task 1 adds the optional member `decode_input_too_long` and crypto's P1 states it, its -errors then unchanged; with Q2's B, Task 2 drops the cap's condition and its test. +Q1 is answered: owner decision 29 (2026-11-30), the core enforces the bound on every path with +`input_too_long`. The design's Q2 (the 4096 cap; recommended) is open; this plan is written with +its recommendation, the places that change marked "(Q2)": with Q2's B, Task 2 drops the cap's +condition and its test. **Paths:** `$W` is the owner's workspace directory, the folder that holds `heavy.sh`, `msvc-lane/`, `linux-lint/` and this stream's folder `codecs-over/` (a plan in the proposals @@ -124,7 +125,7 @@ on the lane tree, through heavy.sh); fix every finding of one run in the task's - Names, verbatim from the design: the member `max_decode_input_size`; detail `has_decode_input_bound`, `value_decode_bound`, `value_bounds_ordered`, `check_value_bounds`, `over_value_middle_bound`, `in_place_scratch_limit` (moved, not renamed); the error - `codecs::error::input_too_long` (Q1); the fuzz target `over_value`; the example + `codecs::error::input_too_long` (owner decision 29); the fuzz target `over_value`; the example `over_value.cpp`; the message test `decode_bound_below_encoded`. - Exceptions (owner decision 24 and the owner's standing rule): codecs throws nothing of its own; an allocator's exception propagates out of the allocating forms, which are not `noexcept`; @@ -158,8 +159,16 @@ on the lane tree, through heavy.sh); fix every finding of one run in the task's allocation. Task 2. 5. **crypto's PEM after the forward.** An RSA public key's PEM under `PUBLIC KEY` (294 bytes of DER) given to `crypto::decode(pem(spki), text)` and to `codecs::decode` of - the same. Expected: both `codecs::error::input_too_long` (Q1), neither allocates, no write past - 138 bytes. Task P1. + the same, and the same DER directly to `crypto::decode(spki, der)`. Expected: + all `codecs::error::input_too_long` (owner decision 29), none allocates, no write past 138 + bytes. Task P1. +6. **One error per input, whatever the path.** 17 bytes of `short_record` directly (a dynamic + span, a static `std::array`, a `std::vector`), as `sealed_record` (secret), + through `over{hex, ...}` and `over{armor, ...}`. Expected: `input_too_long` everywhere, the + value codec's call counter zero. Task 1 (direct) and Task 2 (`over`). +7. **The largest valid input.** 16 bytes (the "version 2" form) on every path decode; a codec of + the tests' own whose bound is one below its largest valid input refuses it on every path. + Tasks 1 and 2; crypto's pairs in Task P1. ## The files @@ -178,16 +187,18 @@ on the lane tree, through heavy.sh); fix every finding of one run in the task's --- -### Task 1: The decode bound in the value codec contract +### Task 1: The decode bound in the value codec contract, enforced on every path -Model tier: standard. Size: M. +Model tier: most capable (the core's one funnel of every value decode). Size: M. **Files:** - Modify: `libs/codecs/include/webcpp/codecs/detail/core/size_maximum.hpp`, `tokens.hpp`, `contract.hpp`, `operations.hpp`, `secrecy.hpp` - Create: `libs/codecs/test/support/bounded_records.hpp`, `libs/codecs/test/messages/decode_bound_below_encoded/{Jamfile,decode_bound_below_encoded.cpp}` -- Modify: `libs/codecs/test/value_codec_test.cpp`, `libs/codecs/test/messages/Jamfile` +- Modify: `libs/codecs/test/value_codec_test.cpp`, `libs/codecs/test/typed_decode_test.cpp`, + `libs/codecs/test/messages/Jamfile`, `libs/codecs/test/Jamfile` (the seam's define on + `typed_decode` if it lacks it) **Interfaces:** @@ -228,6 +239,14 @@ constexpr void check_value_bounds() noexcept { } // value_encoded_size, value_encode and value_decode call check_value_bounds() next to // check_secret_value_overloads(). + +// value_decode, the one funnel of every value decode (the typed decode of bytes and of text, and +// over's call of its inner value codec), gains the core's refusal (owner decision 29), before the +// value codec is called; a View whose static bound is at most the decode bound skips it: +// if constexpr (has_decode_input_bound> && view_bound_v > value_decode_bound()) { +// if (input_view.size() > value_decode_bound()) { return make_error_code(error::input_too_long); } +// } +// Its Doc Comment, and those of the typed decode in operations.hpp, say it. } ``` @@ -242,30 +261,53 @@ constexpr void check_value_bounds() noexcept { - `sealed_record`: the same codec with `secret = true` (its bytes in a `secure::secret<8>`). - `wide_record` (a count): decode only, `max_decode_input_size = 4097`, any length up to 4097 accepted (the count of bytes), longer `invalid_length`. +- `short_text` (a string of up to 20 letters): a value codec of `output_kind::text`, + `max_encoded_size = 20`, `max_decode_input_size = 20`. +- `tight_record`: `short_record`'s codec with `max_encoded_size = 12` and + `max_decode_input_size = 15`, one below its largest valid input (the bound as acceptance + contract: its 16-byte form is refused on every path). +- Each codec counts its `decode` calls in a test-only counter (`decode_calls`), so that a + test sees whether the value codec was called. - [ ] **Step 1: Write the failing tests.** - `value_codec_test.cpp`: `detail::value_decode_bound() == 16`, - `== std::dynamic_extent` for the `be16` number; `value_bounds_ordered` true for the three - records and the number; `codecs::decode(bounded, bytes)` of the 12-byte and - 16-byte forms gives the record, and of 17 bytes the value codec's own `invalid_length` (a - direct decode is the value codec's, spec scenario); the 12-byte form encodes back with - `codecs::encode(bounded, record)` as `bytes<12>`. + `== std::dynamic_extent` for the `be16` number; `value_bounds_ordered` true for the records + and the number; the 12-byte form encodes back with `codecs::encode(bounded, record)` as + `bytes<12>`. + - `typed_decode_test.cpp`, one function per refusal path of the direct decode (spec "Contract: + the decode bound is enforced on every path"), each giving 16 bytes (decoded, one call of the + value codec) and 17 bytes (`input_too_long`, no call): `short_record` from each caller's + buffer, a `std::span`, a `std::vector`, a + `std::array` and a `std::span` (static sizes), an + `std::uint8_t[17]`, a `codecs::bytes<17>` and a `secure::secret<17>` (a secret input); + `sealed_record` (secret by its value codec) from the same buffers, the timing seam + (`WEBCPP_SECURE_TIMING_ENTERED`, as `timing_test.cpp` defines it) recording one guard per + call, refusal included; `short_record` decoded as a requested secret type where the test + defines `is_secret` for a wrapper of it; `short_text` from a `std::string_view` and a + `codecs::text<21>` of 21 characters (`input_too_long`) and of 20 (decoded); `wide_record` with + 4097 and 4098 bytes; a format whose `configuration_fault` is set, given 17 bytes: the + configuration's error first; `tight_record`'s valid 16-byte form refused with + `input_too_long` (Review Focus 7); `static_assert`s that the typed decode keeps the + `noexcept` it had. The buffer forms: codecs has no buffer form that decodes into a value + (design D3), so a value decode's buffer is the caller's input, each type of which is above; + `codecs::decode(formats::hex, text, std::span)` is checked unchanged by its + existing tests. - `test/messages/decode_bound_below_encoded/`: a value codec of the file's own with `max_encoded_size = 12` and `max_decode_input_size = 8`, decoded with `codecs::decode`; `// expected-error@webcpp/codecs/detail/core/secrecy.hpp:* {{static assertion failed due to requirement 'webcpp::codecs::detail::value_bounds_ordered<...>': webcpp::codecs: a value codec's max_decode_input_size is below its max_encoded_size, so its decode would refuse its own longest encoding}}` (the requirement's text as clang prints it, read from the first failing run); its Jamfile as `refused_size`'s (`compile-diagnostic ... : native wasip2 wasip3 : alone` and the `compile-fail` twin on native and Emscripten); `build-project` in `test/messages/Jamfile`. -- [ ] **Step 2: Run, expect failure.** `B2 toolset=clang libs/codecs/test//value_codec libs/codecs/test/messages/decode_bound_below_encoded`: +- [ ] **Step 2: Run, expect failure.** `B2 toolset=clang libs/codecs/test//value_codec libs/codecs/test//typed_decode libs/codecs/test/messages/decode_bound_below_encoded`: `bounded_records.hpp` names a `value_decode_bound` that does not exist; the message test compiles. - [ ] **Step 3: Implement** the interfaces above; `tokens.hpp` reads `in_place_scratch_limit` from `size_maximum.hpp` (it includes it already, or gains the include); `operations.hpp` reads `has_encoded_bound` from `contract.hpp`. - [ ] **Step 4: Run.** The five local lanes over `libs/codecs/test`; the doc; MSVC 14.3 and 14.5 - x64 debug over `libs/codecs/test//value_codec libs/codecs/test//tokens libs/codecs/test//over libs/codecs/test/messages/decode_bound_below_encoded`. + x64 debug over `libs/codecs/test//value_codec libs/codecs/test//typed_decode libs/codecs/test//tokens libs/codecs/test//over libs/codecs/test//timing libs/codecs/test/messages/decode_bound_below_encoded`. Expected: pass. -- [ ] **Step 5: Commit, lint.** `codecs: a value codec may state max_decode_input_size, the longest input its decode accepts, never below max_encoded_size`. Lint step. +- [ ] **Step 5: Commit, lint.** `codecs: a value codec may state max_decode_input_size, the longest input its decode accepts, never below max_encoded_size; the core refuses a longer input on every path`. Lint step. **Lanes:** the five local lanes, the doc, MSVC 14.3 and 14.5 x64 debug. @@ -296,7 +338,7 @@ template // over_value_decode, in this order (design D3): // middle_size = codec_decoded_size(outer, text) -> the outer link's error first -// if (middle_size > value_decode_bound()) -> error::input_too_long (Q1) +// if (middle_size > value_decode_bound()) -> error::input_too_long (owner decision 29) // if (past_bound(middle_size)) -> error::input_too_long (genesis) // over_intermediate middle{...} -> in place, or the allocator // codec_decode(outer, text, middle.bytes()), then value_decode(inner, next_bytes/next_text) @@ -339,6 +381,11 @@ decode bound, the cap, the refusal and that `over`'s own value codec states no d bytes), of 4098 bytes (`input_too_long`, no arena allocation), and an `edge_record` of 4096 bytes (no arena allocation, in place); `noexcept` false for `wide_record`'s chain, true for `edge_record`'s. + - `one_error_whatever_the_path` (Review Focus 6, 7): 17 bytes of `short_record` and of + `sealed_record` through `over{formats::hex, test::bounded}` and `over{formats::armor("RECORD"), + test::bounded}` from a `std::string_view` and from `codecs::text` give `input_too_long`, + equal to the direct decode's of the same bytes (Task 1); `tight_record`'s 16-byte form + through both chains `input_too_long`. - `a_value_codec_with_no_decode_bound_is_unchanged`: the `be16` number through `over{formats::hex, test::be16, arena allocator}` from a `std::string_view`: one arena allocation, as before this change (spec scenario). @@ -386,13 +433,17 @@ int over_value_paths(); // added to format_paths() with `formats::armor("TEST SECRET")` into a `std::string`, the payload's characters marked by `Checker`; `codecs::decode(over{formats::armor("TEST SECRET"), test::bounded}, std::string_view{text})`; the result's bytes `traced_and_equal` to the payload; the same with CRLF lines; a 17-byte - payload `input_too_long` (its verdict on the length, public). Run natively under the replay + payload `input_too_long` (its verdict on the length, public); the direct secret decode + `codecs::decode(test::bounded, bytes)` of 16 marked bytes (traced) and of 17 + (`input_too_long`, the length public). Run natively under the replay (`B2 toolset=clang libs/codecs/test/constant_time`) first: it passes without the checker. - [ ] **Step 2: The fuzz target.** `over_value_fuzz.cpp` (D7): the input's first byte, even or odd, chooses `over{formats::hex, test::bounded}` or `over{formats::armor("RECORD"), test::bounded}`; the rest is the text as a `std::string_view`. Per input: the reference, outside the counted region, is `codecs::decode(outer, text)` into a `std::vector`, then - `input_too_long` past 16 bytes, else `codecs::decode(test::bounded, bytes)`; + `input_too_long` past 16 bytes, else a model of `short_record`'s codec written in the target + (the two forms, `invalid_length`, `invalid_prefix`); the direct + `codecs::decode(test::bounded, bytes)` of the reference's bytes equals it too; inside the region (`fuzz_allocations()` before and after equal) the chain's `codecs::decode` and `codecs::decode`; both equal the reference, value or error (the error's value and category); a decoded record encodes through the chain to @@ -436,11 +487,14 @@ Model tier: standard. Size: S. `over_value.cpp`; its "Errors": the order of D3; its "Pitfalls": a chain of chains is in place only at the level whose inner link is a bounded value codec. writing_a_format's value codec section: the member, what it promises (decode refuses every longer input), never below - `max_encoded_size` (the build stops), and that it sizes `over`'s intermediate while a direct - decode still gives the value codec every input. allocators: `over`'s allocator is no longer + `max_encoded_size` (the build stops), that it is the value codec's acceptance contract (the + core refuses every longer input with `input_too_long` on every path, so a format author pins + with a test that the largest valid input decodes), and that it sizes `over`'s intermediate; + composition's errors section: `input_too_long` for an input past a value codec's bound, + whatever the path. allocators: `over`'s allocator is no longer used for a decode under a decode bound of at most 4096. Each sentence says what the headers' Doc Comments say (codecs' AGENTS.md). -- [ ] **Step 3: The changelog's line** under "Unreleased": `* Changed over: a value decodes in place under its value codec's max_decode_input_size, with no heap.` +- [ ] **Step 3: The changelog's lines** under "Unreleased": `* Added max_decode_input_size to value codecs: a longer input is input_too_long on every path.` and `* Changed over: a value decodes in place under its value codec's max_decode_input_size, with no heap.` - [ ] **Step 4: Run.** The five local lanes over `libs/codecs/example`; the doc; MSVC 14.3 and 14.5 x64 debug over `libs/codecs/example//over_value`. Expected: pass, the doc build clean. - [ ] **Step 5: Commit, lint.** `codecs: the page says where a value's intermediate lives under its decode bound, with an example`. Lint step. @@ -525,20 +579,21 @@ $H $B2 doc `main`, every job green, and its failures fixed in follow-up commits as the autopilot rule says. - [ ] HANDBACK: `$W/codecs-over/HANDBACK.md` with the merged SHAs, the lanes' results, the - findings of the final review and their fixes, the owner's answers to Q1 and Q2 as built, and a + findings of the final review and their fixes, owner decision 29 and the answer to Q2 as built, and a line for the `hpke` stream: `codecs::decode` of a PEM format no longer allocates, and crypto's verbs are forwards. ## Self-review (the planner's) -- Spec coverage: the value codec's member and its order check (Task 1); `over`'s in-place decode, +- Spec coverage: the value codec's member, its order check and the core's refusal on every + direct path, public and secret, every caller's buffer (Task 1); `over`'s in-place decode, the refusal and its order, `noexcept`, the wipe, the cap and the fallback, `over`'s own value codec without a decode bound (Task 2); the constant-time path and the fuzz target (Task 3); the page (Task 4); crypto's forward (Task P1). No requirement without a task. - Names checked against codecs' `main` at `80d90d0`: `over_value_decode`, `over_value_decode_is_noexcept`, `decoded_bound`, `past_bound`, `in_place_intermediate`, `heap_intermediate`, `over_intermediate`, `next_bytes`, `next_text`, `value_decode`, - `check_secret_value_overloads`, `has_encoded_bound` (operations.hpp), `in_place_scratch_limit` + `check_secret_value_overloads`, `view_bound_v`, `has_encoded_bound` (operations.hpp), `in_place_scratch_limit` (tokens.hpp), `size_maximum`, `error::input_too_long`, `fuzz_allocations`, `format_paths`, `traced_and_equal`, `test/support/arena.hpp`, `counting.hpp`, `be16.hpp`, the message test layout of `refused_size`; against crypto's `formats` plan: `detail::decode_pem`, diff --git a/libraries/codecs/openspec/changes/over-in-place/specs/codecs/spec.md b/libraries/codecs/openspec/changes/over-in-place/specs/codecs/spec.md index 4dc2a7e..d053b0b 100644 --- a/libraries/codecs/openspec/changes/over-in-place/specs/codecs/spec.md +++ b/libraries/codecs/openspec/changes/over-in-place/specs/codecs/spec.md @@ -1,7 +1,7 @@ ## ADDED Requirements ### Requirement: Composition: over decodes a value in place under its decode bound -A decode of a `Value` through `codecs::over`, where `value_codec` states `max_decode_input_size` `D`, SHALL hold its intermediate in place, with no heap, when `D` is at most 4096, whatever the text's type: its size is the smallest bound known at compile time among `D` and the outer link's `max_decoded_size` of a text of a static size. Above 4096, and when the inner value codec states no decode bound, the intermediate MUST be held as the requirement "Composition: over" says (in place for a text of a static size, else from `over`'s allocator). In every case the decode MUST check, in this order: the chain's configuration, the outer link's whole text (its `decoded_size`, whose error is returned first), then the exact size of the intermediate against `D`, returning `codecs::error::input_too_long` when it is past `D` before any intermediate is made, allocated or written, so that the inner value codec never receives more than `D` elements from `over`; then the outer link's decode into the intermediate and the inner value codec's decode, whose errors reach the caller unchanged. With the intermediate in place the decode MUST be `noexcept` when the links' calls are, the typed `decode` with it. A secret operation MUST wipe the intermediate's written bytes by `secure::erase_secret` on every path. The direct `decode(Inner, input)` MUST hand every input to the value codec, whatever its size. `over`'s own value codec MUST NOT state `max_decode_input_size`. +A decode of a `Value` through `codecs::over`, where `value_codec` states `max_decode_input_size` `D`, SHALL hold its intermediate in place, with no heap, when `D` is at most 4096, whatever the text's type: its size is the smallest bound known at compile time among `D` and the outer link's `max_decoded_size` of a text of a static size. Above 4096, and when the inner value codec states no decode bound, the intermediate MUST be held as the requirement "Composition: over" says (in place for a text of a static size, else from `over`'s allocator). In every case the decode MUST check, in this order: the chain's configuration, the outer link's whole text (its `decoded_size`, whose error is returned first), then the exact size of the intermediate against `D`, returning `codecs::error::input_too_long` (the error of the direct path) when it is past `D` before any intermediate is made, allocated or written, so that the inner value codec never receives more than `D` elements from `over`; then the outer link's decode into the intermediate and the inner value codec's decode, whose errors reach the caller unchanged. With the intermediate in place the decode MUST be `noexcept` when the links' calls are, the typed `decode` with it. A secret operation MUST wipe the intermediate's written bytes by `secure::erase_secret` on every path. `over`'s own value codec MUST NOT state `max_decode_input_size`. #### Scenario: A value from a run-time text with no heap - **WHEN** a value codec of the test's own states `max_encoded_size = 12` and `max_decode_input_size = 16`, and its 12-byte and 16-byte forms are decoded with `codecs::decode(codecs::over{codecs::formats::hex, format}, text)` and through `codecs::over{codecs::formats::armor("RECORD"), format}`, `text` a `std::string_view`, under a counting `operator new` @@ -23,10 +23,33 @@ A decode of a `Value` through `codecs::over`, where `va - **WHEN** the fuzz target `over_value` runs for its bounded time from its corpus - **THEN** no input crashes or allocates, and every result, value or error, equals the two-step reference's +### Requirement: Contract: the decode bound is enforced on every path +When `value_codec` states `max_decode_input_size` `D`, every decode of a `Value` with it SHALL refuse an input longer than `D` elements with `codecs::error::input_too_long` before the value codec sees it (directly, after the format's configuration fault and before any other check; through `over`, after the outer link's errors): the direct `codecs::decode(format, input)` whatever the caller's buffer holding the input (a `std::span` of a dynamic or a static extent, a `std::vector`, a `std::array`, a byte array, a `secure::secret`, `bytes`, a `std::string_view`, `text` for a value codec of text), public or secret (by the value's `is_secret_v`, the value codec's `secret` or the requested type), and through `over`, so that an input past the bound gives the same error whatever the path. The bound is the value codec's acceptance contract: a bound below the longest valid input MUST refuse that input on every path, and an input of exactly `D` elements MUST reach the value codec. A secret refusal MUST hold the timing guard as any secret operation does and branch on the input's length alone. + +#### Scenario: A direct decode past the bound +- **WHEN** a value codec with `max_encoded_size = 12` and `max_decode_input_size = 16` is given 16 and then 17 bytes by `codecs::decode(format, bytes)`, `bytes` a `std::span`, a `std::vector`, a `std::array`, a byte array and a `std::span` of static extent +- **THEN** 16 bytes reach the value codec and decode, 17 bytes are `codecs::error::input_too_long` and the value codec is not called, for every input type + +#### Scenario: A secret direct decode past the bound +- **WHEN** the same codec marked `secret = true` decodes 17 bytes, also from a `secure::secret<17>`, and a public value codec's 17 bytes are decoded as a requested secret type +- **THEN** each is `codecs::error::input_too_long`, the timing seam records the guard entered once per call, and the value codec is not called + +#### Scenario: A value codec of text +- **WHEN** a value codec of text with `max_decode_input_size = 20` is given a `std::string_view` and a `codecs::text<21>` of 21 characters +- **THEN** both are `codecs::error::input_too_long`, and 20 characters decode + +#### Scenario: The same error on every path +- **WHEN** a 17-byte payload is decoded into the same value directly, through `over{formats::hex, format}` and through `over{formats::armor("RECORD"), format}` +- **THEN** each returns `codecs::error::input_too_long` + +#### Scenario: A bound too small refuses valid input +- **WHEN** a value codec of the test's own whose longest valid input is 16 bytes states `max_decode_input_size = 15`, and its valid 16-byte input is decoded directly and through `over` +- **THEN** both are `codecs::error::input_too_long` + ## MODIFIED Requirements ### Requirement: Contract: value_codec for typed values -`codecs::value_codec` SHALL be declared and not defined by the core; a library MUST be able to specialize it for a format and a type it owns with `output` (`output_kind::bytes` or `output_kind::text`), optionally `secret`, a static `max_encoded_size` (the longest encoding its `encode` writes) and a static `max_decode_input_size` (the longest input its `decode` accepts, in the elements it reads: bytes for `output_kind::bytes`, characters for `output_kind::text`; a promise that `decode` refuses every longer input), `encoded_size(format, value)`, `encode(format, value, output_span)` and `decode(format, input) -> result`, encoding only, decoding only, or both, and MAY add overloads of `encoded_size`, `encode` and `decode` taking `detail::secret_tag` first, which the core MUST call in a secret operation, `over` included. A value codec that states both bounds with `max_decode_input_size` below `max_encoded_size` MUST stop the build with a message that its decode would refuse its own longest encoding. Its errors MUST reach the caller unchanged. +`codecs::value_codec` SHALL be declared and not defined by the core; a library MUST be able to specialize it for a format and a type it owns with `output` (`output_kind::bytes` or `output_kind::text`), optionally `secret`, a static `max_encoded_size` (the longest encoding its `encode` writes) and a static `max_decode_input_size` (the longest input its `decode` accepts, in the elements it reads: bytes for `output_kind::bytes`, characters for `output_kind::text`; its acceptance contract, which the core enforces on every path, the requirement "Contract: the decode bound is enforced on every path"), `encoded_size(format, value)`, `encode(format, value, output_span)` and `decode(format, input) -> result`, encoding only, decoding only, or both, and MAY add overloads of `encoded_size`, `encode` and `decode` taking `detail::secret_tag` first, which the core MUST call in a secret operation, `over` included. A value codec that states both bounds with `max_decode_input_size` below `max_encoded_size` MUST stop the build with a message that its decode would refuse its own longest encoding. Its errors MUST reach the caller unchanged. #### Scenario: A typed value round-trips - **WHEN** a test specializes `value_codec` for a format of its own and a type holding a 16-bit number written as two big-endian bytes, then calls `codecs::encode(format, value)` and `codecs::decode(format, bytes)` @@ -36,9 +59,9 @@ A decode of a `Value` through `codecs::over`, where `va - **WHEN** a program decodes with a value codec that states `max_encoded_size = 12` and `max_decode_input_size = 8` - **THEN** compilation stops with the core's message that the value codec's `max_decode_input_size` is below its `max_encoded_size` -#### Scenario: A direct decode is the value codec's +#### Scenario: A direct decode past the bound is the core's - **WHEN** a value codec with `max_decode_input_size = 16` is given 17 bytes by `codecs::decode(format, bytes)` -- **THEN** the value codec is called and its own error is returned +- **THEN** the result is `codecs::error::input_too_long` and the value codec is not called ### Requirement: Composition: over `codecs::over` SHALL be a format whose encode encodes with `Inner` and then with `Outer`, and whose decode decodes with `Outer` and then with `Inner`; `Inner` MAY be a codec or a value codec's format, `Outer` MUST be a codec, text feeding `Outer` as bytes. Its `name` MUST be `Outer`'s, `" over "` and `Inner`'s; it MUST be constructible from values by class template argument deduction; it MUST be constant time when every link is and secret when any link's operation is; its intermediate MUST be held in place when its bound is known at compile time: the input's static size (with no cap; the stack it costs is documented), the inner value codec's `max_encoded_size` for an encode, or the inner value codec's `max_decode_input_size` when it is at most 4096 for a decode of a value (the requirement "Composition: over decodes a value in place under its decode bound"); it MUST otherwise come from `over`'s allocator (a third template parameter, `std::allocator` by default, deduced from `over{outer, inner, allocator}`), and MUST be wiped when the chain is secret, each link's secret arithmetic running in a secret chain. With a heap intermediate its exact sizes, its encode and decode and the core's buffer forms over it run the inner link into the intermediate, allocate and MUST NOT be `noexcept`; with a static bound they MUST be `noexcept` and allocate nothing. A fault of a link's configuration MUST be the chain's, the outer link's first, before any data; a fault of a link's encode MUST be the chain's before any `prepare`, the inner link's always and the outer link's on an intermediate in place (with a heap intermediate the outer link's is found by its encode, after `prepare`, codecs' tokens being restored). An intermediate whose exact size is past its bound MUST be refused with `input_too_long` before it is made. `over` MUST stay one-shot. diff --git a/libraries/codecs/openspec/changes/over-in-place/tasks.md b/libraries/codecs/openspec/changes/over-in-place/tasks.md index 7829270..605c69f 100644 --- a/libraries/codecs/openspec/changes/over-in-place/tasks.md +++ b/libraries/codecs/openspec/changes/over-in-place/tasks.md @@ -6,7 +6,7 @@ change `pem-forward` (`libraries/crypto/openspec/changes/pem-forward/`) in the s ## 1. The contract and over -- [ ] 1.1 The decode bound in the value codec contract: `max_decode_input_size` read by the core, the bounds' order checked at compile time with its message test, `in_place_scratch_limit` shared (D1, R1, R2, R5) +- [ ] 1.1 The decode bound in the value codec contract: `max_decode_input_size` read by the core and enforced on every direct path, public and secret, every caller's buffer (`input_too_long`, owner decision 29), the bounds' order checked at compile time with its message test, `in_place_scratch_limit` shared (D1, D3, R1, R2, R4, R5) - [ ] 1.2 `over` decodes a value in place under the decode bound: the middle bound of D2, the refusal of D3 before any intermediate, `noexcept` and no heap, the wipe on every path, the cap and the fallback unchanged (D2 to D5, R3 to R9) ## 2. The own lanes From 5558682666de670d434de7660cd3a863e6ed3294 Mon Sep 17 00:00:00 2001 From: R Date: Mon, 30 Nov 2026 21:45:59 -0300 Subject: [PATCH 04/10] crypto: pem-forward follows codecs' owner decision 29: input_too_long past every pair's bound, the formats tests that change, a largest-valid-input test per pair --- .../openspec/changes/pem-forward/design.md | 24 ++-- .../openspec/changes/pem-forward/proposal.md | 25 +++-- .../changes/pem-forward/reference/plan.md | 94 ++++++++++++---- .../changes/pem-forward/specs/crypto/spec.md | 105 +++++++++++++++++- .../openspec/changes/pem-forward/tasks.md | 2 +- 5 files changed, 208 insertions(+), 42 deletions(-) diff --git a/libraries/crypto/openspec/changes/pem-forward/design.md b/libraries/crypto/openspec/changes/pem-forward/design.md index 55af4dc..85244d9 100644 --- a/libraries/crypto/openspec/changes/pem-forward/design.md +++ b/libraries/crypto/openspec/changes/pem-forward/design.md @@ -30,12 +30,17 @@ owner decision 23), the encode side. `formats`' R24 is superseded** - why: codecs' `over` now does R24's two steps, in the same order (the armor's configuration, its structure and base64, the bound, the DER) and with the same wipe - cost if wrong: none; restoring the two steps is R24's 20 lines. -- **R2. Ruling: a PEM payload past the decode bound is `codecs::error::input_too_long` (codecs' - Q1, recommendation A)** - why: it is codecs' refusal of `over`'s intermediate, and one error - through both verbs keeps `formats`' rule that `crypto::decode` and `codecs::decode` give the - same values and errors; with Q1's C, crypto's value codecs state - `decode_input_too_long = crypto::error::invalid_encoding` instead and this ruling's error stays - `invalid_encoding` - cost if wrong: the sentence of the spec and three assertions. +- **R2. Owner decision (2026-11-30, codecs' owner decision 29, its question Q1 answered B): every + input past a pair's decode bound is `codecs::error::input_too_long`, directly and through PEM, + through `crypto::decode` and `codecs::decode` alike** - why (the owner's): the error code must + always be the same whatever the path, so the same file read as PEM or as direct DER gives the + same error; codecs' core refuses it before crypto's value codec reads a byte - cost: `formats`' + sentences "refuse anything else with `invalid_encoding`" and "`invalid_signature` for any other + bytes" gain the exception, and the tests listed in the plan change their expected error. +- **R2a. Ruling: a pair's `max_decode_input_size` is its acceptance contract** - why: under R2 a + bound below the longest valid input refuses that input on every path, unseen by the value codec; + so every pair that decodes has a test that a valid input exactly its bound long decodes and + that one byte more is `input_too_long` (the spec's scenario lists them) - cost if wrong: none. - **R3. Ruling: `crypto::decode` checks `noexcept(codecs::decode(format, input))` at compile time** (`static_assert`, message "webcpp::crypto: a decode of a crypto format allocates nothing and cannot throw: the inner format states max_decode_input_size") - why: the forward is @@ -56,8 +61,9 @@ owner decision 23), the encode side. ## Risks / Trade-offs -- **The error of an over-long PEM payload changes** (R2), for a program that compared it with - `invalid_encoding`. The guide's errors page says it. +- **The error of an over-long input changes** (R2), DER, raw or PEM, for a program that compared + it with `invalid_encoding` or `invalid_signature`. The guide's errors page says it. +- **A wrong bound now refuses valid input** (R2a); the per-pair tests catch it. ## Migration Plan @@ -67,4 +73,4 @@ and 6). ## Open Questions -None of its own: R2 follows codecs' Q1. +None: R2 is the owner's decision 29 of codecs. diff --git a/libraries/crypto/openspec/changes/pem-forward/proposal.md b/libraries/crypto/openspec/changes/pem-forward/proposal.md index 87c6e98..1ebbde3 100644 --- a/libraries/crypto/openspec/changes/pem-forward/proposal.md +++ b/libraries/crypto/openspec/changes/pem-forward/proposal.md @@ -16,15 +16,21 @@ becomes a forward. This change makes it one. the pair (crypto's list, the curves' headers, the refusal reasons) is unchanged. - **The verb states its promise**: `crypto::decode` checks at compile time that the codecs call it forwards to is `noexcept`, so that a crypto pair whose decode would allocate stops the build. -- **The error of a PEM payload past the decode bound** is codecs' `input_too_long` (codecs' - design Q1, recommendation A) through both `crypto::decode` and `codecs::decode`, where `formats` - said `invalid_encoding`; the DER formats' errors are unchanged. +- **The error of any input past a pair's decode bound** is codecs' `input_too_long` (codecs' + owner decision 29, 2026-11-30: one error whatever the path, the same file read as PEM or as + direct DER giving the same error), through both `crypto::decode` and `codecs::decode`, directly + (DER, raw) and through PEM, where `formats` said `invalid_encoding` (keys) or + `invalid_signature` (DER signatures). The bound becomes each pair's acceptance contract, pinned + by a test per pair that its largest valid input decodes. - **Tests:** `formats_pem_test` and the curves' PEM cases: `codecs::decode` of a PEM text allocates nothing (it allocated: the documented difference is gone), the toy's 17 bytes and an RSA public key's PEM under `PUBLIC KEY` are `input_too_long`, the DER buffer's wipe is now - codecs' intermediate's. -- **The page:** the formats chapter and the errors page lose the documented difference and gain - the error; the changelog's source entry. + codecs' intermediate's; every `formats` test that asserts `invalid_encoding` or + `invalid_signature` for a direct input longer than its pair's bound asserts `input_too_long` + (the list is in `reference/plan.md`); a largest-valid-input test per pair. +- **The page:** the formats chapter and the errors page (its error tables) lose the documented + difference and gain `input_too_long` for every input past a pair's bound; the changelog's + source entry. ## Capabilities @@ -39,9 +45,10 @@ None. ## Impact - **Kind:** a wrapper (`"port-of": null`), as crypto's genesis. -- **Breaking:** a PEM whose payload is longer than the inner format's decode bound is - `codecs::error::input_too_long` instead of `crypto::error::invalid_encoding` (with codecs' Q1 - answered A); no API is removed but the private `detail::decode_pem`. +- **Breaking:** an input longer than a pair's decode bound, DER, raw or PEM, is + `codecs::error::input_too_long` instead of `crypto::error::invalid_encoding` (or + `invalid_signature` for a DER signature); no API is removed but the private + `detail::decode_pem`. - **Implementation:** webcpporg/crypto (`include/webcpp/crypto/formats.hpp`, its tests, the guide, the changelog's source entry), with codecs' `over-in-place` in the same stream and one superproject pull request for both gitlinks. The task is `reference/plan.md`'s Task P1, run in diff --git a/libraries/crypto/openspec/changes/pem-forward/reference/plan.md b/libraries/crypto/openspec/changes/pem-forward/reference/plan.md index 8379d83..cefbc92 100644 --- a/libraries/crypto/openspec/changes/pem-forward/reference/plan.md +++ b/libraries/crypto/openspec/changes/pem-forward/reference/plan.md @@ -3,7 +3,9 @@ > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. **Goal:** `crypto::decode` of a PEM format forwards to `codecs::decode`, which after codecs' -`over-in-place` decodes in place with no heap; crypto's two-step `detail::decode_pem` goes. +`over-in-place` decodes in place with no heap; crypto's two-step `detail::decode_pem` goes; every +input past a pair's decode bound is codecs' `input_too_long` on every path (codecs' owner decision +29), and each pair's largest valid input is pinned to decode. **Architecture:** one task, Task P1, run in codecs' `over-in-place` stream after its Task 4 and before its Tasks 5 (the superproject) and 6 (the delivery), which deliver this change too. The @@ -14,15 +16,14 @@ stream's paths, commands, lanes, lint step, preflight and Global Constraints are libsecp256k1, the superproject's pins) and node's WebCrypto on Emscripten. **Spec:** this change, `libraries/crypto/openspec/changes/pem-forward/` (`design.md` R1 to R6, -`specs/crypto/spec.md`, binding), codecs' `over-in-place` (its design D2, D3, D5, Q1), crypto's +`specs/crypto/spec.md`, binding), codecs' `over-in-place` (its design D2, D3, D5, owner decision 29), crypto's `formats` design R24, R35, R37. -**Open for the owner:** codecs' Q1. This plan follows its recommendation A: a PEM payload past the -bound is `codecs::error::input_too_long`. With Q1's C, Step 3 also adds -`static constexpr crypto::error decode_input_too_long = crypto::error::invalid_encoding;` to every -crypto value codec that decodes (its curves' `formats.hpp`, the toy) and the tests below keep -`invalid_encoding`; with B, the DER tests that refuse an input longer than the bound change to -`input_too_long` as well (P-256's 150-byte PKCS#8 among them). +**Decided:** codecs' Q1 is answered B (codecs' owner decision 29, 2026-11-30): the core refuses +every input past a value codec's decode bound with `codecs::error::input_too_long`, directly and +through `over`. Every `formats` test listed in Step 1 that expected crypto's error for such an +input now expects `input_too_long`. codecs' Q2 (the 4096 cap) does not touch crypto (its largest +bound is 138). --- @@ -32,11 +33,14 @@ Model tier: standard. Size: M. **Files:** (as `formats` built them; the codecs plan's preflight re-reads them) - Modify: `libs/crypto/include/webcpp/crypto/formats.hpp` -- Modify: `libs/crypto/test/formats_pem_test.cpp`, the curves' PEM cases (Ed25519's - `pem_variants`, P-256's Review Focus 5 case of `formats`' Task 8), `test/support/format_checks.hpp` - if it states the heap difference, the timing coverage tests that name `decode_pem` -- Modify: the guide's formats chapter and errors page, the changelog's source entry, and - `doc/tables/crypto.json` if it lists `decode_pem`; the generated files rerun +- Modify: `libs/crypto/test/formats_pem_test.cpp`, `formats_verbs_test.cpp`, the curves' tests + listed in Step 1, `test/support/format_checks.hpp` (the heap difference, if it states it; the new + `check_largest_input`), the fuzz targets of `test/fuzz/`, the timing coverage tests that name + `decode_pem` +- Modify: the guide's formats chapter and errors page (its error tables: `input_too_long`, category + `webcpp.codecs`, for every input past a pair's bound, DER, raw and PEM), the changelog's source + entry, and `doc/tables/crypto.json` where it lists `decode_pem` or an error per format; the + generated files rerun **Interfaces:** @@ -60,8 +64,9 @@ template std::string_view)` and `codecs::decode(pem(pkcs8), std::string_view)` allocate nothing (the assertion that it allocated, "the documented difference", is removed); the 16-byte "version 2" `pkcs8` decodes through both verbs; 17 bytes are - `codecs::error::input_too_long` through both (Q1); the 294-byte payload under `PUBLIC KEY` - `input_too_long` through both, the counter zero; the armor of no bytes still the toy's + `codecs::error::input_too_long` through both (owner decision 29); the 294-byte payload under `PUBLIC KEY` + `input_too_long` through both, the counter zero, and the same 294 bytes given directly to + `crypto::decode(spki, der)` also `input_too_long`; the armor of no bytes still the toy's `invalid_encoding` (the value codec's own refusal of 0 bytes); `pem(pkcs8)`'s decode records the erase of codecs' intermediate (12 or 16 bytes) through secure's `WEBCPP_SECURE_TEST_WIPE_RECORD`; `crypto::decode` and `codecs::decode` give the same values @@ -70,24 +75,69 @@ template - The curves' PEM cases: P-256's RSA public key PEM (Review Focus 5) `input_too_long` through both verbs with no heap; Ed25519's OpenSSL PEM of a private key through `codecs::decode` with no heap (the spec's scenario). + - Every `formats` test that expects crypto's error for a direct input longer than its pair's + bound (from `formats`' plan, Tasks 4 to 10, by name as built; the preflight confirms the + names) now expects `codecs::error::input_too_long`: + - `formats_verbs_test.cpp` (Task 4, the toy): an over-long direct input of each toy pair + (13 bytes of `spki`, 17 of `pkcs8`, 9 of `raw`) - a new assertion where `formats` asserted + none, an `invalid_encoding` where it did. + - `formats_pem_test.cpp` (Task 4): the toy's 17-byte `pkcs8` payload and the 294-byte payload + (above). + - `formats_ed25519_sodium_test.cpp` (Task 6): the version-2 PKCS#8 (`30 53 02 01 01 ...`, 83 + bytes, bound 48), directly and through `pem(pkcs8)`; the same case on OpenSSL in + `formats_25519_openssl_oracle_test.cpp` (as renamed by Task 6), the spec's "PKCS#8 version 2 + is refused" on both backends. + - `formats_x25519_sodium_test.cpp` (Task 7): Wycheproof `x25519_asn_test.json`'s invalid + SPKI and PKCS#8 cases longer than 44 and 48 bytes, and `x25519_pem_test.json`'s whose DER + is; the test computes the expected error from the case's length. + - `p256_formats_bearssl_test.cpp` (Task 8): the PKCS#8 with `[0] parameters` (150 bytes, + bound 138; the 67-byte one stays `invalid_encoding`); Wycheproof `ecdh_secp256r1_ecpoint_test.json`'s + invalid points longer than 65 bytes (the others stay `invalid_public_key`); the RSA SPKI + PEM and its DER (Review Focus 5); its DER section's `ecdsa_secp256r1_sha256_test.json` + cases longer than 72 bytes (the others keep `invalid_signature`). + - `p256_wycheproof_bearssl_test.cpp` (Task 8, DER through the format): its cases longer than + 72 bytes. + - `p256_webcrypto_oracle_test.cpp` (Task 8, Emscripten) and `p256_openssl_oracle_test.cpp` + (native): the 150-byte PKCS#8 of the spec's "A P-256 key from WebCrypto". + - `secp256k1_formats_test.cpp` (Task 10): Wycheproof `ecdsa_secp256k1_sha256_test.json`'s keys + through `raw` and `spki` longer than 65 and 88 bytes; `secp256k1_der_test.cpp` (Task 10): + `ecdsa_secp256k1_sha256_bitcoin_test.json`'s DER cases longer than 72 bytes. + - The fuzz targets of `test/fuzz/` (Tasks 5 to 10): each that asserts crypto's error for any + refused input expects `input_too_long` for an input past its pair's bound. + Where a test reads its expected error from a file (Wycheproof), it derives `input_too_long` + from the case's length against `crypto::formats::max_decode_input_size`, never by a + list of case ids. + - The acceptance contract (R2a): `format_checks.hpp` gains + `template void check_largest_input(Format, std::span largest)` + (the input is exactly `max_decode_input_size` long and decodes, directly and, + for `spki` and `pkcs8`, through `pem(F)` by both verbs; one byte appended is `input_too_long` + on every path); called for every pair that decodes, in `formats_verbs_test.cpp` (the toy, its + 16-byte "version 2" `pkcs8`), `formats_ed25519_sodium_test.cpp`, `formats_x25519_sodium_test.cpp`, + `p256_formats_bearssl_test.cpp` (and its OpenSSL twin) and `secp256k1_formats_test.cpp`, with + the inputs of the spec's scenario (a DER signature of 72 bytes is one whose r and s both + have their high bit set, 33 bytes each; a public key's largest `raw` and `spki` are the + uncompressed forms). - A message test `decode_not_noexcept` (crypto's message layout, its `crypto.json` entry and MSVC twin where crypto builds one): a toy pair of the test's own whose value codec states no `max_decode_input_size`, its `pem_t` decoded through `crypto::decode` from a `std::string_view`, stops at R3's `static_assert` (if `formats`' R37 check fires first for such a pair, the test pins the order: R37's message first, and R3's is then pinned with a pair whose bound is above 4096). -- [ ] **Step 2: Run, expect failure.** `B2 toolset=clang libs/crypto/test//formats_pem`: with - codecs' Tasks 1 to 4 in place the heap assertions already flip, while the errors still come - from `detail::decode_pem` (`invalid_encoding`) and the message test compiles. +- [ ] **Step 2: Run, expect failure.** `B2 toolset=clang libs/crypto/test//formats_pem libs/crypto/test//formats_verbs`: + with codecs' Tasks 1 to 4 in place the direct tests already give `input_too_long` (the core's + refusal) and the heap assertions flip, so the old expectations fail; the PEM errors still come + from `detail::decode_pem` (`invalid_encoding`) and the message test compiles. Every curve test + listed above fails on its old expectation until Step 1's edits. - [ ] **Step 3: Implement** the forward and the `static_assert`; delete `detail::decode_pem` and every name only it used; the guide (formats chapter: PEM decodes in place through codecs, the - "documented difference" removed; errors page: `codecs::error::input_too_long` for a PEM payload - past the bound), the changelog's source entry (`* Changed PEM decode: through codecs' over, in - place; a payload past the bound is codecs' input_too_long.`), `crypto.json` and its generated + "documented difference" removed; errors page's tables: `codecs::error::input_too_long` for any + input past a pair's bound, DER, raw or PEM, and the bound of each pair beside it), the + changelog's source entry (`* Changed PEM decode: through codecs' over, in place; an input past a + format's bound is codecs' input_too_long on every path.`), `crypto.json` and its generated files through `generate.py`. - [ ] **Step 4: Run.** The five local lanes over `libs/crypto/test libs/crypto/example`; the doc; `generate.py --check`; MSVC 14.3 and 14.5 x64 debug over `libs/crypto/test//formats_pem` and - the curves' formats tests; arm64 14.5 over crypto's timing set (a guarded function removed); + every test file listed in Step 1; arm64 14.5 over crypto's timing set (a guarded function removed); `$W/heavy.sh codecs-over $W/codecs-over/ct-run/linux.sh crypto constant-time` (the secret PEM paths now through codecs' `over`) and `... crypto fuzz` (the PEM targets; a target that asserted `invalid_encoding` for a long payload asserts `input_too_long`). Expected: pass. diff --git a/libraries/crypto/openspec/changes/pem-forward/specs/crypto/spec.md b/libraries/crypto/openspec/changes/pem-forward/specs/crypto/spec.md index 7a306a3..c06274f 100644 --- a/libraries/crypto/openspec/changes/pem-forward/specs/crypto/spec.md +++ b/libraries/crypto/openspec/changes/pem-forward/specs/crypto/spec.md @@ -1,7 +1,7 @@ ## MODIFIED Requirements ### Requirement: Formats: PEM is codecs' armor over a DER format -`crypto::formats::pem(F)` SHALL encode RFC 7468's armor of `F`'s DER through codecs' `formats::armor`: lines of 64 characters, each ended by a line feed, the label of `F`. Decoding SHALL accept what codecs' armor accepts (lines ended by a line feed or by a carriage return and a line feed, the last line ending optional, nothing before the BEGIN line or after the END line), refuse the armor's faults with codecs' errors (`invalid_prefix` for a boundary or a label other than `F`'s, `invalid_length` for a line, `invalid_character` and `invalid_padding` for the base64), and refuse a DER that `F`'s decoder refuses with crypto's error. `crypto::decode` of a PEM format MUST forward to `codecs::decode(format, text)` after the pair's check, as for every format, and both MUST decode in place, with no heap and `noexcept`, through codecs' `over`, whose intermediate holds the DER under `F`'s decode bound, `max_decode_input_size`, and is wiped after a `pkcs8`; a payload longer than that bound MUST be `codecs::error::input_too_long` through both, before the DER is written. `crypto::decode` MUST stop the build when the codecs call it forwards to is not `noexcept`, and `crypto::detail::decode_pem` MUST NOT exist. ``, the namespace `crypto::pem`, the family `families::pem` and the target `/webcpp/crypto//pem-default` MUST NOT exist. +`crypto::formats::pem(F)` SHALL encode RFC 7468's armor of `F`'s DER through codecs' `formats::armor`: lines of 64 characters, each ended by a line feed, the label of `F`. Decoding SHALL accept what codecs' armor accepts (lines ended by a line feed or by a carriage return and a line feed, the last line ending optional, nothing before the BEGIN line or after the END line), refuse the armor's faults with codecs' errors (`invalid_prefix` for a boundary or a label other than `F`'s, `invalid_length` for a line, `invalid_character` and `invalid_padding` for the base64), and refuse a DER that `F`'s decoder refuses with crypto's error. `crypto::decode` of a PEM format MUST forward to `codecs::decode(format, text)` after the pair's check, as for every format, and both MUST decode in place, with no heap and `noexcept`, through codecs' `over`, whose intermediate holds the DER under `F`'s decode bound, `max_decode_input_size`, and is wiped after a `pkcs8`; a payload longer than that bound MUST be `codecs::error::input_too_long` through both, before the DER is written, the error the same DER gives when decoded directly (codecs' owner decision 29). `crypto::decode` MUST stop the build when the codecs call it forwards to is not `noexcept`, and `crypto::detail::decode_pem` MUST NOT exist. ``, the namespace `crypto::pem`, the family `families::pem` and the target `/webcpp/crypto//pem-default` MUST NOT exist. #### Scenario: OpenSSL's PEM - **WHEN** the PEM texts OpenSSL writes for an Ed25519, an X25519, a P-256 and a secp256k1 key, public and private, are decoded with `crypto::decode` and encoded again @@ -22,3 +22,106 @@ #### Scenario: codecs' decode of a PEM allocates nothing - **WHEN** `codecs::decode(crypto::formats::pem(crypto::formats::pkcs8), text)` decodes OpenSSL's PEM of an Ed25519 private key from a `std::string_view` under a counting `operator new` - **THEN** it gives the key pair crypto's verb gives, the counter is zero, and the 48-byte intermediate is wiped + +### Requirement: Formats: registered into codecs, four mirrored forms, a fixed result +Each valid pair of a format and a type SHALL be a `codecs::value_codec` specialization in the type's curve's `curves//formats.hpp`, stating its `output_kind`, `max_encoded_size` (the longest encoding its encoder writes), its decode bound `max_decode_input_size` (the longest encoded input its decoder accepts; equal to `max_encoded_size` for every pair of this change) when it decodes, and, for the private formats (`pkcs8`, `pem(pkcs8)` and a key pair's `raw`), `secret = true`. The library SHALL offer `crypto::encode(format, value)`, returning codecs' default result (`bytes` for a binary format, `text` for PEM, `secret_bytes` and `secret_text` for a private one, `N` the value codec's bound); `crypto::encode(format, value, token)` with any codecs token; `crypto::encode(format, value, output)` into a caller's `std::span` or `std::span`, returning `result`; `crypto::decode(format, input)`, returning `result`, `input` a `std::span` for `raw`, `spki`, `pkcs8` and `der` and a `std::string_view` for `pem(F)`; and the members `value.encode(format)` and `T::decode(format, input)`. `crypto::encode` and `crypto::decode` MUST check the pair against crypto's list and then call codecs' `encode` and `decode` with the same arguments, so that `codecs::encode` and `codecs::decode` with the same format give the same bytes and values. A program using one curve's formats MUST pull no other backend. No encode and no decode of `crypto::` MUST allocate from the heap with codecs' default and fixed results; the private results MUST be move-only and wiped on destruction and on move; the span form MUST refuse an output shorter than the exact encoding with `codecs::error::output_too_small` and write nothing on any error. `crypto::formats::max_encoded_size` SHALL be the value codec's `max_encoded_size`, and `crypto::formats::max_decode_input_size` its `max_decode_input_size`; a crypto value codec that decodes and states no decode bound MUST stop the build. The decode bound is the pair's acceptance contract, which codecs enforces on every path (codecs' owner decision 29): an input longer than `max_decode_input_size` MUST be `codecs::error::input_too_long` through `crypto::decode` and `codecs::decode` alike, directly and through PEM, before the value codec reads it, and every pair's largest valid input, exactly `max_decode_input_size` long, MUST decode. + +#### Scenario: The same bytes from every form +- **WHEN** a secp256k1 public key is encoded with `crypto::encode(crypto::formats::spki, key)`, `codecs::encode(crypto::formats::spki, key)`, `key.encode(crypto::formats::spki)` and `crypto::encode(crypto::formats::spki, key, output)` +- **THEN** the four give the same 88 bytes, and `crypto::decode(crypto::formats::spki, bytes)` and `secp256k1::public_key::decode(crypto::formats::spki, bytes)` give the key back + +#### Scenario: Two bounds, equal today +- **WHEN** the test iterates every valid pair that decodes +- **THEN** each states `max_decode_input_size`, and it equals `max_encoded_size` (Ed25519's and X25519's `pkcs8` 48, P-256's 138, secp256k1's 135) + +#### Scenario: No heap +- **WHEN** every valid pair of the format table is encoded and decoded through `crypto::encode` and `crypto::decode` under a counting `operator new` +- **THEN** the count is zero + +#### Scenario: A token of codecs' +- **WHEN** a P-256 public key is encoded with `crypto::encode(crypto::formats::pem(crypto::formats::spki), key, codecs::tokens::append_to(text))` into a string that holds a line +- **THEN** the string holds the line followed by the 178 characters of the PEM + +#### Scenario: One curve, one backend +- **WHEN** a program that includes only `curves/ed25519/formats.hpp` and links only libsodium encodes and decodes every Ed25519 format +- **THEN** it builds and runs, as the existing tests that build each family without the others do + +#### Scenario: The largest valid input of every pair decodes +- **WHEN** the test iterates every valid pair that decodes and decodes, directly and, for `spki` and `pkcs8`, through `pem(F)`, a valid input exactly `max_decode_input_size` long (Ed25519's and X25519's public `raw` 32 and `spki` 44, key pair `raw` 32 and `pkcs8` 48, signature `raw` 64; P-256's public `raw` 65 and `spki` 91, key pair `raw` 32 and `pkcs8` 138, signature `raw` 64 and `der` 72; secp256k1's public `raw` 65 and `spki` 88, x-only `raw` 32, key pair `raw` 32 and `pkcs8` 135, ECDSA `raw` 64 and `der` 72, recoverable `raw` 65, Schnorr `raw` 64) +- **THEN** each decodes, and the same input with one byte appended is `codecs::error::input_too_long` + +### Requirement: Formats: the valid pairs, checked with the type's list +`codecs::encodable` and `codecs::decodable` SHALL be true exactly for these pairs, and `crypto::encode` and `crypto::decode` MUST stop the build for every other pair of a crypto type and a crypto format in a `static_assert` whose message says the type has no such format and whose failed requirement names the type's list of formats: + +| Type | Formats | Exact sizes | +|---|---|---| +| `ed25519::public_key`, `x25519::public_key` | `raw`, `spki`, `pem(spki)` | 32, 44, 113 | +| `p256::basic_public_key` | `raw` (also `compressed`), `spki` (also `compressed`), `pem(spki)` | 65 (33), 91 (59), 178 (134) | +| `secp256k1::public_key` | `raw` (also `compressed`; `xonly` to encode only), `spki` (also `compressed`), `pem(spki)` | 65 (33, 32), 88 (56), 174 (130) | +| `secp256k1::xonly_public_key` | `raw` (also `xonly`) | 32 | +| `ed25519::basic_keypair`, `x25519::basic_keypair` | `raw` (its `secret()`), `pkcs8`, `pem(pkcs8)` | 32, 48, 119 | +| `p256::basic_keypair` | `raw` (its `secret()`), `pkcs8`, `pem(pkcs8)` | 32, 138, 241 | +| `secp256k1::basic_keypair` | `raw` (its `secret()`), `pkcs8`, `pem(pkcs8)` | 32, 135, 237 | +| `p256::ecdsa_signature`, `secp256k1::ecdsa_signature` | `raw`, `der` | 64, 8 to 72 | +| `secp256k1::recoverable_signature` | `raw` | 65 | +| `secp256k1::schnorr_signature`, `ed25519::signature` | `raw` | 64 | + +A key pair's `raw` MUST be its `secret()` on encoding and its `from_secret` on decoding, with no second implementation. The default point form of `raw` and `spki` MUST be the uncompressed point on every EC curve, and `compressed` MUST be offered on every EC curve and every backend. `raw(xonly)` decoded into a `secp256k1::public_key` MUST stop the build with a message naming `xonly_public_key`. On a backend whose keys live in WebCrypto (`detail::asynchronous_backend_v`), the private formats MUST be refused at compile time with a message naming WebCrypto's `exportKey`. + +#### Scenario: Ed25519 and DER +- **WHEN** a program calls `crypto::encode(crypto::formats::der, signature)` with an Ed25519 signature +- **THEN** compilation stops with a message saying that Ed25519 and BIP340 signatures have no DER form, and the failed requirement names the signature's list, which holds `raw` alone + +#### Scenario: A key pair's raw is its secret +- **WHEN** a P-256 key pair `k` is encoded with `crypto::formats::raw` +- **THEN** the bytes equal `k.secret()->bytes()`, the result is a `secret_bytes<32>`, and `crypto::decode(crypto::formats::raw, bytes)` has `k`'s public key + +#### Scenario: A compressed P-256 key on BearSSL +- **WHEN** a P-256 public key on BearSSL is encoded with `crypto::formats::raw(crypto::formats::compressed)` and decoded with `crypto::formats::raw` +- **THEN** the 33 bytes are OpenSSL's compressed form of the key, and the decoded key equals the original + +#### Scenario: Wycheproof's compressed points on BearSSL +- **WHEN** every case of Wycheproof's `ecdh_secp256r1_ecpoint_test.json` whose public key is a compressed point is decoded with `crypto::decode>(crypto::formats::raw, bytes)` +- **THEN** the valid cases decode to the point the uncompressed cases of the same file hold, and the invalid ones give `invalid_public_key`, or `codecs::error::input_too_long` for one longer than 65 bytes + +#### Scenario: A list in one place +- **WHEN** the test of the format table iterates `detail::all_formats` over every type +- **THEN** `codecs::encodable` is true exactly for the table's pairs, and the guide's table is generated from the same list + +### Requirement: Formats: DER of the typed ECDSA signatures +`crypto::encode(crypto::formats::der, signature)`, `signature` a `p256::ecdsa_signature` or a `secp256k1::ecdsa_signature`, SHALL write strict DER of 8 to 72 bytes, its exact size known before any write, refusing r or s 0 or not below n with `invalid_signature`, and `crypto::decode(crypto::formats::der, bytes)` SHALL accept only the DER that encoding gives again, returning `codecs::error::input_too_long` for more than 72 bytes, before the backend reads them, and `invalid_signature` for any other bytes. + +#### Scenario: A non-canonical DER signature +- **WHEN** `crypto::decode(crypto::formats::der, bytes)` is given a Wycheproof case of `ecdsa_secp256r1_sha256_test.json` whose DER has a leading zero byte it does not need +- **THEN** it returns `invalid_signature` + +#### Scenario: A short buffer +- **WHEN** `crypto::encode(crypto::formats::der, signature, output)` is given a buffer one byte shorter than the signature's DER +- **THEN** it returns `codecs::error::output_too_small` and the buffer is untouched + +#### Scenario: A DER signature longer than 72 bytes +- **WHEN** `crypto::decode(crypto::formats::der, bytes)` and `crypto::decode(crypto::formats::der, bytes)` are given a Wycheproof case whose DER is longer than 72 bytes +- **THEN** each returns `codecs::error::input_too_long` + +### Requirement: Key formats: SPKI, PKCS#8 and PEM, strict +Each curve SHALL offer its keys through `crypto::encode` and `crypto::decode` with the formats `raw`, `spki`, `pkcs8`, `pem(spki)` and `pem(pkcs8)` of `crypto::formats` (PEM per RFC 7468 through codecs' armor: labels `PUBLIC KEY` and `PRIVATE KEY` taken from the inner format, lines of 64 characters, LF on encoding): Ed25519 and X25519 per RFC 8410 (on libsodium, RFC 8410's fixed DER prefix and the 32 key bytes, a recorded constant), secp256k1 per RFC 5480 with its OID, P-256 per RFC 5480 and RFC 5915 (SPKI with the uncompressed point by default, 91 bytes, or the compressed point, 59 bytes, and PKCS#8 version 0 whose `ECPrivateKey` is version 1 with the `publicKey` and without `parameters`, 138 bytes, by fixed layouts on every backend of the curve, BearSSL included, `design.md` D36 of the foundation; a PKCS#8 without `publicKey` or with `[0] parameters` refused). The names `encode_spki`, `decode_spki`, `encode_pkcs8`, `decode_pkcs8`, `max_spki_size` and `max_pkcs8_size` of every curve, and the namespace `crypto::pem`, MUST NOT exist. Decoding of the DER formats MUST accept an encoding only when re-encoding what was decoded gives the same bytes, on every backend, and refuse anything else with `invalid_encoding`, but an input longer than the pair's `max_decode_input_size`, which is `codecs::error::input_too_long`, directly and through PEM alike. Tests MUST run round trips, malformed-input refusals, and OpenSSL natively and WebCrypto's `importKey` and `exportKey` (`raw`, `spki`, `pkcs8`) under node as outside oracles; for secp256k1, which WebCrypto lacks, node's `crypto` module (`createPrivateKey`, `createPublicKey`, `export`) is the oracle under node. + +#### Scenario: An Ed25519 key from WebCrypto +- **WHEN** node's WebCrypto exports an Ed25519 key pair as `pkcs8` and `spki` and the library decodes both on libsodium with `crypto::decode` +- **THEN** the key pair signs as WebCrypto's does, and encoding it again gives the same bytes + +#### Scenario: PKCS#8 version 2 is refused +- **WHEN** `crypto::decode(crypto::formats::pkcs8, bytes)` is given an Ed25519 PKCS#8 that carries the public key (version 2, 83 bytes, longer than the pair's bound of 48), and `crypto::decode` of its PEM through `pem(pkcs8)` +- **THEN** each returns `codecs::error::input_too_long`, on libsodium and on OpenSSL alike + +#### Scenario: A P-256 key from WebCrypto +- **WHEN** node's WebCrypto exports a P-256 key pair imported from `crypto::encode(crypto::formats::pkcs8, key)`'s bytes as `pkcs8` and its public key as `spki`, and the library decodes both on BearSSL +- **THEN** the exports are exactly the 138 and 91 bytes `crypto::encode` writes, and a PKCS#8 of the same key carrying `[0] parameters` (150 bytes) is refused with `codecs::error::input_too_long` (longer than 138) and one without `publicKey` (67 bytes) with `invalid_encoding` + +#### Scenario: An X25519 key from WebCrypto +- **WHEN** node's WebCrypto exports an X25519 key pair as `pkcs8` and `spki`, and the library decodes each into `x25519::keypair` or `x25519::public_key` +- **THEN** each agrees with WebCrypto's `deriveBits` against the same peer, and encoding again gives the same bytes + +#### Scenario: A libp2p PeerId's key +- **WHEN** a P-256 public key's SPKI DER from OpenSSL is decoded by `crypto::decode>(crypto::formats::spki, bytes)` and re-encoded +- **THEN** the bytes are identical, as a libp2p PeerId of an ECDSA key requires diff --git a/libraries/crypto/openspec/changes/pem-forward/tasks.md b/libraries/crypto/openspec/changes/pem-forward/tasks.md index 4d07da8..4e93c57 100644 --- a/libraries/crypto/openspec/changes/pem-forward/tasks.md +++ b/libraries/crypto/openspec/changes/pem-forward/tasks.md @@ -6,7 +6,7 @@ is `reference/plan.md`. ## 1. The forward -- [ ] 1.1 `crypto::decode` forwards PEM to codecs, `detail::decode_pem` removed, the `noexcept` check; the PEM tests of the toy and the curves (no heap through `codecs::decode`, `input_too_long` past the bound, codecs' wipe); the guide, the errors page and the changelog's source entry (R1 to R5) +- [ ] 1.1 `crypto::decode` forwards PEM to codecs, `detail::decode_pem` removed, the `noexcept` check; the PEM tests of the toy and the curves (no heap through `codecs::decode`, `input_too_long` past the bound, codecs' wipe); every `formats` test of a direct DER or raw input past its pair's bound moved to `input_too_long`; a largest-valid-input test per pair; the guide, the errors page's tables and the changelog's source entry (R1 to R5, R2a) ## 2. The delivery From 68966d96bec804b9fbec7e492994db6f1414d07d Mon Sep 17 00:00:00 2001 From: R Date: Mon, 30 Nov 2026 22:02:51 -0300 Subject: [PATCH 05/10] codecs: over-in-place records owner decision 30, the in-place intermediate capped at 4096 bytes, the heap above refused before allocating and wiped when secret; no open question left --- .../openspec/changes/over-in-place/design.md | 34 ++++++++----------- .../changes/over-in-place/proposal.md | 2 +- .../changes/over-in-place/reference/plan.md | 28 ++++++++------- .../over-in-place/specs/codecs/spec.md | 8 +++-- .../openspec/changes/over-in-place/tasks.md | 2 +- 5 files changed, 38 insertions(+), 36 deletions(-) diff --git a/libraries/codecs/openspec/changes/over-in-place/design.md b/libraries/codecs/openspec/changes/over-in-place/design.md index 7c7ed4b..830dd50 100644 --- a/libraries/codecs/openspec/changes/over-in-place/design.md +++ b/libraries/codecs/openspec/changes/over-in-place/design.md @@ -1,21 +1,8 @@ ## Open questions for the owner -One choice changes the public contract and nothing decided so far answers it. The plan is -written with its recommendation; the places that change with the answer are marked "(Q2)" in the -plan. (Q1, the error of an input past the decode bound, was answered by the owner on 2026-11-30: -owner decision 29.) - -1. **Q2. The cap on the in-place intermediate of a decode bound.** The genesis puts an - intermediate of a static bound in place with no cap (its R3): the caller chose a static input - and can pass a view of a dynamic extent to reach the heap. A decode bound is the format - author's, and the caller has no such escape; a value codec of a certificate or of a JSON - document may state tens of kilobytes, and Emscripten's default stack is 64 KiB. - - **A (recommended): in place when the bound is at most 4096 bytes, on the heap above it**, - the bound still checked before the allocation. 4096 is the owner's own threshold of - 2026-11-26 for `assign_to`'s scratch (`detail::in_place_scratch_limit`), reused, not a new - number. Every crypto bound (at most 138 today, 83 for PKCS#8 v2) is far below it. - - **B: no cap**, as the genesis' R3: simpler to state, but a large bound costs every caller its - stack, with no way out. +None. Both questions the design asked were answered by the owner on 2026-11-30: Q1 (the error of +an input past the decode bound) by owner decision 29, Q2 (the cap on the in-place intermediate) +by owner decision 30. ## Context @@ -96,6 +83,14 @@ errors for one input past the bound depending on the path it took. (`decode(format, input)`, every input type a caller's buffer can be, public and secret) and through `over` alike. +30. **The in-place intermediate of a decode bound is capped at 4096 bytes** (2026-11-30, this + design's question Q2, option A): in place when the bound is at most 4096 bytes, on the heap + from `over`'s allocator above it, the input still refused before any allocation when it is + past the bound, and the heap intermediate wiped when the chain is secret. 4096 is the owner's + threshold of 2026-11-26 for `assign_to`'s scratch (`detail::in_place_scratch_limit`), reused; + a format author's bound must not cost every caller a large stack with no escape (Emscripten's + default stack is 64 KiB). + The numbers 1 to 27 are the genesis'; this change continues them. ## Decisions @@ -136,7 +131,7 @@ Value, View>()`, the smallest of the bounds known at compile time: | static size `N` | decode bound `D` at most 4096 | in place, the smaller of the two | | static size `N` | decode bound `D` above 4096 | in place, `codec::max_decoded_size(N)` (the genesis' rule for a static text, no cap) | | dynamic | decode bound `D` at most 4096 | in place, `D` (this change) | -| dynamic | decode bound `D` above 4096 | heap, from `over`'s allocator, exactly the written size, at most `D` (Q2) | +| dynamic | decode bound `D` above 4096 | heap, from `over`'s allocator, exactly the written size, at most `D`, wiped when secret (owner decision 30) | | dynamic | no decode bound | heap, from `over`'s allocator (genesis, unchanged) | A bound of `SIZE_MAX` is above 4096 and never refuses anything: it is no bound, with no special @@ -252,8 +247,7 @@ lane as every example. The changelog's line under "Unreleased". allows", and refusing before the allocation also bounds the heap path - cost if wrong: the check is one comparison in one funnel; crypto's `pem-forward` changes its tests and spec for the over-long inputs of its DER, raw and PEM formats. -- **R5. Ruling: a decode bound above 4096 bytes keeps the heap intermediate (Q2, recommendation - A), reusing `detail::in_place_scratch_limit`, moved from tokens.hpp to size_maximum.hpp so that +- **R5. Owner decision 30: a decode bound above 4096 bytes keeps the heap intermediate, reusing `detail::in_place_scratch_limit`, moved from tokens.hpp to size_maximum.hpp so that `over.hpp` and `tokens.hpp` share it** - why: the owner's own threshold for `assign_to`'s scratch, and a format author's bound must not cost every caller a large stack with no escape; Emscripten's default stack is 64 KiB - cost if wrong: a value codec above 4096 bytes allocates @@ -333,4 +327,4 @@ stream under the owner's standing instruction, one CI at the end. Then `hpke`. ## Open Questions -Q2, at the top of this design. Q1 is answered (owner decision 29). Nothing else is open. +None: Q1 and Q2 are answered (owner decisions 29 and 30). diff --git a/libraries/codecs/openspec/changes/over-in-place/proposal.md b/libraries/codecs/openspec/changes/over-in-place/proposal.md index bb59d40..ea8b230 100644 --- a/libraries/codecs/openspec/changes/over-in-place/proposal.md +++ b/libraries/codecs/openspec/changes/over-in-place/proposal.md @@ -81,4 +81,4 @@ None. `pem-forward`, the superproject (both gitlinks). The plan is `reference/plan.md`. - **Status:** approved by the owner on 2026-11-30 (crypto `formats`' question Q1); accepted with `reference/plan.md`; the error past the bound decided by the owner on 2026-11-30 (owner - decision 29), the 4096 cap (design Q2) still open. + decision 29) and the 4096 cap (owner decision 30). diff --git a/libraries/codecs/openspec/changes/over-in-place/reference/plan.md b/libraries/codecs/openspec/changes/over-in-place/reference/plan.md index 0eddc08..01fd597 100644 --- a/libraries/codecs/openspec/changes/over-in-place/reference/plan.md +++ b/libraries/codecs/openspec/changes/over-in-place/reference/plan.md @@ -34,9 +34,8 @@ and owner decision 23. ## Open for the owner Q1 is answered: owner decision 29 (2026-11-30), the core enforces the bound on every path with -`input_too_long`. The design's Q2 (the 4096 cap; recommended) is open; this plan is written with -its recommendation, the places that change marked "(Q2)": with Q2's B, Task 2 drops the cap's -condition and its test. +`input_too_long`. Q2 is answered: owner decision 30 (2026-11-30), in place up to 4096 bytes, the +heap above, refused before allocating, the heap intermediate wiped when secret. Nothing is open. **Paths:** `$W` is the owner's workspace directory, the folder that holds `heavy.sh`, `msvc-lane/`, `linux-lint/` and this stream's folder `codecs-over/` (a plan in the proposals @@ -260,7 +259,8 @@ constexpr void check_value_bounds() noexcept { shape of crypto's PKCS#8 v1 and the deferred v2). - `sealed_record`: the same codec with `secret = true` (its bytes in a `secure::secret<8>`). - `wide_record` (a count): decode only, `max_decode_input_size = 4097`, any length up to 4097 - accepted (the count of bytes), longer `invalid_length`. + accepted (the count of bytes), longer `invalid_length`; `sealed_wide_record`, the same with + `secret = true`. - `short_text` (a string of up to 20 letters): a value codec of `output_kind::text`, `max_encoded_size = 20`, `max_decode_input_size = 20`. - `tight_record`: `short_record`'s codec with `max_encoded_size = 12` and @@ -328,7 +328,7 @@ Model tier: most capable (the core's `noexcept` and secret paths). Size: L. namespace webcpp::codecs::detail { // The bound the intermediate of a decode of View into a Value through Outer over Inner is held // in place under (design D2): the smaller of the outer link's bound on a text of a static size -// and the inner value codec's decode bound when it is at most in_place_scratch_limit (Q2); +// and the inner value codec's decode bound when it is at most in_place_scratch_limit (owner decision 30); // std::dynamic_extent when neither is known. std::dynamic_extent is SIZE_MAX, so the smaller of // two is (std::min) of them. template @@ -375,12 +375,16 @@ decode bound, the cap, the refusal and that `over`'s own value codec states no d outer link's `invalid_character`, found by its `decoded_size`: no intermediate, no erase), 17 bytes (`input_too_long`, no intermediate, no erase); the same chain over `short_record`, a public value, records no erase. - - `a_bound_above_the_cap_takes_the_allocator` (Review Focus 4, Q2): `over{formats::hex, - test::bounded, std::pmr::polymorphic_allocator{&arena}}` (`test/support/arena.hpp`) - decodes a `wide_record` of 4097 bytes from a `std::string` (one arena allocation of 4097 - bytes), of 4098 bytes (`input_too_long`, no arena allocation), and an `edge_record` of 4096 - bytes (no arena allocation, in place); `noexcept` false for `wide_record`'s chain, true for - `edge_record`'s. + - `a_bound_above_the_cap_takes_the_allocator` (Review Focus 4, owner decision 30): + `over{formats::hex, test::bounded, std::pmr::polymorphic_allocator{&arena}}` + (`test/support/arena.hpp`) decodes a `wide_record` (bound 4097, just above the cap) of 4097 + bytes from a `std::string` (exactly one arena allocation, of 4097 bytes), of 4098 bytes + (`input_too_long`, the arena untouched: refused before allocating), and an `edge_record` of + 4096 bytes (no arena allocation, in place); `noexcept` false for `wide_record`'s chain, true + for `edge_record`'s; `sealed_wide_record` (`wide_record`'s codec with `secret = true`) through + the same chain over `test/support/allocators.hpp`'s `wipe_checking_allocator`: one allocation + of 4097 bytes, every byte erased before it is given back (on success and on the value codec's + refusal), and 4098 bytes `input_too_long` with no allocation. - `one_error_whatever_the_path` (Review Focus 6, 7): 17 bytes of `short_record` and of `sealed_record` through `over{formats::hex, test::bounded}` and `over{formats::armor("RECORD"), test::bounded}` from a `std::string_view` and from `codecs::text` give `input_too_long`, @@ -579,7 +583,7 @@ $H $B2 doc `main`, every job green, and its failures fixed in follow-up commits as the autopilot rule says. - [ ] HANDBACK: `$W/codecs-over/HANDBACK.md` with the merged SHAs, the lanes' results, the - findings of the final review and their fixes, owner decision 29 and the answer to Q2 as built, and a + findings of the final review and their fixes, owner decisions 29 and 30 as built, and a line for the `hpke` stream: `codecs::decode` of a PEM format no longer allocates, and crypto's verbs are forwards. diff --git a/libraries/codecs/openspec/changes/over-in-place/specs/codecs/spec.md b/libraries/codecs/openspec/changes/over-in-place/specs/codecs/spec.md index d053b0b..03dddb8 100644 --- a/libraries/codecs/openspec/changes/over-in-place/specs/codecs/spec.md +++ b/libraries/codecs/openspec/changes/over-in-place/specs/codecs/spec.md @@ -1,7 +1,7 @@ ## ADDED Requirements ### Requirement: Composition: over decodes a value in place under its decode bound -A decode of a `Value` through `codecs::over`, where `value_codec` states `max_decode_input_size` `D`, SHALL hold its intermediate in place, with no heap, when `D` is at most 4096, whatever the text's type: its size is the smallest bound known at compile time among `D` and the outer link's `max_decoded_size` of a text of a static size. Above 4096, and when the inner value codec states no decode bound, the intermediate MUST be held as the requirement "Composition: over" says (in place for a text of a static size, else from `over`'s allocator). In every case the decode MUST check, in this order: the chain's configuration, the outer link's whole text (its `decoded_size`, whose error is returned first), then the exact size of the intermediate against `D`, returning `codecs::error::input_too_long` (the error of the direct path) when it is past `D` before any intermediate is made, allocated or written, so that the inner value codec never receives more than `D` elements from `over`; then the outer link's decode into the intermediate and the inner value codec's decode, whose errors reach the caller unchanged. With the intermediate in place the decode MUST be `noexcept` when the links' calls are, the typed `decode` with it. A secret operation MUST wipe the intermediate's written bytes by `secure::erase_secret` on every path. `over`'s own value codec MUST NOT state `max_decode_input_size`. +A decode of a `Value` through `codecs::over`, where `value_codec` states `max_decode_input_size` `D`, SHALL hold its intermediate in place, with no heap, when `D` is at most 4096, whatever the text's type: its size is the smallest bound known at compile time among `D` and the outer link's `max_decoded_size` of a text of a static size. Above 4096 the intermediate MUST come from `over`'s allocator, exactly the written size and wiped before it goes back when the chain is secret, after the size check refuses an input past `D` without allocating; when the inner value codec states no decode bound, the intermediate MUST be held as the requirement "Composition: over" says (in place for a text of a static size, else from `over`'s allocator). In every case the decode MUST check, in this order: the chain's configuration, the outer link's whole text (its `decoded_size`, whose error is returned first), then the exact size of the intermediate against `D`, returning `codecs::error::input_too_long` (the error of the direct path) when it is past `D` before any intermediate is made, allocated or written, so that the inner value codec never receives more than `D` elements from `over`; then the outer link's decode into the intermediate and the inner value codec's decode, whose errors reach the caller unchanged. With the intermediate in place the decode MUST be `noexcept` when the links' calls are, the typed `decode` with it. A secret operation MUST wipe the intermediate's written bytes by `secure::erase_secret` on every path. `over`'s own value codec MUST NOT state `max_decode_input_size`. #### Scenario: A value from a run-time text with no heap - **WHEN** a value codec of the test's own states `max_encoded_size = 12` and `max_decode_input_size = 16`, and its 12-byte and 16-byte forms are decoded with `codecs::decode(codecs::over{codecs::formats::hex, format}, text)` and through `codecs::over{codecs::formats::armor("RECORD"), format}`, `text` a `std::string_view`, under a counting `operator new` @@ -17,7 +17,11 @@ A decode of a `Value` through `codecs::over`, where `va #### Scenario: A bound above the cap - **WHEN** a value codec states `max_decode_input_size = 4097` and a chain over it with an arena's allocator decodes a run-time text of 4097 bytes, then one of 4098 -- **THEN** the first allocates once from the arena, exactly 4097 bytes, and the second is `input_too_long` with no allocation +- **THEN** the first allocates once from the arena, exactly 4097 bytes, and the second is `input_too_long` with no allocation, refused before allocating + +#### Scenario: A secret heap intermediate is wiped +- **WHEN** a secret value codec with `max_decode_input_size = 4097` decodes 4097 bytes through `over` with a wiping-checking allocator, then 4098 bytes +- **THEN** the first allocates once, 4097 bytes, every byte erased before the allocator gets them back, and the second is `input_too_long` with no allocation #### Scenario: The fuzz target of the value chain - **WHEN** the fuzz target `over_value` runs for its bounded time from its corpus diff --git a/libraries/codecs/openspec/changes/over-in-place/tasks.md b/libraries/codecs/openspec/changes/over-in-place/tasks.md index 605c69f..8338026 100644 --- a/libraries/codecs/openspec/changes/over-in-place/tasks.md +++ b/libraries/codecs/openspec/changes/over-in-place/tasks.md @@ -7,7 +7,7 @@ change `pem-forward` (`libraries/crypto/openspec/changes/pem-forward/`) in the s ## 1. The contract and over - [ ] 1.1 The decode bound in the value codec contract: `max_decode_input_size` read by the core and enforced on every direct path, public and secret, every caller's buffer (`input_too_long`, owner decision 29), the bounds' order checked at compile time with its message test, `in_place_scratch_limit` shared (D1, D3, R1, R2, R4, R5) -- [ ] 1.2 `over` decodes a value in place under the decode bound: the middle bound of D2, the refusal of D3 before any intermediate, `noexcept` and no heap, the wipe on every path, the cap and the fallback unchanged (D2 to D5, R3 to R9) +- [ ] 1.2 `over` decodes a value in place under the decode bound: the middle bound of D2, the refusal of D3 before any intermediate, `noexcept` and no heap, the wipe on every path, the cap and the fallback unchanged (D2 to D5, R3 to R9, owner decision 30) ## 2. The own lanes From 54e7764d22c6bb8dd1d2a7786c31d789bb5ada80 Mon Sep 17 00:00:00 2001 From: R Date: Wed, 2 Dec 2026 14:11:42 -0300 Subject: [PATCH 06/10] codecs: over-in-place becomes one-verb, owner decision 31: a value type's formats and reasons declared to codecs (value_formats), one refusal through every value operation, the armor's label in its type (basic_armor), the decode bound and over in place as planned --- README.md | 2 +- .../openspec/changes/one-verb/.openspec.yaml | 11 + .../openspec/changes/one-verb/design.md | 667 ++++++++++++++++++ .../openspec/changes/one-verb/proposal.md | 117 +++ .../reference/plan.md | 530 ++++++++++---- .../changes/one-verb/specs/codecs/spec.md | 161 +++++ .../codecs/openspec/changes/one-verb/tasks.md | 29 + .../changes/over-in-place/.openspec.yaml | 11 - .../openspec/changes/over-in-place/design.md | 330 --------- .../changes/over-in-place/proposal.md | 84 --- .../over-in-place/specs/codecs/spec.md | 90 --- .../openspec/changes/over-in-place/tasks.md | 24 - 12 files changed, 1383 insertions(+), 673 deletions(-) create mode 100644 libraries/codecs/openspec/changes/one-verb/.openspec.yaml create mode 100644 libraries/codecs/openspec/changes/one-verb/design.md create mode 100644 libraries/codecs/openspec/changes/one-verb/proposal.md rename libraries/codecs/openspec/changes/{over-in-place => one-verb}/reference/plan.md (52%) create mode 100644 libraries/codecs/openspec/changes/one-verb/specs/codecs/spec.md create mode 100644 libraries/codecs/openspec/changes/one-verb/tasks.md delete mode 100644 libraries/codecs/openspec/changes/over-in-place/.openspec.yaml delete mode 100644 libraries/codecs/openspec/changes/over-in-place/design.md delete mode 100644 libraries/codecs/openspec/changes/over-in-place/proposal.md delete mode 100644 libraries/codecs/openspec/changes/over-in-place/specs/codecs/spec.md delete mode 100644 libraries/codecs/openspec/changes/over-in-place/tasks.md diff --git a/README.md b/README.md index 5e62162..a234aaf 100644 --- a/README.md +++ b/README.md @@ -49,7 +49,7 @@ tag is placed. | beast | [genesis](libraries/beast/openspec/changes/genesis) | beast: existing Boost.Beast applications on WASIp2, WASIp3 and Emscripten | wrapper | implementing | | 2026-11-06 | [code](https://github.com/webcpporg/beast) | | cobalt | [genesis](libraries/cobalt/openspec/changes/genesis) | cobalt: existing Boost.Cobalt applications on native, browsers and WASIp2/P3 | wrapper | implementing | | 2026-11-06 | [code](https://github.com/webcpporg/cobalt) | | codecs | [genesis](libraries/codecs/openspec/changes/genesis) | codecs: one contract for turning bytes and values into text and back, one header per format, tokens like Boost.URL | own | implementing | | 2026-11-24 | [code](https://github.com/webcpporg/codecs) | -| codecs | [over-in-place](libraries/codecs/openspec/changes/over-in-place) | codecs: over decodes a value in place under the inner value codec's decode bound | own | accepted | | 2026-11-30 | | +| codecs | [one-verb](libraries/codecs/openspec/changes/one-verb) | codecs: one verb for every library: a value type's formats declared to codecs, the armor's label in its type, over decoding a value in place | own | accepted | | 2026-12-02 | | | config | [genesis](libraries/config/openspec/changes/archive/2026-10-09-genesis) | config: webcpp's configuration, the target, exceptions and version every library includes first | own | implemented | 0.1.0 | 2026-10-09 | [code](https://github.com/webcpporg/config/tree/2fad162) | | config | [timing-guard](libraries/config/openspec/changes/archive/2026-11-24-timing-guard) | config: one DIT timing guard for every webcpp library, moved from crypto and hash, Windows on ARM64 covered | own | withdrawn | | 2026-11-24 | | | crypto | [genesis](libraries/crypto/openspec/changes/genesis) | crypto: authenticated encryption, randomness and secp256k1 over C backends | wrapper | implementing | | 2026-10-11 | [code](https://github.com/webcpporg/crypto) | diff --git a/libraries/codecs/openspec/changes/one-verb/.openspec.yaml b/libraries/codecs/openspec/changes/one-verb/.openspec.yaml new file mode 100644 index 0000000..38b30b1 --- /dev/null +++ b/libraries/codecs/openspec/changes/one-verb/.openspec.yaml @@ -0,0 +1,11 @@ +schema: spec-driven +created: 2026-11-30 +webcpp: + library: codecs + title: "codecs: one verb for every library: a value type's formats declared to codecs, the armor's label in its type, over decoding a value in place" + kind: own + port_of: null + status: accepted + release: null + implementation: null + decided: 2026-12-02 diff --git a/libraries/codecs/openspec/changes/one-verb/design.md b/libraries/codecs/openspec/changes/one-verb/design.md new file mode 100644 index 0000000..3f6c992 --- /dev/null +++ b/libraries/codecs/openspec/changes/one-verb/design.md @@ -0,0 +1,667 @@ +## Open questions for the owner + +None. Both questions the first design asked were answered by the owner on 2026-11-30: Q1 (the +error of an input past the decode bound) by owner decision 29, Q2 (the cap on the in-place +intermediate) by owner decision 30. Owner decision 31 (2026-12-02, one verb) leaves one choice to +this design, how the PEM label stays the inner format's through codecs' verbs; R23 rules it. The +public names this change adds (`codecs::value_formats`, `codecs::format_list`, +`codecs::direction`, `codecs::check_conversion`, `codecs::formats::basic_armor`) are rulings +(R17, R22, R23); renaming any before Task 4 costs nothing. + +## Context + +This change builds on webcpp::codecs as merged (codecs#1, `80d90d0`, its genesis +`libraries/codecs/openspec/changes/genesis/`, owner decisions 1 to 27 and the rulings of its +implementation) and on crypto's `formats` change as merged (`libraries/crypto/openspec/changes/formats/`, +crypto#20, webcpp#62), which ran right before it. It began as `over-in-place` (owner decisions 28 +to 30, 2026-11-30); owner decision 31 (2026-12-02) widened it to one verb for every library, and +it was renamed `one-verb` with crypto's follow-up (R16). + +**The verbs today.** crypto's `formats` gave crypto its own verbs, `crypto::encode` and +`crypto::decode` (crypto's owner decision 16 and ruling R18): function templates that check the +pair against crypto's list first and then forward to `codecs::encode` and `codecs::decode`, +because codecs' own refusal of a pair (genesis R2: a `static_assert` whose requirement is +`detail::converts` and whose message is "this format does not convert this type") +cannot name the formats a type has. crypto's check (its D3, as built in `formats.hpp`: +`detail::pair_accepted`, `detail::refuse_pair`, `detail::refusal_reason_v`, +`detail::decode_refusal_reason_v`, `detail::formats_of`, `detail::forms_of`) stops the build, with +that error alone, in this order: the curve's formats header not included ("include +/formats.hpp>"), a `forms_of` without the default form, the pair's own +reason (`der` on an Ed25519 or BIP340 signature, `der` on a recoverable signature, `raw(xonly)` +decoded into a `secp256k1::public_key`, a private format on a key pair whose secret lives in +WebCrypto), then "this type has no such format; the formats it has are the format_list named in +this assertion", the type's `format_list` printed in the failed requirement, then "this type lists +the format, and no codecs::value_codec of the pair encodes (decodes) it". A program that calls +codecs' verbs with crypto's formats gets the same bytes and values and codecs' generic +diagnostic. Two verbs answer one question; owner decision 31 keeps one. + +**The PEM label today.** crypto's `formats::pem(F)` is `codecs::over`, +the armor configured with `detail::pem_label_v` (`PUBLIC KEY`, `PRIVATE KEY`). The armor's label +is a value (`armor_t` holds up to 64 characters, `formats::armor("PUBLIC KEY")`), so a hand-built +`formats::pem_t{codecs::formats::armor("CERTIFICATE"), F{}}` is a valid object; +`crypto::encode` and `crypto::decode` replace its armor by the inner format's (as built, design D2 +(3) of `formats`), and `codecs::encode` with the same object writes `CERTIFICATE`. A PEM result's +capacity is the armor's bound over every label (crypto's R20: 347 characters for P-256's +`pem(pkcs8)`, whose text is 241). + +What codecs does today, in `include/webcpp/codecs/detail/core/over.hpp`: + +- `over` holds its intermediate in `in_place_intermediate` + (a `std::array` in the frame of each of its functions, its written bytes wiped by + `secure::erase_secret` when the chain is secret) when `Bound` is known at compile time, and in + `heap_intermediate` (a `std::vector` or a `basic_secret_byte_vector` of + `over`'s allocator) otherwise. +- For a decode, `Bound` is `decoded_bound>()`, the outer link's + `max_decoded_size` of the text's static size, or `std::dynamic_extent` for a `std::string_view`. + The value decode (`over_value_decode`) asks the outer link's exact `decoded_size` (which checks + the whole text, so the outer link's data errors come first), refuses a size past `Bound` with + `input_too_long`, makes the intermediate, decodes the outer link into it and gives the written + bytes to the inner value codec's `decode`. +- Its `noexcept` (genesis R3) follows the intermediate: `over_value_decode_is_noexcept` is false + whenever `Bound` is `std::dynamic_extent`, so the typed `decode` of such a chain is not + `noexcept`. +- A value codec states `output`, optionally `secret`, optionally `max_encoded_size` (which sizes + the encode's intermediate and the default result); it states nothing about the longest input + its decode takes. `SIZE_MAX` (`detail::size_maximum`, equal to `std::dynamic_extent`) is the + saturated bound that means "no size to hold in place". +- `detail::in_place_scratch_limit = 4096` (tokens.hpp) is the threshold the owner set on + 2026-11-26 for `assign_to`'s scratch: in place up to 4096 elements, the target's allocator + above. + +What crypto does after `formats` (its design R24, R37 and owner decision 23): each crypto value +codec that decodes states `max_decode_input_size` (crypto's `formats.hpp` checks it is there and, +today, that it equals `max_encoded_size`); `crypto::decode` of `pem(F)` calls +`detail::decode_pem`, which decodes the armor through codecs' buffer form into a +`std::array>`, maps `output_too_small` to +`crypto::error::invalid_encoding`, then calls `codecs::decode(format.inner, ...)` and wipes +the buffer of a secret pair; `codecs::decode` of the same format and text allocates, which crypto's +guide and tests state as "the documented difference". + +## Goals / Non-Goals + +**Goals:** one error, codecs' `input_too_long`, for every input past a value codec's decode +bound, on every path (owner decision 29); `codecs::decode(over{outer, inner}, text)` of a text of a dynamic size, when the +inner value codec states a decode bound, holds its intermediate in place, allocates nothing and is +`noexcept` when the links' calls are; the inner value codec never receives more than its decode +bound from `over`; a secret intermediate is wiped on every path; crypto's PEM decode needs +nothing of its own (owner decisions 28 to 30). `codecs::encode` and `codecs::decode` are the +verbs of every library (owner decision 31): a library declares, for each value type it owns, +the formats the type has and its pairs' own reasons, and every operation of codecs refuses a pair +of that type with the type's list in the failed requirement, or with the library's sentence, as +crypto's D3 does today, with that error alone; a type with no declaration keeps the genesis' +diagnostic; an armored format whose label follows from its content carries the label in its type, +so that no value of it holds another (crypto's owner decision 1 through codecs' verbs). + +**Non-goals:** a decode bound on `codec` (a codec's `max_decoded_size(n)` already bounds a +decode from its input's size); a decode bound on `over`'s own value codec (R8); the encode side +of `over` (its intermediate is already in place under `max_encoded_size`, and its outer link's +encode fault after `prepare` stays as the genesis documents, R12); a stream form of a value +codec's `over` (decision 17 of the genesis: a value codec has no transformer); PKCS#8 v2, which +stays deferred (crypto's owner decision 23); a declaration for a byte input or a byte result +(`codec`'s pairs, whose diagnostic stays the genesis'); a format chosen at run time; a +diagnostic text computed at compile time (C++26's `static_assert` with a constant-expression +message; codecs is C++20); removing `formats::armor_t` or its run-time label. + +**Anti-goals:** a heap allocation where the decode bound is known and small; a stack array sized +by a bound the caller cannot see or escape; a secret byte of the intermediate left unwiped; two +errors for one input past the bound depending on the path it took; two verbs for one conversion; +a refusal that is a cascade of errors or an overload-resolution failure where the declaration +holds a sentence; a PEM label a caller can get wrong through any verb. + +## Approaches + +The decode bound and the in-place `over` were chosen on 2026-11-30 (owner decisions 28 to 30, +"Decisions" D1 to D8). The approaches below are those of owner decision 31. + +**The verb.** + +- **A. Keep crypto's verbs** (crypto's R18 as built): two verbs per conversion, the same bytes, + two diagnostics. Rejected by the owner (decision 31, option A of the question). +- **B (chosen, owner decision 31).** One verb, codecs', and an extension point of codecs through + which a library declares a value type's formats and its pairs' reasons, so that codecs' own + refusal names the type's list and says the library's sentence. +- **C. Using-declarations** (`namespace crypto { using codecs::encode; }`): one implementation, + two spellings, and the diagnostics lose the list (crypto's R18's cost line). Rejected: the owner + wants one name and the list. +- **D. The library's diagnostics in the value codec**: a `value_codec` is a pair; a refused pair + has no specialization to hold a sentence, and the list is per type, not per pair. Rejected. + +**The extension point's shape.** + +- **E (chosen). A class template per value type, `codecs::value_formats`, declared and + not defined, as `value_codec` is**: its `formats` (a `codecs::format_list`), an optional + predicate `has_format` for a type whose list names a family of formats (crypto's point + forms), and an optional pair of members `has_reason` and + `refuse()`, the library's own `static_assert` with its fixed text. A partial + specialization constrained by a concept declares a family of types at once. +- **F. Sentences as `std::string_view` data that codecs puts in its own `static_assert`**: + impossible in C++20, whose `static_assert` message is a string literal (the genesis' R2 met the + same limit with `F::name`). Rejected. +- **G. A reason enumeration of codecs'**: codecs would hold crypto's sentences, or a fixed set of + generic ones that cannot say "Ed25519 and BIP340 signatures have no DER form". Rejected. + +**The PEM label through codecs' verbs.** + +- **H (chosen, R23). The label in the armor's type**: codecs gains + `formats::basic_armor