Skip to content

Tidy the drift the allocation series left behind - #235

Merged
kahrendt merged 2 commits into
mainfrom
coherence-drift
Nov 3, 2026
Merged

kahrendt merged 2 commits into
mainfrom
coherence-drift

Conversation

@kahrendt

@kahrendt kahrendt commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

Summary

A coherence review of the allocation series (#225-#234) found the migrated pieces consistent with each other, plus a set of small inconsistencies at their edges. This PR fixes those. No behavior change.

Change

  • Caps: MAX_SERVER_INIT_BYTES moves from noise_handshake.h to crypto/constants.h, beside MAX_HANDSHAKE_MESSAGE_BYTES; each comment names the other.
  • Inline text:
    • InlineText::assign() is [[nodiscard]]; each caller checks it, or casts to (void) with the reason its text fits (or, for the last-played id, that clearing is the documented behavior).
    • set_noise_handshake_result() and run_rehandshake_msg1() take const IdText& instead of re-assigning views. last_played_server_id() returns const IdText&, like get_server_id().
    • ResolvedPsk::counterparty_id is a plain IdText, empty for a PSK bound to no server, instead of std::optional<IdText>.
    • SENTINEL_PSK_ID is a constexpr std::string_view literal instead of a global std::string built during static initialization.
    • The connection's id and name members sit in its "String fields" group.
  • ParsedJsonMessage::extract() static_asserts that an extractor does not return a pointer, a std::string_view, or a JsonVariant/JsonObject/JsonArray/JsonString (alone or in std::optional), since the document is released before the caller reads it.
  • Comments: the stale "hub" comments name the real callers (protocol task, ConnectionManager, transport threads); the ESP start() comment describes when the connection is delivered.
  • Naming: the activation check left over from ConnectionTrust is "the admissibility check" in src, docs and tests, matching admissible() and inadmissible_reject_reason().

Tests

  • Tests build ids through a new id_text() helper in tests/record_test_helpers.h, which fails a test whose id would not fit.
  • CryptoConstants.SentinelPskIdMatchesSpecConstant now checks that psk_id_for(SENTINEL_PSK) derives the literal, so it fails if either drifts.
  • The extract() guard was checked with a probe: an extractor returning a std::string_view fails to compile with the new message, one returning an int compiles.

A coherence review of the series found small inconsistencies:

- MAX_SERVER_INIT_BYTES moves beside MAX_HANDSHAKE_MESSAGE_BYTES in
  crypto/constants.h, each naming the other.
- InlineText::assign() is [[nodiscard]]: each caller checks it or says
  why its text fits. The handshake glue (set_noise_handshake_result(),
  run_rehandshake_msg1()) takes IdText instead of re-assigning views,
  ResolvedPsk::counterparty_id is empty when unset like every other id,
  and SENTINEL_PSK_ID is a constexpr literal instead of a std::string
  built during static initialization.
- ParsedJsonMessage::extract() refuses, at compile time, an extractor
  that returns a pointer, a string_view or an ArduinoJson reference.
- Comments that still named the ESPHome hub name the real callers, and
  the activation check left over from ConnectionTrust is called the
  admissibility check, as admissible() is.

No behavior change.
@kahrendt
kahrendt marked this pull request as ready for review November 3, 2026 19:02
@kahrendt
kahrendt requested a max review from Copilot November 3, 2026 19:02

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

The extractor guard misses const-qualified optional string views and JSON handles, potentially allowing dangling results after the document is released.

2 open issues
What changed in this PR

Tidies the allocation-reduction work by aligning internal ID handling, compile-time ownership checks, and documentation across the cross-platform Sendspin library.

Changes:

  • Standardizes inline IDs and explicit assignment handling, with checked test helpers.
  • Centralizes handshake limits and replaces startup construction of the Sentinel PSK ID with a constant literal.
  • Adds JSON extraction lifetime checks and updates admission terminology and threading comments.
File Description
tests/​test_source_role.cpp Uses checked inline IDs in connection setup.
tests/​test_record_store.cpp Adapts assertions to empty counterparty IDs.
tests/​test_pairing_state_machine.cpp Updates inline IDs and admissibility comments.
tests/​test_noise_rehandshake.cpp Supplies checked IDs to re-handshakes.
tests/​test_encrypted_lifecycle.cpp Updates connection IDs and admission comments.
tests/​test_crypto.cpp Checks the Sentinel ID against its derivation.
tests/​test_client_lifecycle.cpp Uses checked inline IDs in fixtures.
tests/​test_admission.cpp Renames trust terminology in comments.
tests/​record_test_helpers.h Adds the checked id_text() helper.
tests/​lifecycle_test_fixtures.h Clarifies PSK-category terminology.
src/​record_store.h Makes counterparty IDs non-optional.
src/​record_store.cpp Documents intentionally ignored assignment results.
src/​protocol.cpp Documents bounded friendly-name assignment.
src/​platform/​json_arena.h Adds compile-time extraction return checks.
src/​noise_handshake.h Accepts inline IDs and relocates the initialization cap.
src/​noise_handshake.cpp Removes redundant ID conversions.
src/​inline_text.h Marks assignment results [[nodiscard]].
src/​esp/​server_connection.cpp Corrects the transport-start comment.
src/​crypto/​constants.h Groups handshake caps and defines the Sentinel ID literal.
src/​crypto/​constants.cpp Removes runtime Sentinel ID construction.
src/​connection.h Copies inline IDs and updates field grouping and thread notes.
src/​connection.cpp Passes inline IDs directly through handshakes.
src/​connection_manager.h Returns the stored inline ID and refreshes comments.
src/​connection_manager.cpp Renames the activation check without changing its logic.
src/​client_dispatch.cpp Updates admission and unpairing comments.
src/​admission.h Renames trust enforcement to admissibility.
docs/​internals.md Aligns activation documentation with admissibility terminology.
docs/​conventions.md Updates the activation-handler terminology.

Review effort: Max

Comment thread src/platform/json_arena.h Resolved
Comment thread src/connection.h Resolved
RefersIntoDocument stripped only top-level qualifiers, so an extractor
returning std::optional<const std::string_view> (or an optional const
ArduinoJson handle) passed the static_assert. The optional case now
checks its element without cv-qualifiers.

is_ws_upgraded() is read on the transport thread too, by the host
client's close_transport_now(), so its doc and the flag's say so.
@kahrendt
kahrendt merged commit 2d3cafd into main Nov 3, 2026
16 checks passed
@kahrendt
kahrendt deleted the coherence-drift branch November 3, 2026 19:35
kahrendt added a commit that referenced this pull request Nov 3, 2026
## Summary

The coherence review from #235 of the allocation series found peer text
copied before any length check: the `server/error` reason (up to the 16
KiB pre-admission cap, unauthenticated), the msg1 `psk_category`, the
pairing fields, and the `noise/handshake` data itself. This PR reads
each in place or refuses it before it is copied.

## Change

- **`server/error`:** the reason is parsed into `ServerErrorReason`
(`UNSUPPORTED_VERSION`, `UNSUPPORTED_SUITE`, `MALFORMED`, `UNKNOWN`),
the three reasons messaging.md "server/error" defines.
`server_error_reason()` returns `std::optional<ServerErrorReason>`,
nullopt when no `server/error` arrived. The reason and an unexpected
frame `type` are logged up to `PEER_TEXT_LOG_BYTES` (32).
- **msg1 payload:** `psk_category` is parsed from the view inside
`extract()`. A new `to_cstr(PskCategory)` gives the wire code
(`lt`/`pr`/`sn`), which the five category logs now print instead of
`%d`.
- **Pairing fields:** `b64url_decode_exact<N>` (`platform/base64.h`)
decodes `nonce_A`, `pake_msg_1` and `server_kc` straight into their
arrays, replacing `as<std::string>()` plus a `std::vector` decode. The
three parsers share one shape, so a validate-only call checks the
decoded length too, as their docs say. `public_key_from_peer_id()` uses
the same helper.
- **msg1 size:** `MAX_HANDSHAKE_MSG1_BYTES` (ephemeral key +
`MAX_HANDSHAKE_MESSAGE_BYTES` payload + tag = 560) refuses longer
`noise/handshake` data before its buffer is allocated; a `static_assert`
ties it to `X25519_KEY_SIZE` and `AEAD_TAG_SIZE`.
- **Full-length reads:** the six handshake fields (`psk_id`,
`psk_category`, `data`, the reason, `type`, `server_id`) are read with
`| std::string_view("")` instead of `| ""`, whose `const char*` stops at
an embedded NUL; a `server_id` with a NUL suffix was cut back to the
real id and accepted.

## Tests

- `ServerErrorWhileAwaitingServerInitAborts` is a table over every
defined reason, unknown text, a non-string and a missing reason, with a
non-`server/error` abort as the nullopt control row (it replaces
`AbortWithoutServerErrorReportsNoReason`).
- `HandshakeDataLongerThanAMsg1IsRefused` checks the msg1 cap at and one
byte over.
- The three pairing parser tables gain an over-length row (33/33/65
bytes); over-length input had no test before.
- NUL-suffixed rows for the reason (`UNKNOWN`), `psk_category` (abort),
`psk_id` (Sentinel fallback), `type` and `server_id` (refused); each
fails with the `| ""` read.
- Mutants killed: a reason mapped to `UNKNOWN`, `b64url_decode_exact`
accepting any decoded size, a wrong output capacity (caught by ASan on
the over-length rows), and the msg1 cap moved by one.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants