Skip to content

Commit 2d3cafd

Browse files
authored
Tidy the drift the allocation series left behind (#235)
## 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.
1 parent 93a2c67 commit 2d3cafd

28 files changed

Lines changed: 153 additions & 125 deletions

‎docs/conventions.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,7 @@ checklists in `.claude/skills/` apply these standards to a diff.
8080
call back into the client. See "Re-entrant Teardown During Callback
8181
Dispatch" in `docs/internals.md` for the guard patterns in use.
8282
- A message handler on the protocol task does the connection work the message
83-
calls for in place (an activation's trust check, admission and role
83+
calls for in place (an activation's admissibility check, admission and role
8484
ownership, a pairing step, a `noise/handshake` re-handshake, the RAM commit
8585
of a pairing record), and hands role and consumer work on through Inbox
8686
slots, role item lists and buffers. It never calls a listener or a

‎docs/internals.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -277,7 +277,7 @@ Role-bound traffic reaches a role only from the admitted connection that owns it
277277
| Message | Action on the protocol task |
278278
|---------|------------------------------|
279279
| `server/hello` | Records server info and the codecs its source@v1 support object lists on the connection, and sets `server_hello_received_` |
280-
| `server/activate` | `ConnectionManager::on_server_activate()`: trust and pairing-method checks, what the roles owed until the activation (`SendspinClient::on_activation_applied()`), role ownership and removals, and admission of a nursery connection the activation makes operational |
280+
| `server/activate` | `ConnectionManager::on_server_activate()`: admissibility and pairing-method checks, what the roles owed until the activation (`SendspinClient::on_activation_applied()`), role ownership and removals, and admission of a nursery connection the activation makes operational |
281281
| `server/time` | Claims the connection's `client/time` frame in flight, dropping a reply that answers none, and feeds the measurement to the connection's own time burst |
282282
| `server/state` | Writes the controller, metadata, and color `InboxSlot`s |
283283
| `server/command` | Merges the player object into the player's `command_slot`; the source object starts or ends the input stream (see [Source Stream Start and End](#source-stream-start-and-end)) |
@@ -389,7 +389,7 @@ Every role this client drives has at most one owner among the admitted connectio
389389

390390
1. An inbound connection is delivered by the platform server once its WebSocket upgrade completes, as an accept in the command queue; the protocol task takes it into the nursery and sends `client/init`. An outbound connection enters the nursery from `connect_to()` and sends `client/init` once its upgrade completes. The rest of the Noise handshake runs on the protocol task as messages arrive.
391391
2. Once `server/hello` arrives, the nursery scan sends `client/hello` (messaging.md "Client -> Server: client/hello").
392-
3. The connection is operational once both hellos are exchanged and its first `server/activate` arrives, in either order relative to the hellos. That activate is checked against the connection's trust when it is processed, and a rejected one closes the connection.
392+
3. The connection is operational once both hellos are exchanged and its first `server/activate` arrives, in either order relative to the hellos. That activate is checked for admissibility against the connection's PSK category when it is processed, and a rejected one closes the connection.
393393
4. The activation handler admits a connection the activation makes operational before it returns (the nursery scan covers a hello that completes after the activation), arbitrating against the admitted connections it conflicts with, mainly by highest activity (playback over pairing over none); `should_admit_connection()` in `src/admission.h` has the full rules.
394394
5. A losing newcomer is released with a goodbye; a displaced incumbent is dropped, and the roles no remaining connection owns are torn down.
395395

‎src/admission.h‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
// limitations under the License.
1414

1515
/// @file admission.h
16-
/// @brief Pure functions for server/activate trust enforcement, multi-server admission
16+
/// @brief Pure functions for the server/activate admissibility check, multi-server admission
1717
/// arbitration, and role ownership among admitted connections.
1818
///
1919
/// Implements the allowed-activity-set table and the rejection order in messaging.md
@@ -37,7 +37,7 @@
3737
namespace sendspin {
3838

3939
// ============================================================================
40-
// Trust enforcement (PSK category -> allowed activities)
40+
// Admissibility (PSK category -> allowed activities)
4141
// ============================================================================
4242

4343
/// @brief Whether an activity set is allowed for the matched PSK category.

‎src/client_dispatch.cpp‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -528,7 +528,7 @@ void SendspinClient::process_json_message(SendspinConnection& connection, const
528528
SS_LOGD(TAG, "server/activate received (playback=%d, pairing=%d)",
529529
activate_msg.activities.contains(SendspinActivity::PLAYBACK),
530530
activate_msg.activities.contains(SendspinActivity::PAIRING));
531-
// Applied before the next message is parsed: trust enforcement, role
531+
// Applied before the next message is parsed: the admissibility check, role
532532
// ownership and, for a nursery connection that is now operational, admission
533533
// all land here, so the role traffic the server sends behind this activate
534534
// meets the gate this activation set.
@@ -757,7 +757,7 @@ void SendspinClient::process_json_message(SendspinConnection& connection, const
757757
break;
758758
}
759759
case SendspinServerToClientMessageType::SERVER_UNPAIR: {
760-
// server/unpair. Trust gating (LONG_TERM only) happens in handle_server_unpair.
760+
// server/unpair. The LONG_TERM-only check happens in handle_server_unpair.
761761
parsed.release();
762762
SS_LOGI(TAG, "server/unpair received (psk_id=%s)", conn->get_psk_id().c_str());
763763
this->connection_manager_->on_server_unpair(conn);

‎src/connection.cpp‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -279,8 +279,8 @@ void SendspinConnection::handle_noise_handshake_text(std::string_view text) {
279279
assert(outcome.has_value() && "a completed handshake hands out its result");
280280
// Record the server's identity (public key) and the PSK category/psk_id that admitted
281281
// the connection, resolved by the handshake.
282-
this->set_noise_handshake_result(outcome->server_id.view(), outcome->psk_category,
283-
outcome->psk_id.view());
282+
this->set_noise_handshake_result(outcome->server_id, outcome->psk_category,
283+
outcome->psk_id);
284284
// pairing.md "Pairing index": a fresh handshake starts a fresh count for the
285285
// pairing_index / CPace-sid counter.
286286
this->reset_pairing_index();
@@ -333,7 +333,7 @@ bool SendspinConnection::handle_noise_rehandshake(std::span<uint8_t> msg1_bytes)
333333
SS_LOGE(TAG, "handle_noise_rehandshake: no handshake hash available");
334334
return false;
335335
}
336-
auto result = run_rehandshake_msg1(msg1_bytes, this->server_id_.view(), *this->noise_identity_,
336+
auto result = run_rehandshake_msg1(msg1_bytes, this->server_id_, *this->noise_identity_,
337337
*this->noise_record_store_, this->noise_suite_name_,
338338
prior_h.value(), *this->json_arena_);
339339
if (!result.has_value()) {

‎src/connection.h‎

Lines changed: 18 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -642,12 +642,12 @@ class SendspinConnection : public std::enable_shared_from_this<SendspinConnectio
642642
void wake_protocol_task() const;
643643

644644
// ========================================
645-
// Configuration setters (called by hub after receiving server/hello message)
645+
// Handshake state (protocol task unless noted)
646646
// ========================================
647647

648648
/// @brief Sets the client hello sent flag
649649
/// @param sent True if client hello message has been sent.
650-
/// @note Called by hub to track handshake state.
650+
/// @note Protocol task only: the nursery scan, once it sends client/hello.
651651
void set_client_hello_sent(bool sent) {
652652
this->client_hello_sent_ = sent;
653653
}
@@ -668,25 +668,25 @@ class SendspinConnection : public std::enable_shared_from_this<SendspinConnectio
668668
return this->client_hello_sent_;
669669
}
670670

671-
/// @brief Marks that the WebSocket upgrade completed
671+
/// @brief Marks that the WebSocket upgrade completed. Transport thread.
672672
/// @note Distinct from is_connected(): on ESP the socket is accepted before any WebSocket
673673
/// handshake, so this flag signals that the peer spoke WebSocket.
674674
void mark_ws_upgraded() {
675675
this->ws_upgraded_.store(true, std::memory_order_release);
676676
}
677677

678-
/// @brief Returns whether the WebSocket upgrade completed.
678+
/// @brief Returns whether the WebSocket upgrade completed. Any thread.
679679
bool is_ws_upgraded() const {
680680
return this->ws_upgraded_.load(std::memory_order_acquire);
681681
}
682682

683683
/// @brief Sets the server_id and PSK metadata from the Noise handshake result.
684684
/// Called at COMPLETE in connection.cpp.
685-
void set_noise_handshake_result(std::string_view server_id, PskCategory psk_category,
686-
std::string_view psk_id) {
687-
this->server_id_.assign(server_id);
685+
void set_noise_handshake_result(const IdText& server_id, PskCategory psk_category,
686+
const IdText& psk_id) {
687+
this->server_id_ = server_id;
688688
this->psk_category_ = psk_category;
689-
this->psk_id_.assign(psk_id);
689+
this->psk_id_ = psk_id;
690690
}
691691

692692
/// @brief Returns whether server/hello has arrived on this connection.
@@ -696,7 +696,7 @@ class SendspinConnection : public std::enable_shared_from_this<SendspinConnectio
696696

697697
/// @brief Sets the server hello received flag
698698
/// @param received True if server hello message has been received.
699-
/// @note Called by hub when SERVER_HELLO is processed.
699+
/// @note Protocol task only: the server/hello dispatch.
700700
void set_server_hello_received(bool received) {
701701
this->server_hello_received_ = received;
702702
}
@@ -777,7 +777,7 @@ class SendspinConnection : public std::enable_shared_from_this<SendspinConnectio
777777
void notify_transport_closed();
778778

779779
// ========================================
780-
// Initialization setters (called by hub before start)
780+
// Initialization setters (ConnectionManager, before the protocol task can reach the connection)
781781
// ========================================
782782

783783
/// @brief Sets the memory location preference for the fallback buffer the transport
@@ -1010,12 +1010,6 @@ class SendspinConnection : public std::enable_shared_from_this<SendspinConnectio
10101010
MessageTracer message_tracer_;
10111011
#endif
10121012

1013-
/// Server identity: server_id from the Noise handshake result (or re-handshake; unchanged
1014-
/// across a re-handshake since it is the same server), name from server/hello. Protocol task
1015-
/// only; ConnectionManager publishes a copy to other threads at admission.
1016-
IdText server_id_{};
1017-
ServerName server_name_{};
1018-
10191013
/// The pairing record staged by the attempt in flight, committed by the
10201014
/// server/pair-finalize handler (nullopt = nothing to store). Protocol task only.
10211015
std::optional<SendspinPairingRecord> pending_pairing_record_{};
@@ -1095,6 +1089,12 @@ class SendspinConnection : public std::enable_shared_from_this<SendspinConnectio
10951089
/// re-handshake. Protocol task only.
10961090
IdText psk_id_{};
10971091

1092+
/// Server identity: server_id from the Noise handshake result (or re-handshake; unchanged
1093+
/// across a re-handshake since it is the same server), name from server/hello. Protocol task
1094+
/// only; ConnectionManager publishes a copy to other threads at admission.
1095+
IdText server_id_{};
1096+
ServerName server_name_{};
1097+
10981098
// Struct fields
10991099

11001100
/// Active roles declared by server/activate (sticky: preserved across activates that omit
@@ -1187,7 +1187,8 @@ class SendspinConnection : public std::enable_shared_from_this<SendspinConnectio
11871187

11881188
/// true once the transport delivered the connected event (WebSocket upgrade completed).
11891189
/// Written from the transport connected callback (transport thread), read by the manager on
1190-
/// the protocol task, hence atomic. See mark_ws_upgraded().
1190+
/// the protocol task and by the host client's close_transport_now() on the transport thread,
1191+
/// hence atomic. See mark_ws_upgraded().
11911192
std::atomic<bool> ws_upgraded_{false};
11921193

11931194
/// The kind of the message in fallback_buf_ (TEXT or BINARY: a continuation frame does not

‎src/connection_manager.cpp‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -652,13 +652,13 @@ void ConnectionManager::on_server_activate(SendspinConnection* conn,
652652
msg.active_roles.value_or(playback_capable ? conn->get_active_roles() : ActiveRoles{});
653653
const bool has_roles = !effective_roles.empty();
654654

655-
// Trust enforcement against the PSK category the Noise handshake resolved for this
655+
// The admissibility check against the PSK category the Noise handshake resolved for this
656656
// connection. Every connection has one: no server/activate can arrive before the
657657
// handshake completes.
658-
const bool trust_ok =
658+
const bool activation_admissible =
659659
admissible(conn->get_psk_category(), msg.activities, has_roles, unpaired_access);
660660

661-
if (!trust_ok) {
661+
if (!activation_admissible) {
662662
const SendspinGoodbyeReason reject_reason = inadmissible_reject_reason(
663663
conn->get_psk_category(), msg.activities, has_roles, unpaired_access);
664664
SS_LOGW(TAG, "server/activate inadmissible (psk_category=%d): closing with %s",
@@ -1277,9 +1277,9 @@ uint32_t ConnectionManager::scan_nursery(int64_t now_us) {
12771277
}
12781278

12791279
// Admission: every nursery entry that has proven itself (is_operational(): hello handshake
1280-
// complete and first server/activate applied and admissible; trust was already checked when
1281-
// that activate was processed). The activate handler admits at once when the hello completed
1282-
// first; this level-triggered pass covers the other order.
1280+
// complete and first server/activate applied, its admissibility checked when it was
1281+
// processed). The activate handler admits at once when the hello completed first; this
1282+
// level-triggered pass covers the other order.
12831283
for (auto it = this->nursery_.begin(); it != this->nursery_.end();) {
12841284
if (!it->conn->is_operational()) {
12851285
++it;

‎src/connection_manager.h‎

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -468,9 +468,9 @@ class ConnectionManager {
468468
// Protocol task: message handlers
469469
// ========================================
470470

471-
/// @brief Applies a server/activate: trust enforcement, pairing-method admissibility, role
472-
/// ownership and removals, and, for a nursery connection that is now operational, admission
473-
/// before this returns.
471+
/// @brief Applies a server/activate: the admissibility check, the pairing-method check,
472+
/// role ownership and removals, and, for a nursery connection that is now operational,
473+
/// admission before this returns.
474474
void on_server_activate(SendspinConnection* conn, const ServerActivateMessage& msg);
475475

476476
/// @brief Handles a pair/abort from the server (an unrecognized reason arrives as
@@ -605,12 +605,12 @@ class ConnectionManager {
605605
/// @param server_id The server_id of the last-played server; empty, or longer than a peer_id,
606606
/// clears it.
607607
void set_last_played_server_id(std::string_view server_id) {
608-
this->last_played_server_id_.assign(server_id);
608+
(void)this->last_played_server_id_.assign(server_id);
609609
}
610610

611611
/// @brief Returns the current last-played server_id, empty if unset. Protocol task.
612-
std::string_view last_played_server_id() const {
613-
return this->last_played_server_id_.view();
612+
const IdText& last_played_server_id() const {
613+
return this->last_played_server_id_;
614614
}
615615

616616
private:
@@ -723,7 +723,7 @@ class ConnectionManager {
723723

724724
/// @brief Decides whether an incoming connection should displace an admitted one.
725725
///
726-
/// Applies admission.h::should_admit_connection; trust enforcement runs earlier, on the
726+
/// Applies admission.h::should_admit_connection; the admissibility check runs earlier, on the
727727
/// activate.
728728
/// @param admitted The admitted connection the incoming one conflicts with, or nullptr.
729729
/// @param new_conn The newly proven candidate connection. Must not be null.
@@ -769,7 +769,7 @@ class ConnectionManager {
769769
/// Removing a record from the RecordStore does not by itself end a session that is already
770770
/// running on it: a connection caches its resolved psk_id and PSK category at Noise-handshake
771771
/// completion (see SendspinConnection::get_psk_category()) and never re-resolves them against
772-
/// the store. Without this sweep a revoked device would keep its LONG_TERM trust (and with
772+
/// the store. Without this sweep a revoked device would keep its LONG_TERM category (and with
773773
/// it playback) until it happened to disconnect, so revocation would not take effect until
774774
/// the peer's next connection.
775775
///

‎src/crypto/constants.cpp‎

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,6 @@
1414

1515
#include "constants.h"
1616

17-
#include "keys.h"
1817
#include "platform/crypto.h"
1918

2019
#include <cstdlib>
@@ -44,9 +43,4 @@ const std::array<uint8_t, NOISE_PSK_SIZE> SENTINEL_PSK = []() {
4443
return digest;
4544
}();
4645

47-
// SENTINEL_PSK_ID = base64url(SHA-256(PSK_ID_LABEL || SENTINEL_PSK))
48-
// Computed once at startup from SENTINEL_PSK.
49-
// NOLINTNEXTLINE(bugprone-throwing-static-initialization)
50-
const std::string SENTINEL_PSK_ID = psk_id_for(SENTINEL_PSK);
51-
5246
} // namespace sendspin

‎src/crypto/constants.h‎

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,6 @@
2525
#include <array>
2626
#include <cstddef>
2727
#include <cstdint>
28-
#include <string>
2928
#include <string_view>
3029

3130
namespace sendspin {
@@ -46,10 +45,9 @@ static constexpr std::string_view PSK_ID_LABEL{"sendspin-psk-id-v1"};
4645
/// Expected hex: 1b5e24dbc1aed95fc2a5a338a90c05df44bd10f5ec1f4cd66cbf86272767b9d3
4746
extern const std::array<uint8_t, NOISE_PSK_SIZE> SENTINEL_PSK;
4847

49-
/// @brief The psk_id for the Sentinel PSK: base64url(SHA-256(PSK_ID_LABEL || SENTINEL_PSK)).
50-
/// Expected value: "GFsV9tLaSQm9HcFWpKsgYQOr7wFTvNUtkmFwuVz3zoo"
51-
/// Computed once at startup by constants.cpp.
52-
extern const std::string SENTINEL_PSK_ID;
48+
/// @brief The psk_id for the Sentinel PSK: base64url(SHA-256(PSK_ID_LABEL || SENTINEL_PSK)), the
49+
/// value connection.md "Pre-Shared Key" publishes.
50+
static constexpr std::string_view SENTINEL_PSK_ID = "GFsV9tLaSQm9HcFWpKsgYQOr7wFTvNUtkmFwuVz3zoo";
5351

5452
// ============================================================================
5553
// Cipher suite name (passed to noise_protocol_name_to_id)
@@ -77,9 +75,17 @@ static constexpr size_t MAX_TRANSPORT_PLAINTEXT = 65535 - 16; // = 65519
7775
/// without paying for a buffer sized like transport-mode traffic. noise-c bounds-checks against
7876
/// this capacity and returns an error rather than overflowing it if a peer's payload does not fit
7977
/// (verified against noise_handshakestate_read_message()'s payload->max_size check), so a longer
80-
/// payload fails the handshake rather than corrupting memory.
78+
/// payload fails the handshake rather than corrupting memory. MAX_SERVER_INIT_BYTES bounds the
79+
/// handshake's other peer input.
8180
static constexpr size_t MAX_HANDSHAKE_MESSAGE_BYTES = 512;
8281

82+
/// @brief Largest server/init the handshake keeps for its prologue: about five times the minimal
83+
/// frame, a version and a PEER_ID_SIZE server_id in about 104 bytes (messaging.md "server/init").
84+
/// It bounds the prologue buffer each handshake holds; the cost is that a later revision's
85+
/// optional fields, which messaging.md "Forward compatibility" has the client ignore, must keep
86+
/// the frame under it. MAX_HANDSHAKE_MESSAGE_BYTES bounds the handshake's other peer input.
87+
static constexpr size_t MAX_SERVER_INIT_BYTES = 512;
88+
8389
/// @brief Per-connection reassembly buffer cap: 1 MiB.
8490
/// Artwork is never fragmented: roles/artwork/v1.md "Artwork (Binary)" caps a message at
8591
/// MAX_TRANSPORT_PLAINTEXT so it fits one Noise transport message. The message that can

0 commit comments

Comments
 (0)