diff --git a/docs/conventions.md b/docs/conventions.md index a9e448f8..915fd69c 100644 --- a/docs/conventions.md +++ b/docs/conventions.md @@ -80,7 +80,7 @@ checklists in `.claude/skills/` apply these standards to a diff. call back into the client. See "Re-entrant Teardown During Callback Dispatch" in `docs/internals.md` for the guard patterns in use. - A message handler on the protocol task does the connection work the message - calls for in place (an activation's trust check, admission and role + calls for in place (an activation's admissibility check, admission and role ownership, a pairing step, a `noise/handshake` re-handshake, the RAM commit of a pairing record), and hands role and consumer work on through Inbox slots, role item lists and buffers. It never calls a listener or a diff --git a/docs/internals.md b/docs/internals.md index 1b7661f1..1e47c2c6 100644 --- a/docs/internals.md +++ b/docs/internals.md @@ -277,7 +277,7 @@ Role-bound traffic reaches a role only from the admitted connection that owns it | Message | Action on the protocol task | |---------|------------------------------| | `server/hello` | Records server info and the codecs its source@v1 support object lists on the connection, and sets `server_hello_received_` | -| `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 | +| `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 | | `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 | | `server/state` | Writes the controller, metadata, and color `InboxSlot`s | | `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 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. 2. Once `server/hello` arrives, the nursery scan sends `client/hello` (messaging.md "Client -> Server: client/hello"). -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. +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. 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. 5. A losing newcomer is released with a goodbye; a displaced incumbent is dropped, and the roles no remaining connection owns are torn down. diff --git a/src/admission.h b/src/admission.h index 46e69d07..affb0af2 100644 --- a/src/admission.h +++ b/src/admission.h @@ -13,7 +13,7 @@ // limitations under the License. /// @file admission.h -/// @brief Pure functions for server/activate trust enforcement, multi-server admission +/// @brief Pure functions for the server/activate admissibility check, multi-server admission /// arbitration, and role ownership among admitted connections. /// /// Implements the allowed-activity-set table and the rejection order in messaging.md @@ -37,7 +37,7 @@ namespace sendspin { // ============================================================================ -// Trust enforcement (PSK category -> allowed activities) +// Admissibility (PSK category -> allowed activities) // ============================================================================ /// @brief Whether an activity set is allowed for the matched PSK category. diff --git a/src/client_dispatch.cpp b/src/client_dispatch.cpp index 2179d18e..d079dbb2 100644 --- a/src/client_dispatch.cpp +++ b/src/client_dispatch.cpp @@ -528,7 +528,7 @@ void SendspinClient::process_json_message(SendspinConnection& connection, const SS_LOGD(TAG, "server/activate received (playback=%d, pairing=%d)", activate_msg.activities.contains(SendspinActivity::PLAYBACK), activate_msg.activities.contains(SendspinActivity::PAIRING)); - // Applied before the next message is parsed: trust enforcement, role + // Applied before the next message is parsed: the admissibility check, role // ownership and, for a nursery connection that is now operational, admission // all land here, so the role traffic the server sends behind this activate // meets the gate this activation set. @@ -757,7 +757,7 @@ void SendspinClient::process_json_message(SendspinConnection& connection, const break; } case SendspinServerToClientMessageType::SERVER_UNPAIR: { - // server/unpair. Trust gating (LONG_TERM only) happens in handle_server_unpair. + // server/unpair. The LONG_TERM-only check happens in handle_server_unpair. parsed.release(); SS_LOGI(TAG, "server/unpair received (psk_id=%s)", conn->get_psk_id().c_str()); this->connection_manager_->on_server_unpair(conn); diff --git a/src/connection.cpp b/src/connection.cpp index 80ef97f5..dfe89fa7 100644 --- a/src/connection.cpp +++ b/src/connection.cpp @@ -279,8 +279,8 @@ void SendspinConnection::handle_noise_handshake_text(std::string_view text) { assert(outcome.has_value() && "a completed handshake hands out its result"); // Record the server's identity (public key) and the PSK category/psk_id that admitted // the connection, resolved by the handshake. - this->set_noise_handshake_result(outcome->server_id.view(), outcome->psk_category, - outcome->psk_id.view()); + this->set_noise_handshake_result(outcome->server_id, outcome->psk_category, + outcome->psk_id); // pairing.md "Pairing index": a fresh handshake starts a fresh count for the // pairing_index / CPace-sid counter. this->reset_pairing_index(); @@ -333,7 +333,7 @@ bool SendspinConnection::handle_noise_rehandshake(std::span msg1_bytes) SS_LOGE(TAG, "handle_noise_rehandshake: no handshake hash available"); return false; } - auto result = run_rehandshake_msg1(msg1_bytes, this->server_id_.view(), *this->noise_identity_, + auto result = run_rehandshake_msg1(msg1_bytes, this->server_id_, *this->noise_identity_, *this->noise_record_store_, this->noise_suite_name_, prior_h.value(), *this->json_arena_); if (!result.has_value()) { diff --git a/src/connection.h b/src/connection.h index 3a602c63..44fdde56 100644 --- a/src/connection.h +++ b/src/connection.h @@ -642,12 +642,12 @@ class SendspinConnection : public std::enable_shared_from_thisclient_hello_sent_ = sent; } @@ -668,25 +668,25 @@ class SendspinConnection : public std::enable_shared_from_thisclient_hello_sent_; } - /// @brief Marks that the WebSocket upgrade completed + /// @brief Marks that the WebSocket upgrade completed. Transport thread. /// @note Distinct from is_connected(): on ESP the socket is accepted before any WebSocket /// handshake, so this flag signals that the peer spoke WebSocket. void mark_ws_upgraded() { this->ws_upgraded_.store(true, std::memory_order_release); } - /// @brief Returns whether the WebSocket upgrade completed. + /// @brief Returns whether the WebSocket upgrade completed. Any thread. bool is_ws_upgraded() const { return this->ws_upgraded_.load(std::memory_order_acquire); } /// @brief Sets the server_id and PSK metadata from the Noise handshake result. /// Called at COMPLETE in connection.cpp. - void set_noise_handshake_result(std::string_view server_id, PskCategory psk_category, - std::string_view psk_id) { - this->server_id_.assign(server_id); + void set_noise_handshake_result(const IdText& server_id, PskCategory psk_category, + const IdText& psk_id) { + this->server_id_ = server_id; this->psk_category_ = psk_category; - this->psk_id_.assign(psk_id); + this->psk_id_ = psk_id; } /// @brief Returns whether server/hello has arrived on this connection. @@ -696,7 +696,7 @@ class SendspinConnection : public std::enable_shared_from_thisserver_hello_received_ = received; } @@ -777,7 +777,7 @@ class SendspinConnection : public std::enable_shared_from_this pending_pairing_record_{}; @@ -1095,6 +1089,12 @@ class SendspinConnection : public std::enable_shared_from_this ws_upgraded_{false}; /// The kind of the message in fallback_buf_ (TEXT or BINARY: a continuation frame does not diff --git a/src/connection_manager.cpp b/src/connection_manager.cpp index 7c22afe2..f844a897 100644 --- a/src/connection_manager.cpp +++ b/src/connection_manager.cpp @@ -652,13 +652,13 @@ void ConnectionManager::on_server_activate(SendspinConnection* conn, msg.active_roles.value_or(playback_capable ? conn->get_active_roles() : ActiveRoles{}); const bool has_roles = !effective_roles.empty(); - // Trust enforcement against the PSK category the Noise handshake resolved for this + // The admissibility check against the PSK category the Noise handshake resolved for this // connection. Every connection has one: no server/activate can arrive before the // handshake completes. - const bool trust_ok = + const bool activation_admissible = admissible(conn->get_psk_category(), msg.activities, has_roles, unpaired_access); - if (!trust_ok) { + if (!activation_admissible) { const SendspinGoodbyeReason reject_reason = inadmissible_reject_reason( conn->get_psk_category(), msg.activities, has_roles, unpaired_access); 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) { } // Admission: every nursery entry that has proven itself (is_operational(): hello handshake - // complete and first server/activate applied and admissible; trust was already checked when - // that activate was processed). The activate handler admits at once when the hello completed - // first; this level-triggered pass covers the other order. + // complete and first server/activate applied, its admissibility checked when it was + // processed). The activate handler admits at once when the hello completed first; this + // level-triggered pass covers the other order. for (auto it = this->nursery_.begin(); it != this->nursery_.end();) { if (!it->conn->is_operational()) { ++it; diff --git a/src/connection_manager.h b/src/connection_manager.h index 30175878..edb8f292 100644 --- a/src/connection_manager.h +++ b/src/connection_manager.h @@ -468,9 +468,9 @@ class ConnectionManager { // Protocol task: message handlers // ======================================== - /// @brief Applies a server/activate: trust enforcement, pairing-method admissibility, role - /// ownership and removals, and, for a nursery connection that is now operational, admission - /// before this returns. + /// @brief Applies a server/activate: the admissibility check, the pairing-method check, + /// role ownership and removals, and, for a nursery connection that is now operational, + /// admission before this returns. void on_server_activate(SendspinConnection* conn, const ServerActivateMessage& msg); /// @brief Handles a pair/abort from the server (an unrecognized reason arrives as @@ -605,12 +605,12 @@ class ConnectionManager { /// @param server_id The server_id of the last-played server; empty, or longer than a peer_id, /// clears it. void set_last_played_server_id(std::string_view server_id) { - this->last_played_server_id_.assign(server_id); + (void)this->last_played_server_id_.assign(server_id); } /// @brief Returns the current last-played server_id, empty if unset. Protocol task. - std::string_view last_played_server_id() const { - return this->last_played_server_id_.view(); + const IdText& last_played_server_id() const { + return this->last_played_server_id_; } private: @@ -723,7 +723,7 @@ class ConnectionManager { /// @brief Decides whether an incoming connection should displace an admitted one. /// - /// Applies admission.h::should_admit_connection; trust enforcement runs earlier, on the + /// Applies admission.h::should_admit_connection; the admissibility check runs earlier, on the /// activate. /// @param admitted The admitted connection the incoming one conflicts with, or nullptr. /// @param new_conn The newly proven candidate connection. Must not be null. @@ -769,7 +769,7 @@ class ConnectionManager { /// Removing a record from the RecordStore does not by itself end a session that is already /// running on it: a connection caches its resolved psk_id and PSK category at Noise-handshake /// completion (see SendspinConnection::get_psk_category()) and never re-resolves them against - /// the store. Without this sweep a revoked device would keep its LONG_TERM trust (and with + /// the store. Without this sweep a revoked device would keep its LONG_TERM category (and with /// it playback) until it happened to disconnect, so revocation would not take effect until /// the peer's next connection. /// diff --git a/src/crypto/constants.cpp b/src/crypto/constants.cpp index c0ad691b..01d76c9a 100644 --- a/src/crypto/constants.cpp +++ b/src/crypto/constants.cpp @@ -14,7 +14,6 @@ #include "constants.h" -#include "keys.h" #include "platform/crypto.h" #include @@ -44,9 +43,4 @@ const std::array SENTINEL_PSK = []() { return digest; }(); -// SENTINEL_PSK_ID = base64url(SHA-256(PSK_ID_LABEL || SENTINEL_PSK)) -// Computed once at startup from SENTINEL_PSK. -// NOLINTNEXTLINE(bugprone-throwing-static-initialization) -const std::string SENTINEL_PSK_ID = psk_id_for(SENTINEL_PSK); - } // namespace sendspin diff --git a/src/crypto/constants.h b/src/crypto/constants.h index 3c11c231..acd3a5c6 100644 --- a/src/crypto/constants.h +++ b/src/crypto/constants.h @@ -25,7 +25,6 @@ #include #include #include -#include #include namespace sendspin { @@ -46,10 +45,9 @@ static constexpr std::string_view PSK_ID_LABEL{"sendspin-psk-id-v1"}; /// Expected hex: 1b5e24dbc1aed95fc2a5a338a90c05df44bd10f5ec1f4cd66cbf86272767b9d3 extern const std::array SENTINEL_PSK; -/// @brief The psk_id for the Sentinel PSK: base64url(SHA-256(PSK_ID_LABEL || SENTINEL_PSK)). -/// Expected value: "GFsV9tLaSQm9HcFWpKsgYQOr7wFTvNUtkmFwuVz3zoo" -/// Computed once at startup by constants.cpp. -extern const std::string SENTINEL_PSK_ID; +/// @brief The psk_id for the Sentinel PSK: base64url(SHA-256(PSK_ID_LABEL || SENTINEL_PSK)), the +/// value connection.md "Pre-Shared Key" publishes. +static constexpr std::string_view SENTINEL_PSK_ID = "GFsV9tLaSQm9HcFWpKsgYQOr7wFTvNUtkmFwuVz3zoo"; // ============================================================================ // Cipher suite name (passed to noise_protocol_name_to_id) @@ -77,9 +75,17 @@ static constexpr size_t MAX_TRANSPORT_PLAINTEXT = 65535 - 16; // = 65519 /// without paying for a buffer sized like transport-mode traffic. noise-c bounds-checks against /// this capacity and returns an error rather than overflowing it if a peer's payload does not fit /// (verified against noise_handshakestate_read_message()'s payload->max_size check), so a longer -/// payload fails the handshake rather than corrupting memory. +/// payload fails the handshake rather than corrupting memory. MAX_SERVER_INIT_BYTES bounds the +/// handshake's other peer input. static constexpr size_t MAX_HANDSHAKE_MESSAGE_BYTES = 512; +/// @brief Largest server/init the handshake keeps for its prologue: about five times the minimal +/// frame, a version and a PEER_ID_SIZE server_id in about 104 bytes (messaging.md "server/init"). +/// It bounds the prologue buffer each handshake holds; the cost is that a later revision's +/// optional fields, which messaging.md "Forward compatibility" has the client ignore, must keep +/// the frame under it. MAX_HANDSHAKE_MESSAGE_BYTES bounds the handshake's other peer input. +static constexpr size_t MAX_SERVER_INIT_BYTES = 512; + /// @brief Per-connection reassembly buffer cap: 1 MiB. /// Artwork is never fragmented: roles/artwork/v1.md "Artwork (Binary)" caps a message at /// MAX_TRANSPORT_PLAINTEXT so it fits one Noise transport message. The message that can diff --git a/src/esp/server_connection.cpp b/src/esp/server_connection.cpp index 06247f37..ecec64eb 100644 --- a/src/esp/server_connection.cpp +++ b/src/esp/server_connection.cpp @@ -122,7 +122,8 @@ SendspinServerConnection::SendspinServerConnection(httpd_handle_t server, int so } void SendspinServerConnection::start() { - // Time filter is initialized by the hub when it sets up the connection. + // No action needed: the ws_server delivers the connection only once its WebSocket upgrade + // completes, so the transport is already established by then. } void SendspinServerConnection::disconnect(SendspinGoodbyeReason reason) { diff --git a/src/inline_text.h b/src/inline_text.h index a2f97835..94fc7145 100644 --- a/src/inline_text.h +++ b/src/inline_text.h @@ -60,7 +60,7 @@ class InlineText { /// @brief Holds `text`. /// @return false, leaving the text empty, when `text` is longer than N. - bool assign(std::string_view text) { + [[nodiscard]] bool assign(std::string_view text) { if (text.size() > N) { this->set(std::string_view{}); return false; diff --git a/src/noise_handshake.cpp b/src/noise_handshake.cpp index 37ac6314..56cee621 100644 --- a/src/noise_handshake.cpp +++ b/src/noise_handshake.cpp @@ -217,8 +217,7 @@ std::optional run_msg1_core(HandshakeKind kind, const Identity& if (resolved->category == PskCategory::LONG_TERM && resolved->counterparty_id != server_id) { SS_LOGW(TAG, "%s: PSK bound to server_id='%s', but connected to '%s'", log_prefix, - resolved->counterparty_id.has_value() ? resolved->counterparty_id->c_str() : "", - server_id.c_str()); + resolved->counterparty_id.c_str(), server_id.c_str()); return std::nullopt; } } else if (kind == HandshakeKind::INITIAL) { @@ -372,8 +371,9 @@ HandshakeFrameResult NoiseHandshake::on_text_frame( } if (awaiting_server_init) { version = root["payload"]["version"] | 0; - // Refused when longer than a peer_id, which handle_server_init() then rejects. - server_id.assign(root["payload"]["server_id"] | ""); + // Refused when longer than a peer_id, leaving it empty for handle_server_init() to + // reject. + (void)server_id.assign(root["payload"]["server_id"] | ""); } else { msg1_bytes = read_noise_handshake_data(root, to_cstr(HandshakeKind::INITIAL)); } @@ -475,31 +475,27 @@ bool NoiseHandshake::handle_msg1(std::span msg1_bytes, // ============================================================================ std::optional run_rehandshake_msg1( - std::span msg1_bytes, std::string_view server_id, const Identity& identity, + std::span msg1_bytes, const IdText& server_id, const Identity& identity, const RecordStore& record_store, const char* suite_name, const std::array& prior_h, SendspinArenaAllocator& arena) { - // The id the initial handshake recorded; run_msg1_core()'s decode check refuses an empty one. - IdText known_server_id; - known_server_id.assign(server_id); // Prologue for re-handshake = prior handshake hash h (32 bytes) const uint8_t* prologue = prior_h.data(); const size_t prologue_len = prior_h.size(); auto core = run_msg1_core(HandshakeKind::REHANDSHAKE, identity, record_store, suite_name, - known_server_id, prologue, prologue_len, msg1_bytes, arena); + server_id, prologue, prologue_len, msg1_bytes, arena); if (!core.has_value()) { return std::nullopt; } - SS_LOGI(TAG, "Re-handshake complete: server_id=%s psk_category=%d", known_server_id.c_str(), + SS_LOGI(TAG, "Re-handshake complete: server_id=%s psk_category=%d", server_id.c_str(), static_cast(core->psk_category)); // The caller wraps msg2 in its noise/handshake envelope and sends it encrypted. Returned as a // prvalue, which is built in the caller's optional; a named optional would be moved there, // since this function also returns nullopt. - return std::optional(std::in_place, std::move(core->session), - known_server_id, core->psk_id, core->psk_category, - core->msg2_bytes); + return std::optional(std::in_place, std::move(core->session), server_id, + core->psk_id, core->psk_category, core->msg2_bytes); } } // namespace sendspin diff --git a/src/noise_handshake.h b/src/noise_handshake.h index 6efa79b8..093d6e75 100644 --- a/src/noise_handshake.h +++ b/src/noise_handshake.h @@ -132,17 +132,10 @@ std::optional read_noise_handshake_data(JsonObjectConst envelope /// @return Populated NoiseHandshakeResult (session + msg2_bytes to send) on success, /// or nullopt on any failure (caller should close the WebSocket). std::optional run_rehandshake_msg1( - std::span msg1_bytes, std::string_view server_id, const Identity& identity, + std::span msg1_bytes, const IdText& server_id, const Identity& identity, const RecordStore& record_store, const char* suite_name, const std::array& prior_h, SendspinArenaAllocator& arena); -/// @brief Largest server/init the handshake keeps for its prologue: about five times the minimal -/// frame, a version and a PEER_ID_SIZE server_id in about 104 bytes (messaging.md "server/init"). -/// It bounds the prologue buffer each handshake holds; the cost is that a later revision's -/// optional fields, which messaging.md "Forward compatibility" has the client ignore, must keep -/// the frame under it. -static constexpr size_t MAX_SERVER_INIT_BYTES = 512; - // ============================================================================ // NoiseHandshake class (initial handshake state machine) // ============================================================================ diff --git a/src/platform/json_arena.h b/src/platform/json_arena.h index 44ea98fb..7192dd4d 100644 --- a/src/platform/json_arena.h +++ b/src/platform/json_arena.h @@ -28,6 +28,7 @@ #include #include #include +#include #include #include @@ -274,6 +275,20 @@ inline JsonDocument make_json_document(SendspinArenaAllocator& arena) { return JsonDocument(&arena); } +/// @brief Whether a T can point into a parsed document: a pointer, a std::string_view, or a +/// JsonVariant, JsonObject, JsonArray (or their Const forms) or JsonString, alone or in a +/// std::optional. ParsedJsonMessage::extract() refuses to return one, since the document is gone +/// by the time the caller reads it. +template +struct RefersIntoDocument + : std::bool_constant || std::is_same_v || + std::is_same_v || std::is_same_v || + std::is_same_v || std::is_same_v || + std::is_same_v || std::is_same_v || + std::is_same_v> {}; +template +struct RefersIntoDocument> : RefersIntoDocument> {}; + /** * @brief A parsed inbound JSON message, read once and released before anything acts on it * @@ -316,6 +331,9 @@ class ParsedJsonMessage { extractor(this->root()); this->release(); } else { + using Extracted = std::decay_t>; + static_assert(!RefersIntoDocument::value, + "extract() releases the document: return an owned value, not a view"); auto extracted = extractor(this->root()); this->release(); return extracted; diff --git a/src/protocol.cpp b/src/protocol.cpp index 1fc90441..6b0603db 100644 --- a/src/protocol.cpp +++ b/src/protocol.cpp @@ -349,7 +349,8 @@ bool process_server_hello_message(JsonObject root, ServerHelloMessage* hello_msg if (hello_msg == nullptr) { return true; } - hello_msg->name.assign(read_friendly_name(root["payload"]["name"], "server/hello name")); + // read_friendly_name() cuts it to the name's capacity. + (void)hello_msg->name.assign(read_friendly_name(root["payload"]["name"], "server/hello name")); // roles/source/v1.md "server/hello source@v1 support object": supported_codecs is a required // list of strings that must include flac and pcm, and a source ignores the codec identifiers diff --git a/src/record_store.cpp b/src/record_store.cpp index c6ad7c53..42a5486d 100644 --- a/src/record_store.cpp +++ b/src/record_store.cpp @@ -225,15 +225,17 @@ std::optional RecordStore::resolve_by_psk_id(std::string_view psk_i // Only the declared category's candidates are searched (connection.md "Pre-Shared Key"): the // same psk_id under another category is a lookup miss, which keeps a server from using, say, a // long-term PSK as though it were the Pairing PSK and inheriting that category's activities. + // Every id below is PEER_ID_SIZE characters (psk_id_for(), the record codec and the handshake + // that bound the record), so each assign() fits. switch (category) { case PskCategory::LONG_TERM: { const SendspinPairingRecord* rec = this->record_by_psk_id(psk_id); if (rec != nullptr) { ResolvedPsk r; - r.psk_id.assign(rec->psk_id); + (void)r.psk_id.assign(rec->psk_id); r.psk = rec->psk; r.category = PskCategory::LONG_TERM; - r.counterparty_id.emplace().assign(rec->server_id); + (void)r.counterparty_id.assign(rec->server_id); return r; } break; @@ -241,7 +243,7 @@ std::optional RecordStore::resolve_by_psk_id(std::string_view psk_i case PskCategory::PAIRING: { if (this->pairing_psk_.has_value() && this->pairing_psk_->psk_id == psk_id) { ResolvedPsk r; - r.psk_id.assign(this->pairing_psk_->psk_id); + (void)r.psk_id.assign(this->pairing_psk_->psk_id); r.psk = this->pairing_psk_->psk; r.category = PskCategory::PAIRING; return r; @@ -251,7 +253,7 @@ std::optional RecordStore::resolve_by_psk_id(std::string_view psk_i case PskCategory::SENTINEL: { if (psk_id == SENTINEL_PSK_ID) { ResolvedPsk r; - r.psk_id.assign(SENTINEL_PSK_ID); + (void)r.psk_id.assign(SENTINEL_PSK_ID); r.psk = SENTINEL_PSK; r.category = PskCategory::SENTINEL; return r; diff --git a/src/record_store.h b/src/record_store.h index 6aead7fc..0a6ffd95 100644 --- a/src/record_store.h +++ b/src/record_store.h @@ -76,13 +76,13 @@ inline std::optional psk_category_from_string(std::string_view code // Resolved PSK (handshake currency) // ============================================================================ -/// @brief A PSK selected during a handshake, with its trust metadata. +/// @brief A PSK selected during a handshake, with its category and the server it is bound to. struct ResolvedPsk { IdText psk_id; std::array psk{}; PskCategory category{PskCategory::SENTINEL}; /// Peer server_id; set for every long-term record, empty for the Sentinel and Pairing PSKs. - std::optional counterparty_id; + IdText counterparty_id{}; ResolvedPsk() = default; ResolvedPsk(const ResolvedPsk&) = default; diff --git a/tests/lifecycle_test_fixtures.h b/tests/lifecycle_test_fixtures.h index aab669b4..90706102 100644 --- a/tests/lifecycle_test_fixtures.h +++ b/tests/lifecycle_test_fixtures.h @@ -87,7 +87,7 @@ class TestNetworkProvider : public SendspinNetworkProvider { // Seeds the client's RecordStore with known LONG_TERM records (server-side pairing is not under // test here) so a fake server that knows the same psk_id/psk resolves to PskCategory::LONG_TERM, -// matching the trust category the admission tests need. Optionally also seeds the last-played +// matching the PSK category the admission tests need. Optionally also seeds the last-played // server_id that the rank-0 arbitration tiebreak keys on. // // save_blob is left at the base class's rejecting default: nothing here is meant to diff --git a/tests/record_test_helpers.h b/tests/record_test_helpers.h index 02207e5c..6aa1588c 100644 --- a/tests/record_test_helpers.h +++ b/tests/record_test_helpers.h @@ -35,6 +35,7 @@ #include #include #include +#include #include #include @@ -45,6 +46,13 @@ inline void PrintTo(const IdText& id, std::ostream* os) { *os << '"' << id.view() << '"'; } +/// An IdText holding `text`, which a test id must fit (at most PEER_ID_SIZE characters). +inline IdText id_text(std::string_view text) { + IdText id; + EXPECT_TRUE(id.assign(text)) << "a test id is longer than a peer_id: " << text; + return id; +} + /// Generate a random PSK of NOISE_PSK_SIZE bytes. inline std::array make_random_psk() { std::array psk{}; diff --git a/tests/test_admission.cpp b/tests/test_admission.cpp index 37161da8..18ca04e3 100644 --- a/tests/test_admission.cpp +++ b/tests/test_admission.cpp @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -// Unit tests for the admission/trust enforcement and arbitration functions: +// Unit tests for the admissibility check and the arbitration functions: // the allowed-activity-set table and rejection order in messaging.md "server/activate", and the // priority rules in connection.md "Multiple servers (server-initiated)". diff --git a/tests/test_client_lifecycle.cpp b/tests/test_client_lifecycle.cpp index 794451b6..a567c359 100644 --- a/tests/test_client_lifecycle.cpp +++ b/tests/test_client_lifecycle.cpp @@ -1926,7 +1926,7 @@ TEST(ClientLifecycle, TheConnectedFlagRisesOnlyAtTheEndOfTheTick) { ConnectionManager& manager = *client.connection_manager_; manager.liveness_timeout_us_ = 0; auto conn = std::make_shared(); - conn->set_noise_handshake_result("server", PskCategory::LONG_TERM, "psk"); + conn->set_noise_handshake_result(id_text("server"), PskCategory::LONG_TERM, id_text("psk")); conn->set_client_hello_sent(true); conn->set_server_hello_received(true); conn->apply_server_activate({SendspinActivity::PLAYBACK}, ActiveRoles{}, diff --git a/tests/test_crypto.cpp b/tests/test_crypto.cpp index d64ca335..6c43aa6a 100644 --- a/tests/test_crypto.cpp +++ b/tests/test_crypto.cpp @@ -194,8 +194,8 @@ TEST(CryptoConstants, SentinelPskMatchesSpecHex) { } TEST(CryptoConstants, SentinelPskIdMatchesSpecConstant) { - // psk_id_for(SENTINEL_PSK) must equal the spec's published identifier. - EXPECT_EQ(SENTINEL_PSK_ID, "GFsV9tLaSQm9HcFWpKsgYQOr7wFTvNUtkmFwuVz3zoo"); + // The published identifier must be the one psk_id_for() derives from the Sentinel PSK. + EXPECT_EQ(psk_id_for(SENTINEL_PSK), SENTINEL_PSK_ID); } TEST(CryptoConstants, PskIdLabelIsLiteralUtf8NoNul) { diff --git a/tests/test_encrypted_lifecycle.cpp b/tests/test_encrypted_lifecycle.cpp index 425c06ea..d9b44eba 100644 --- a/tests/test_encrypted_lifecycle.cpp +++ b/tests/test_encrypted_lifecycle.cpp @@ -427,7 +427,7 @@ TEST(EncryptedLifecycle, AeadFailureOnOutboundConnectionDoesNotCrash) { } // Negative path: a post-re-handshake server/activate that the new PSK category cannot admit must -// still go through the existing inadmissible-activate drop path (trust enforcement applies +// still go through the existing inadmissible-activate drop path (the admissibility check applies // identically whether the activate follows the initial handshake or a re-handshake), closing with // the correct client/goodbye reason. TEST(EncryptedLifecycle, PostRehandshakeInadmissibleActivateDrops) { @@ -2524,8 +2524,8 @@ TEST(EncryptedLifecycle, AReplyBuiltInsideAHandlerHasTheArenaToItself) { auto conn = std::make_shared(); // A paired server, whose playback activations are admissible (the stand-in's default Sentinel // category would have the activate dropped instead). - conn->set_noise_handshake_result(test_peer_id("arena-release-server"), PskCategory::LONG_TERM, - "arena-release-psk-id"); + conn->set_noise_handshake_result(id_text(test_peer_id("arena-release-server")), + PskCategory::LONG_TERM, id_text("arena-release-psk-id")); conn->set_client_hello_sent(true); conn->set_server_hello_received(true); conn->last_receive_time_us_.store(static_cast(platform_time_us()), @@ -2601,8 +2601,8 @@ TEST(EncryptedLifecycle, TheFirstClientStateLeavesOnlyOnceTheConnectionIsAdmitte if (row.pairing_method.has_value()) { const auto& pairing_psk = bundle.client_ref().record_store_->pairing_psk(); ASSERT_TRUE(pairing_psk.has_value()); - conn->set_noise_handshake_result(test_peer_id("state-after-admission-server"), - PskCategory::PAIRING, pairing_psk->psk_id); + conn->set_noise_handshake_result(id_text(test_peer_id("state-after-admission-server")), + PskCategory::PAIRING, id_text(pairing_psk->psk_id)); // The count the activate-event drain takes for every pairing server/activate. conn->bump_pairing_index(); } @@ -2844,8 +2844,8 @@ TEST(EncryptedLifecycle, SeveralRecordChangesInOneTickWriteEachTouchedKeyOnce) { const size_t writes_before = record_writes(persistence); DispatchTestConnection conn; - conn.set_noise_handshake_result(unpairing_record.server_id, PskCategory::LONG_TERM, - unpairing_record.psk_id); + conn.set_noise_handshake_result(id_text(unpairing_record.server_id), PskCategory::LONG_TERM, + id_text(unpairing_record.psk_id)); { // What note_playback_activity() does when a long-term connection takes playback. EXPECT_TRUE(client.record_store_->note_record_played(played_record.psk_id)); @@ -2898,7 +2898,8 @@ TEST(EncryptedLifecycle, APlaybackThatMovesNothingWritesNothing) { ConnectionManager& manager = *client.connection_manager_; auto conn = std::make_shared(); - conn->set_noise_handshake_result(older.server_id, PskCategory::LONG_TERM, older.psk_id); + conn->set_noise_handshake_result(id_text(older.server_id), PskCategory::LONG_TERM, + id_text(older.psk_id)); conn->apply_server_activate({SendspinActivity::PLAYBACK}, std::nullopt, std::nullopt, std::nullopt); @@ -2958,7 +2959,8 @@ TEST(EncryptedLifecycle, AnEvictionBeforeTheFlushSparesTheRecordJustPlayed) { ConnectionManager& manager = *client.connection_manager_; auto conn = std::make_shared(); - conn->set_noise_handshake_result(played.server_id, PskCategory::LONG_TERM, played.psk_id); + conn->set_noise_handshake_result(id_text(played.server_id), PskCategory::LONG_TERM, + id_text(played.psk_id)); conn->apply_server_activate({SendspinActivity::PLAYBACK}, std::nullopt, std::nullopt, std::nullopt); { @@ -3080,8 +3082,8 @@ TEST(EncryptedLifecycle, APlayingGroupDoesNotMakeAnIdleServerTheLastPlaybackOne) ConnectionManager& manager = *client.connection_manager_; auto conn = std::make_shared(); - conn->set_noise_handshake_result(server_identity.peer_id(), PskCategory::SENTINEL, - /*psk_id=*/""); + conn->set_noise_handshake_result(id_text(server_identity.peer_id()), PskCategory::SENTINEL, + /*psk_id=*/IdText{}); conn->apply_server_activate({}, std::nullopt, std::nullopt, std::nullopt); { manager.install_admitted(conn, conn->get_active_role_mask()); @@ -3160,7 +3162,8 @@ TEST(EncryptedLifecycle, OnlyPlaybackOnTheAdmittedConnectionMovesRecency) { ConnectionManager& manager = *client.connection_manager_; auto conn = std::make_shared(); - conn->set_noise_handshake_result(older.server_id, PskCategory::LONG_TERM, older.psk_id); + conn->set_noise_handshake_result(id_text(older.server_id), PskCategory::LONG_TERM, + id_text(older.psk_id)); conn->apply_server_activate(row.activities, std::nullopt, std::nullopt, std::nullopt); { if (row.admitted) { @@ -3275,8 +3278,8 @@ TEST(EncryptedLifecycle, ACoalescedFlushRejectedByTheProviderKeepsTheRamState) { reject_record_saves(persistence); DispatchTestConnection conn; - conn.set_noise_handshake_result(unpairing_record.server_id, PskCategory::LONG_TERM, - unpairing_record.psk_id); + conn.set_noise_handshake_result(id_text(unpairing_record.server_id), PskCategory::LONG_TERM, + id_text(unpairing_record.psk_id)); { // What note_playback_activity() does when a long-term connection takes playback. EXPECT_TRUE(client.record_store_->note_record_played(played_record.psk_id)); @@ -3320,7 +3323,8 @@ TEST(EncryptedLifecycle, UnpairRevokesTheRecordBeforeTheWriteIsFlushed) { ASSERT_TRUE(client.record_store_->store_record_superseding(record, {})); DispatchTestConnection conn; - conn.set_noise_handshake_result(record.server_id, PskCategory::LONG_TERM, record.psk_id); + conn.set_noise_handshake_result(id_text(record.server_id), PskCategory::LONG_TERM, + id_text(record.psk_id)); manager.handle_server_unpair(&conn); // The re-handshake's lookup, on the protocol task (this thread) right behind the handler. const std::optional resolved = diff --git a/tests/test_noise_rehandshake.cpp b/tests/test_noise_rehandshake.cpp index f5886164..1e602930 100644 --- a/tests/test_noise_rehandshake.cpp +++ b/tests/test_noise_rehandshake.cpp @@ -34,6 +34,7 @@ #include "platform/base64.h" #include "platform/crypto.h" #include "record_store.h" +#include "record_test_helpers.h" #include "sendspin/config.h" #include "test_util.h" @@ -235,8 +236,9 @@ static std::optional run_rehandshake( } std::vector msg1_bytes = msg1_bytes_of(msg1_json); - auto result = run_rehandshake_msg1(msg1_bytes, init.server_id.peer_id(), init.client_id, rs, - suite_name.c_str(), prior_h, TestArena()); + auto result = + run_rehandshake_msg1(msg1_bytes, id_text(init.server_id.peer_id()), init.client_id, rs, + suite_name.c_str(), prior_h, TestArena()); if (!result.has_value()) { ADD_FAILURE() << "run_rehandshake_msg1 returned nullopt"; return std::nullopt; @@ -388,8 +390,9 @@ TEST(NoiseRehandshake, UnknownPskIdAborts) { // run_rehandshake_msg1 must return nullopt (unknown psk_id). std::vector msg1_bytes = msg1_bytes_of(msg1_json); - auto result = run_rehandshake_msg1(msg1_bytes, init.server_id.peer_id(), init.client_id, - empty_rs, suite.c_str(), prior_h, TestArena()); + auto result = + run_rehandshake_msg1(msg1_bytes, id_text(init.server_id.peer_id()), init.client_id, + empty_rs, suite.c_str(), prior_h, TestArena()); EXPECT_FALSE(result.has_value()) << "run_rehandshake_msg1 should fail with an unknown psk_id"; } diff --git a/tests/test_pairing_state_machine.cpp b/tests/test_pairing_state_machine.cpp index c03476d8..a8adc3de 100644 --- a/tests/test_pairing_state_machine.cpp +++ b/tests/test_pairing_state_machine.cpp @@ -526,7 +526,8 @@ class PairingStateMachineTest : public ::testing::Test { const std::string& server_id, SendspinPairMethod method, SendspinPairingCodeFormat format = SendspinPairingCodeFormat::DIGITS) { auto conn = std::make_shared(); - conn->set_noise_handshake_result(server_id, PskCategory::SENTINEL, /*psk_id=*/""); + conn->set_noise_handshake_result(id_text(server_id), PskCategory::SENTINEL, + /*psk_id=*/IdText{}); conn->apply_server_activate({SendspinActivity::PAIRING}, std::nullopt, method, method == SendspinPairMethod::DYNAMIC_PAIRING_CODE ? std::optional(format) @@ -545,7 +546,8 @@ class PairingStateMachineTest : public ::testing::Test { /// exercised end to end (not bypassed through the handle_enter_pairing() seam). FakeConnection* inject_provisional_current_connection(const std::string& server_id) { auto conn = std::make_shared(); - conn->set_noise_handshake_result(server_id, PskCategory::SENTINEL, /*psk_id=*/""); + conn->set_noise_handshake_result(id_text(server_id), PskCategory::SENTINEL, + /*psk_id=*/IdText{}); FakeConnection* raw = conn.get(); this->injected_conn_ = conn; this->admit(conn); @@ -607,8 +609,8 @@ class PairingStateMachineTest : public ::testing::Test { } /// Apply a server/activate on the injected current connection through the real activation - /// path, ConnectionManager::on_server_activate() (trust check, apply_server_activate, then - /// either the already-admitted branch's leftover-activate handling or + /// path, ConnectionManager::on_server_activate() (admissibility check, apply_server_activate, + /// then either the already-admitted branch's leftover-activate handling or /// on_handshake_complete()): the call process_json_message() makes on the protocol task. void post_activate(ActivitySet activities, std::optional active_roles, @@ -2909,8 +2911,8 @@ TEST_F(PairingStateMachineTest, FinalizedPairingIsNotEvictedByRankZeroLastPlayba // A rank-0 peer (no activities) whose server_id is the last playback server: exactly the // inputs admission rule 5 keys on. auto newcomer = std::make_shared(); - newcomer->set_noise_handshake_result("old-playback-server", PskCategory::SENTINEL, - /*psk_id=*/""); + newcomer->set_noise_handshake_result(id_text("old-playback-server"), PskCategory::SENTINEL, + /*psk_id=*/IdText{}); newcomer->apply_server_activate({}, std::nullopt, std::nullopt, std::nullopt); EXPECT_FALSE(this->would_switch_to(current, newcomer.get(), "old-playback-server")) @@ -2919,7 +2921,8 @@ TEST_F(PairingStateMachineTest, FinalizedPairingIsNotEvictedByRankZeroLastPlayba // The shield really is suppressed though: a rank-2 playback peer wins. auto playback = std::make_shared(); - playback->set_noise_handshake_result("playback-server", PskCategory::SENTINEL, /*psk_id=*/""); + playback->set_noise_handshake_result(id_text("playback-server"), PskCategory::SENTINEL, + /*psk_id=*/IdText{}); playback->apply_server_activate({SendspinActivity::PLAYBACK}, std::nullopt, std::nullopt, std::nullopt); EXPECT_TRUE(this->would_switch_to(current, playback.get(), "old-playback-server")) diff --git a/tests/test_record_store.cpp b/tests/test_record_store.cpp index 5f8c0a7a..0f749359 100644 --- a/tests/test_record_store.cpp +++ b/tests/test_record_store.cpp @@ -338,8 +338,7 @@ TEST(RecordStore, StoreRecordReplacesTheRecordHoldingTheSamePskId) { auto resolved = store.resolve_by_psk_id(psk_id, PskCategory::LONG_TERM); ASSERT_TRUE(resolved.has_value()); - ASSERT_TRUE(resolved->counterparty_id.has_value()); - EXPECT_EQ(resolved->counterparty_id.value(), test_peer_id("server-B")) + EXPECT_EQ(resolved->counterparty_id, test_peer_id("server-B")) << "the psk_id must authenticate the server that paired with it last, not the one it " "replaced"; @@ -864,8 +863,7 @@ TEST(RecordStore, CapacitySupersedeAtCapacityEvictsNothing) { << "the superseded PSK must stop authenticating"; auto resolved = store.resolve_by_psk_id(outcome1.record.psk_id, PskCategory::LONG_TERM); ASSERT_TRUE(resolved.has_value()); - ASSERT_TRUE(resolved->counterparty_id.has_value()); - EXPECT_EQ(resolved->counterparty_id.value(), existing_server); + EXPECT_EQ(resolved->counterparty_id, existing_server); for (const std::string& psk_id : other_psk_ids) { EXPECT_TRUE(store.resolve_by_psk_id(psk_id, PskCategory::LONG_TERM).has_value()) << "no other server's record may be evicted by a supersede"; @@ -948,15 +946,14 @@ TEST(RecordStore, ResolveByPskIdReturnsTheCategorysPskAndCounterparty) { std::string psk_id; PskCategory category; std::array psk; - std::optional counterparty; + std::string counterparty; // Empty for a PSK bound to no server }; const Row rows[] = { {"long-term-record", rec.psk_id, PskCategory::LONG_TERM, rec.psk, rec.server_id}, - {"pairing-psk", pairing.psk_id, PskCategory::PAIRING, pairing.psk, std::nullopt}, + {"pairing-psk", pairing.psk_id, PskCategory::PAIRING, pairing.psk, ""}, // The Sentinel PSK is a constant, so it resolves on a store that has never been // provisioned as well as on this one. - {"sentinel-psk", std::string(SENTINEL_PSK_ID), PskCategory::SENTINEL, SENTINEL_PSK, - std::nullopt}, + {"sentinel-psk", std::string(SENTINEL_PSK_ID), PskCategory::SENTINEL, SENTINEL_PSK, ""}, }; for (const Row& row : rows) { @@ -993,7 +990,7 @@ TEST(RecordStore, DeclaredCategoryPicksBetweenTwoPsksWithTheSamePskId) { auto as_pairing = store.resolve_by_psk_id(rec.psk_id, PskCategory::PAIRING); ASSERT_TRUE(as_pairing.has_value()); EXPECT_EQ(as_pairing->category, PskCategory::PAIRING); - EXPECT_FALSE(as_pairing->counterparty_id.has_value()); + EXPECT_TRUE(as_pairing->counterparty_id.empty()); } // A psk_id the client holds only under another category is a lookup miss, not a match @@ -1220,7 +1217,7 @@ TEST(RecordStore, SupersedeIsDurableWhenTheProviderAcceptsTheFlush) { } // The refused delete is exactly the durability hole the bool return exists to surface: the -// record the store kept comes back on the next start, and resolves as LONG_TERM trust again. +// record the store kept comes back on the next start, and resolves as LONG_TERM again. TEST(RecordStore, RefusedDeleteLetsTheRevokedRecordReturnAfterAReboot) { RejectingDeleteProvider provider; diff --git a/tests/test_source_role.cpp b/tests/test_source_role.cpp index 71da176c..6fcfcad9 100644 --- a/tests/test_source_role.cpp +++ b/tests/test_source_role.cpp @@ -890,7 +890,8 @@ class SourceStandIn { auto conn = std::make_shared(); conn->set_json_arena(*this->client->json_arena_); conn->set_noise_session(std::move(loopback->responder_session)); - conn->set_noise_handshake_result("stand-in-server", PskCategory::LONG_TERM, "stand-in"); + conn->set_noise_handshake_result(id_text("stand-in-server"), PskCategory::LONG_TERM, + id_text("stand-in")); conn->set_client_hello_sent(true); conn->set_server_hello_received(true); conn->apply_server_activate({SendspinActivity::PLAYBACK}, ActiveRoles{"source@v1"},