From 581f52a6397cde9ff30083750184b838013629e8 Mon Sep 17 00:00:00 2001 From: Kevin Ahrendt Date: Tue, 3 Nov 2026 06:39:57 -0500 Subject: [PATCH 1/5] Hold the Noise transport session by value NoiseHandshakeResult carries its NoiseSession by value and NoiseTransport keeps it in a std::optional, which a re-handshake move-assigns, so a handshake no longer heap-allocates its session. is_active() reads the optional instead of a separate flag. Accept to admission: 6 -> 5 allocations under libc++, 8 -> 7 under libstdc++. --- src/noise_handshake.cpp | 8 +++----- src/noise_handshake.h | 3 +-- src/noise_transport.cpp | 5 ++--- src/noise_transport.h | 14 +++++--------- tests/loopback_connection.h | 10 ++++------ tests/test_allocations.cpp | 4 ++-- tests/test_noise_rehandshake.cpp | 11 +++++------ tests/test_noise_transport.cpp | 3 +-- 8 files changed, 23 insertions(+), 35 deletions(-) diff --git a/src/noise_handshake.cpp b/src/noise_handshake.cpp index 1a7bef33..bd91190e 100644 --- a/src/noise_handshake.cpp +++ b/src/noise_handshake.cpp @@ -263,11 +263,9 @@ std::optional run_msg1_core(HandshakeKind kind, const Identity& /// @param core Completed core result (session and resolved_psk are moved out of it). /// @param server_id Server peer_id to record on the result. NoiseHandshakeResult make_handshake_result(Msg1CoreResult&& core, const IdText& server_id) { - NoiseHandshakeResult result; - result.session = std::make_unique(std::move(core.session)); - result.server_id = server_id; - result.resolved_psk = std::move(core.resolved_psk); - return result; + return NoiseHandshakeResult{.session = std::move(core.session), + .server_id = server_id, + .resolved_psk = std::move(core.resolved_psk)}; } } // namespace diff --git a/src/noise_handshake.h b/src/noise_handshake.h index 000ad309..52d25759 100644 --- a/src/noise_handshake.h +++ b/src/noise_handshake.h @@ -48,7 +48,6 @@ #include #include #include -#include #include #include #include @@ -62,7 +61,7 @@ class SendspinArenaAllocator; /// @brief Outcome of a successful Noise handshake (initial or re-handshake). struct NoiseHandshakeResult { /// The cipher session ready for transport-mode encrypt/decrypt. - std::unique_ptr session; + NoiseSession session; /// Server's public key peer_id (43-char base64url). IdText server_id; /// The PSK record that admitted the connection. diff --git a/src/noise_transport.cpp b/src/noise_transport.cpp index 024af955..073650e7 100644 --- a/src/noise_transport.cpp +++ b/src/noise_transport.cpp @@ -30,9 +30,8 @@ static const char* const TAG = "sendspin.noise_transport"; // Session lifecycle // ============================================================================ -void NoiseTransport::activate(std::unique_ptr session) { +void NoiseTransport::activate(NoiseSession session) { this->session_ = std::move(session); - this->active_ = true; } std::optional> NoiseTransport::handshake_hash() const { @@ -147,7 +146,7 @@ SsErr NoiseTransport::send_binary_lent(OutboundRing& ring, void* item, size_t me return err; } -SsErr NoiseTransport::send_msg2_and_swap(size_t len, std::unique_ptr next_session) { +SsErr NoiseTransport::send_msg2_and_swap(size_t len, NoiseSession next_session) { // msg2 goes out under the OLD session, then the session swaps. Every send runs on the // protocol task, as this does, so no encrypt can fall between the two. SsErr err = this->send_staged_json(len); diff --git a/src/noise_transport.h b/src/noise_transport.h index a425d22d..56ad43b7 100644 --- a/src/noise_transport.h +++ b/src/noise_transport.h @@ -37,7 +37,6 @@ #include #include #include -#include #include #include @@ -95,7 +94,7 @@ class NoiseTransport { /// @brief Installs the cipher session produced by the initial Noise handshake and marks /// the transport active. Called on the protocol task at handshake COMPLETE. - void activate(std::unique_ptr session); + void activate(NoiseSession session); /// @brief Returns the current session's 32-byte Noise handshake hash, or nullopt if no /// session is active. Protocol task only. @@ -105,7 +104,7 @@ class NoiseTransport { /// swaps). This is the check send paths use to decide encrypted-vs-cleartext. Protocol task /// only. bool is_active() const { - return this->active_; + return this->session_.has_value(); } /// @brief Whether a send failed once its first frame was encrypted. Each encrypt spends a send @@ -159,7 +158,7 @@ class NoiseTransport { /// text) under the OLD session, then swap to the new session. Protocol task only, like every /// other send, so no encrypt falls between the msg2 send and the swap. /// @return SsErr::OK on success (session swapped); on error the old session is kept. - SsErr send_msg2_and_swap(size_t len, std::unique_ptr next_session); + SsErr send_msg2_and_swap(size_t len, NoiseSession next_session); // ======================================== // Inbound (decrypt + reassemble); protocol task only @@ -260,12 +259,12 @@ class NoiseTransport { /// reasm_buf_. PlatformBuffer send_buf_; - // Pointer fields /// Noise cipher session (set at handshake COMPLETE, replaced on re-handshake swap). /// Protocol task only. - std::unique_ptr session_; + std::optional session_; #ifdef SENDSPIN_ENABLE_MESSAGE_TRACE + // Pointer fields /// From set_message_tracer(); nullptr for none. Written once at setup, then protocol task /// only. const MessageTracer* message_tracer_{nullptr}; @@ -280,9 +279,6 @@ class NoiseTransport { /// Memory placement for reasm_buf_ and send_buf_. MemoryLocation buffer_location_{MemoryLocation::PREFER_EXTERNAL}; - /// True once a transport session exists. See is_active(). Protocol task only. - bool active_{false}; - /// See is_send_desynced(). Protocol task only. bool send_desynced_{false}; diff --git a/tests/loopback_connection.h b/tests/loopback_connection.h index eb7b63d7..780d98d0 100644 --- a/tests/loopback_connection.h +++ b/tests/loopback_connection.h @@ -46,7 +46,6 @@ extern "C" { #include #include #include -#include #include #include #include @@ -141,8 +140,8 @@ class TestConnection : public SendspinConnection { std::function on_binary; /// Install a noise session directly (bypasses handshake, for transport-only tests). - void set_noise_session(std::unique_ptr session) { - this->noise_transport_.activate(std::move(session)); + void set_noise_session(std::optional&& session) { + this->noise_transport_.activate(std::move(session.value())); this->noise_handshake_complete_ = true; } @@ -214,10 +213,10 @@ inline std::optional> extract_noise_bytes(const std::string /// The "server" side is noise-c as initiator. /// The "client" side is our NoiseHandshake/NoiseSession as responder. /// -/// Returns the initiator cipher pair after split (for transport tests), or nullptr on failure. +/// Returns the initiator cipher pair after split (for transport tests), or nullopt on failure. struct LoopbackResult { CipherPair initiator; - std::unique_ptr responder_session; + std::optional responder_session; LoopbackResult() = default; LoopbackResult(LoopbackResult&&) = default; @@ -357,7 +356,6 @@ inline std::optional run_loopback_handshake(const std::string& s if (!outcome.has_value()) { return std::nullopt; } - EXPECT_TRUE(outcome->session != nullptr); EXPECT_FALSE(outcome->server_id.empty()); EXPECT_EQ(outcome->server_id, server_id.peer_id()); diff --git a/tests/test_allocations.cpp b/tests/test_allocations.cpp index aa98c61f..a1be1f58 100644 --- a/tests/test_allocations.cpp +++ b/tests/test_allocations.cpp @@ -430,9 +430,9 @@ constexpr int TIME_BURST_SIZE = 8; // libstdc++ (ESP-IDF's) keeps strings of up to 15 characters inline, libc++ up to 22: the fake // server's name, parsed and then published, allocates only under libstdc++. #ifdef _LIBCPP_VERSION -constexpr size_t ADMISSION_ALLOCATIONS = 6; +constexpr size_t ADMISSION_ALLOCATIONS = 5; #else -constexpr size_t ADMISSION_ALLOCATIONS = 8; +constexpr size_t ADMISSION_ALLOCATIONS = 7; #endif constexpr size_t CLIENT_STATE_ALLOCATIONS = 0; constexpr size_t TIME_BURST_ALLOCATIONS = 0; diff --git a/tests/test_noise_rehandshake.cpp b/tests/test_noise_rehandshake.cpp index c5f0a058..7b863b58 100644 --- a/tests/test_noise_rehandshake.cpp +++ b/tests/test_noise_rehandshake.cpp @@ -54,7 +54,6 @@ extern "C" { #include #include #include -#include #include #include #include @@ -74,7 +73,7 @@ using namespace sendspin; // NOLINT(google-build-using-namespace): test-local c /// Returns: initiator cipher pair, responder NoiseSession, and server_id (public key). struct InitialHandshakeResult { CipherPair initiator; - std::unique_ptr responder_session; + std::optional responder_session; std::array responder_h{}; // handshake hash from the responder side std::array psk{}; std::string psk_id; @@ -161,8 +160,8 @@ static std::optional run_initial_handshake(const std::st } auto outcome = nh.take_result(); - if (!outcome.has_value() || !outcome->session) { return std::nullopt; } - r.responder_h = outcome->session->handshake_hash(); + if (!outcome.has_value()) { return std::nullopt; } + r.responder_h = outcome->session.handshake_hash(); r.responder_session = std::move(outcome->session); return r; @@ -205,7 +204,7 @@ static std::vector msg1_bytes_of(const std::string& envelope) { /// @return New initiator cipher pair + new responder session on success, or nullopt. struct RehandshakeResult { CipherPair initiator; - std::unique_ptr responder_session; + std::optional responder_session; std::array new_h{}; // new handshake hash }; @@ -267,7 +266,7 @@ static std::optional run_rehandshake( return std::nullopt; } - rr.new_h = result->session->handshake_hash(); + rr.new_h = result->session.handshake_hash(); rr.responder_session = std::move(result->session); return rr; } diff --git a/tests/test_noise_transport.cpp b/tests/test_noise_transport.cpp index 96782aef..563d6be3 100644 --- a/tests/test_noise_transport.cpp +++ b/tests/test_noise_transport.cpp @@ -349,7 +349,6 @@ Msg1Outcome run_msg1_with_payload( EXPECT_TRUE(result.has_value()); if (result.has_value()) { outcome.category = result->resolved_psk.category; - EXPECT_NE(result->session, nullptr) << "a completed handshake must carry its session"; } // The peer holds the PSK it referenced, so it can only read message 2 if the client bound the @@ -1266,7 +1265,7 @@ TEST(NoiseTransport, EncryptInPlaceRefusesMissingTagRoomAndMarksAFailedEncrypt) ASSERT_TRUE(r.has_value()); NoiseCipherState* send_cs = r->responder_session->send_cipher_; NoiseTransport transport; - transport.activate(std::move(r->responder_session)); + transport.activate(std::move(*r->responder_session)); if (row.c == Case::NONCE_EXHAUSTED) { ASSERT_EQ(noise_cipherstate_set_nonce(send_cs, UINT64_MAX), NOISE_ERROR_NONE); } From ba616043c2402b6c92174fdc59df364674b3a24d Mon Sep 17 00:00:00 2001 From: Kevin Ahrendt Date: Tue, 3 Nov 2026 06:44:23 -0500 Subject: [PATCH 2/5] Hold the Noise handshake driver inside the connection SendspinConnection keeps its NoiseHandshake in a std::optional, emplaced by init_noise_handshake() and reset when the handshake completes or aborts, instead of allocating it per connection. The connection carries the driver's storage for its whole life. Accept to admission: 5 -> 4 allocations under libc++, 7 -> 6 under libstdc++. --- src/connection.cpp | 3 +-- src/connection.h | 9 +++++---- tests/test_allocations.cpp | 4 ++-- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/src/connection.cpp b/src/connection.cpp index d2f66e81..b871eed0 100644 --- a/src/connection.cpp +++ b/src/connection.cpp @@ -225,8 +225,7 @@ std::optional SendspinConnection::claim_time_frame(int64_t client_trans void SendspinConnection::init_noise_handshake(const Identity& identity, const RecordStore& record_store, const char* suite_name) { - this->noise_handshake_ = - std::make_unique(identity, record_store, suite_name, *this->json_arena_); + this->noise_handshake_.emplace(identity, record_store, suite_name, *this->json_arena_); // Retain for re-handshake: these pointers outlive connections (owned by the // SendspinClient that constructed the manager which called this). this->noise_identity_ = &identity; diff --git a/src/connection.h b/src/connection.h index 07797844..d29f235e 100644 --- a/src/connection.h +++ b/src/connection.h @@ -191,7 +191,7 @@ class SendspinConnection : public std::enable_shared_from_thisnoise_handshake_ != nullptr; + return this->noise_handshake_.has_value(); } /// @brief Return the full Noise suite name supplied at init_noise_handshake() (e.g. @@ -1033,15 +1033,16 @@ class SendspinConnection : public std::enable_shared_from_this noise_handshake_; + // Pointer fields /// Time synchronization filter (Kalman-based). Shared so role threads can hold it without /// holding this connection (ConnectionManager::time_filter()). std::shared_ptr time_filter_; - /// Noise handshake driver (active from connection open until handshake complete). - std::unique_ptr noise_handshake_; - /// Retained for re-handshake: pointer to the client identity supplied at /// init_noise_handshake(). Lifetime is owned by SendspinClient (outlives connections). const Identity* noise_identity_{nullptr}; diff --git a/tests/test_allocations.cpp b/tests/test_allocations.cpp index a1be1f58..bdcd1616 100644 --- a/tests/test_allocations.cpp +++ b/tests/test_allocations.cpp @@ -430,9 +430,9 @@ constexpr int TIME_BURST_SIZE = 8; // libstdc++ (ESP-IDF's) keeps strings of up to 15 characters inline, libc++ up to 22: the fake // server's name, parsed and then published, allocates only under libstdc++. #ifdef _LIBCPP_VERSION -constexpr size_t ADMISSION_ALLOCATIONS = 5; +constexpr size_t ADMISSION_ALLOCATIONS = 4; #else -constexpr size_t ADMISSION_ALLOCATIONS = 7; +constexpr size_t ADMISSION_ALLOCATIONS = 6; #endif constexpr size_t CLIENT_STATE_ALLOCATIONS = 0; constexpr size_t TIME_BURST_ALLOCATIONS = 0; From c4f87c1583943924f3bb5cd4e31f8917b9600566 Mon Sep 17 00:00:00 2001 From: Kevin Ahrendt Date: Tue, 3 Nov 2026 07:33:40 -0500 Subject: [PATCH 3/5] Hand the handshake result to the caller instead of holding it NoiseHandshake::on_text_frame() writes the result into the caller's optional when it returns COMPLETE, so the handshake no longer stores it and take_result() goes. The result, like the handshake core's, carries the admitting PSK's psk_id and category instead of a whole ResolvedPsk: the PSK is mixed into the session's keys before the result is built, so its bytes never leave run_msg1_core(). Every connection carries the handshake inline, which shrinks from 440 to 152 bytes on a 64-bit host (about 384 to 115 on ESP32). No task stack bound changes. --- src/connection.cpp | 19 +++++------ src/noise_handshake.cpp | 35 +++++++++++++-------- src/noise_handshake.h | 32 +++++++++---------- tests/loopback_connection.h | 16 +++++----- tests/test_noise_rehandshake.cpp | 13 ++++---- tests/test_noise_transport.cpp | 54 ++++++++++++++++++++------------ 6 files changed, 95 insertions(+), 74 deletions(-) diff --git a/src/connection.cpp b/src/connection.cpp index b871eed0..d3620a8b 100644 --- a/src/connection.cpp +++ b/src/connection.cpp @@ -26,6 +26,7 @@ #include "time_filter.h" #include +#include #include #include #include @@ -263,7 +264,8 @@ void SendspinConnection::handle_noise_handshake_text(std::string_view text) { return this->send_json(msg) == SsErr::OK; }; - HandshakeFrameResult result = this->noise_handshake_->on_text_frame(text, send_fn); + std::optional outcome; + HandshakeFrameResult result = this->noise_handshake_->on_text_frame(text, send_fn, outcome); if (result == HandshakeFrameResult::ABORT) { const std::string& server_error = this->noise_handshake_->server_error_reason(); @@ -282,16 +284,11 @@ void SendspinConnection::handle_noise_handshake_text(std::string_view text) { } if (result == HandshakeFrameResult::COMPLETE) { - auto outcome = this->noise_handshake_->take_result(); - if (!outcome.has_value()) { - SS_LOGE(TAG, "Noise handshake: COMPLETE but no result"); - this->noise_handshake_.reset(); - return; - } + 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->resolved_psk.category, - outcome->resolved_psk.psk_id.view()); + this->set_noise_handshake_result(outcome->server_id.view(), outcome->psk_category, + outcome->psk_id.view()); // pairing.md "Pairing index": a fresh handshake starts a fresh count for the // pairing_index / CPace-sid counter. this->reset_pairing_index(); @@ -371,8 +368,8 @@ bool SendspinConnection::handle_noise_rehandshake(std::span msg1_bytes) } // Update PSK metadata from the re-handshake result. server_id is unchanged (same server). - this->psk_category_ = result->resolved_psk.category; - this->psk_id_ = result->resolved_psk.psk_id; + this->psk_category_ = result->psk_category; + this->psk_id_ = result->psk_id; // pairing.md "Pairing index": a re-handshake starts a fresh count for the pairing_index / // CPace-sid counter, same as an initial handshake. diff --git a/src/noise_handshake.cpp b/src/noise_handshake.cpp index bd91190e..89451d5a 100644 --- a/src/noise_handshake.cpp +++ b/src/noise_handshake.cpp @@ -90,8 +90,11 @@ namespace { struct Msg1CoreResult { /// The session, split into transport cipher states, with the resolved PSK bound. NoiseSession session; - /// The PSK record that admitted the connection. - ResolvedPsk resolved_psk; + /// psk_id of the PSK that admitted the connection. Its bytes stay in run_msg1_core()'s + /// ResolvedPsk, wiped when that returns. + IdText psk_id; + /// Category of that PSK. + PskCategory psk_category{PskCategory::SENTINEL}; /// Serialized noise/handshake msg2 bytes (not yet wrapped in a JSON envelope). NoiseMsg2 msg2_bytes{}; }; @@ -253,19 +256,23 @@ std::optional run_msg1_core(HandshakeKind kind, const Identity& return std::nullopt; } - return Msg1CoreResult{std::move(session.value()), std::move(resolved.value()), msg2_bytes}; + return Msg1CoreResult{.session = std::move(session.value()), + .psk_id = resolved->psk_id, + .psk_category = resolved->category, + .msg2_bytes = msg2_bytes}; } /// @brief Build a NoiseHandshakeResult from a completed Msg1CoreResult. Shared by /// NoiseHandshake::handle_msg1 (initial handshake) and run_rehandshake_msg1: both assemble the -/// result identically from the core's session and resolved_psk; only msg2 differs, so the -/// caller sets it afterward. -/// @param core Completed core result (session and resolved_psk are moved out of it). +/// result identically from the core's session and PSK; only msg2 differs, so the caller sets it +/// afterward. +/// @param core Completed core result (its session is moved out of it). /// @param server_id Server peer_id to record on the result. NoiseHandshakeResult make_handshake_result(Msg1CoreResult&& core, const IdText& server_id) { return NoiseHandshakeResult{.session = std::move(core.session), .server_id = server_id, - .resolved_psk = std::move(core.resolved_psk)}; + .psk_id = core.psk_id, + .psk_category = core.psk_category}; } } // namespace @@ -338,7 +345,8 @@ void NoiseHandshake::take_server_error(JsonObjectConst root, const char* log_con } HandshakeFrameResult NoiseHandshake::on_text_frame( - std::string_view text, const std::function& send_fn) { + std::string_view text, const std::function& send_fn, + std::optional& completed) { if (this->state_ != State::WAIT_SERVER_INIT && this->state_ != State::WAIT_MSG1) { SS_LOGE(TAG, "on_text_frame: no frame expected in this state"); this->state_ = State::ABORTED; @@ -399,7 +407,7 @@ HandshakeFrameResult NoiseHandshake::on_text_frame( } if (!msg1_bytes.has_value() || - !this->handle_msg1({msg1_bytes->data(), msg1_bytes->size()}, send_fn)) { + !this->handle_msg1({msg1_bytes->data(), msg1_bytes->size()}, send_fn, completed)) { this->state_ = State::ABORTED; return HandshakeFrameResult::ABORT; } @@ -446,7 +454,8 @@ bool NoiseHandshake::handle_server_init(int version, const IdText& server_id, // ============================================================================ bool NoiseHandshake::handle_msg1(std::span msg1_bytes, - const std::function& send_fn) { + const std::function& send_fn, + std::optional& completed) { // Prologue = exact bytes of client/init || server/init const uint8_t* prologue = this->prologue_.data(); const size_t prologue_len = this->client_init_size_ + this->server_init_size_; @@ -466,9 +475,9 @@ bool NoiseHandshake::handle_msg1(std::span msg1_bytes, } SS_LOGI(TAG, "Noise handshake complete: server_id=%s psk_category=%d", this->server_id_.c_str(), - static_cast(core->resolved_psk.category)); + static_cast(core->psk_category)); - this->result_ = make_handshake_result(std::move(core.value()), this->server_id_); + completed = make_handshake_result(std::move(core.value()), this->server_id_); return true; } @@ -495,7 +504,7 @@ std::optional run_rehandshake_msg1( } SS_LOGI(TAG, "Re-handshake complete: server_id=%s psk_category=%d", known_server_id.c_str(), - static_cast(core->resolved_psk.category)); + static_cast(core->psk_category)); // The caller wraps msg2 in its noise/handshake envelope and sends it encrypted. const NoiseMsg2 msg2_bytes = core->msg2_bytes; diff --git a/src/noise_handshake.h b/src/noise_handshake.h index 52d25759..6efa79b8 100644 --- a/src/noise_handshake.h +++ b/src/noise_handshake.h @@ -64,8 +64,11 @@ struct NoiseHandshakeResult { NoiseSession session; /// Server's public key peer_id (43-char base64url). IdText server_id; - /// The PSK record that admitted the connection. - ResolvedPsk resolved_psk; + /// psk_id of the PSK that admitted the connection. The handshake has already mixed the PSK + /// into session's keys, so the result carries none of its bytes. + IdText psk_id; + /// Category of that PSK. + PskCategory psk_category{PskCategory::SENTINEL}; /// The Noise msg2 bytes to send to the peer, in a noise/handshake envelope /// (build_noise_handshake_message()). Set only for re-handshake results (initial handshake /// sends msg2 inline). @@ -146,8 +149,8 @@ static constexpr size_t MAX_SERVER_INIT_BYTES = 512; /// @brief Noise handshake state machine for the Sendspin client (Noise responder). /// -/// build_client_init() produces the first cleartext frame, on_text_frame() takes each incoming -/// text frame, and take_result() yields the session once that returns COMPLETE. +/// build_client_init() produces the first cleartext frame, and on_text_frame() takes each +/// incoming text frame, handing out the session with the frame that completes the handshake. /// /// Threading: runs entirely on the protocol task, which is where RecordStore::resolve_by_psk_id() /// runs (see record_store.h). @@ -181,10 +184,13 @@ class NoiseHandshake { /// @brief Process one incoming WS text frame. /// Must be called in sequence: server/init, then noise/handshake msg1. - /// @param send_fn Callable that sends a JSON message to the peer as a TEXT frame. - /// Signature: `bool send_fn(const JsonDocument& msg)`. + /// @param send_fn Callable that sends a JSON message to the peer as a TEXT frame. + /// Signature: `bool send_fn(const JsonDocument& msg)`. + /// @param completed Set to the handshake's result when this returns COMPLETE, untouched + /// otherwise. HandshakeFrameResult on_text_frame(std::string_view text, - const std::function& send_fn); + const std::function& send_fn, + std::optional& completed); /// @brief The reason carried by a server/error received during the handshake, or empty. /// @@ -195,11 +201,6 @@ class NoiseHandshake { return this->server_error_reason_; } - /// @brief Take ownership of the handshake result (only valid after COMPLETE). - std::optional take_result() { - return std::move(this->result_); - } - private: enum class State : uint8_t { INIT, ///< client/init not yet sent @@ -225,18 +226,17 @@ class NoiseHandshake { /// @param msg1_bytes The msg1 Noise bytes, read from the frame (read_noise_handshake_data()); /// cleared on return. /// @param send_fn Sends the msg2 frame back to the peer. + /// @param completed Set to the handshake's result on success. /// @return true when msg1 authenticated and msg2 was sent. bool handle_msg1(std::span msg1_bytes, - const std::function& send_fn); + const std::function& send_fn, + std::optional& completed); // Struct fields /// The prologue: the exact bytes of the client/init we sent, then of the server/init we /// received, in one buffer sized for both when client/init is built. PlatformBuffer prologue_; - /// Result available after COMPLETE. - std::optional result_; - /// Reason from a received server/error. See server_error_reason(). std::string server_error_reason_; diff --git a/tests/loopback_connection.h b/tests/loopback_connection.h index 780d98d0..7030d5e8 100644 --- a/tests/loopback_connection.h +++ b/tests/loopback_connection.h @@ -246,6 +246,7 @@ inline std::optional run_loopback_handshake(const std::string& s // ----------------------------------------------------------------- TestArena arena; NoiseHandshake nh(client_id, rs, suite_name.c_str(), arena); + std::optional completed; // Step 1: client sends client/init std::string client_init(nh.build_client_init()); @@ -282,7 +283,7 @@ inline std::optional run_loopback_handshake(const std::string& s return true; }; - HandshakeFrameResult r1 = nh.on_text_frame(server_init_text, send_fn); + HandshakeFrameResult r1 = nh.on_text_frame(server_init_text, send_fn, completed); EXPECT_EQ(r1, HandshakeFrameResult::NEED_MORE); EXPECT_TRUE(captured_msg2.empty()); // No msg2 yet @@ -310,7 +311,7 @@ inline std::optional run_loopback_handshake(const std::string& s // Step 4: our driver processes msg1 // on_text_frame should: decrypt msg1, resolve PSK, write msg2, return COMPLETE // ----------------------------------------------------------------- - HandshakeFrameResult r2 = nh.on_text_frame(msg1_text, send_fn); + HandshakeFrameResult r2 = nh.on_text_frame(msg1_text, send_fn, completed); EXPECT_EQ(r2, HandshakeFrameResult::COMPLETE); EXPECT_FALSE(captured_msg2.empty()) << "Expected msg2 to be sent"; @@ -351,15 +352,14 @@ inline std::optional run_loopback_handshake(const std::string& s NOISE_ERROR_NONE); // noise_handshakestate_split does not free the hs; the guard destructor will free it. - auto outcome = nh.take_result(); - EXPECT_TRUE(outcome.has_value()); - if (!outcome.has_value()) { + EXPECT_TRUE(completed.has_value()); + if (!completed.has_value()) { return std::nullopt; } - EXPECT_FALSE(outcome->server_id.empty()); - EXPECT_EQ(outcome->server_id, server_id.peer_id()); + EXPECT_FALSE(completed->server_id.empty()); + EXPECT_EQ(completed->server_id, server_id.peer_id()); - result.responder_session = std::move(outcome->session); + result.responder_session = std::move(completed->session); return result; } diff --git a/tests/test_noise_rehandshake.cpp b/tests/test_noise_rehandshake.cpp index 7b863b58..bce07eef 100644 --- a/tests/test_noise_rehandshake.cpp +++ b/tests/test_noise_rehandshake.cpp @@ -99,6 +99,7 @@ static std::optional run_initial_handshake(const std::st // Run initial handshake via NoiseHandshake state machine TestArena arena; NoiseHandshake nh(r.client_id, rs, suite_name.c_str(), arena); + std::optional completed; std::string client_init(nh.build_client_init()); if (client_init.empty()) { return std::nullopt; } @@ -116,7 +117,8 @@ static std::optional run_initial_handshake(const std::st captured_msg2 = to_text(msg); return true; }; - EXPECT_EQ(nh.on_text_frame(server_init_text, send_fn), HandshakeFrameResult::NEED_MORE); + EXPECT_EQ(nh.on_text_frame(server_init_text, send_fn, completed), + HandshakeFrameResult::NEED_MORE); // Build initiator msg1 const uint8_t* prologue = reinterpret_cast(prologue_str.data()); @@ -133,7 +135,7 @@ static std::optional run_initial_handshake(const std::st return std::nullopt; } - EXPECT_EQ(nh.on_text_frame(msg1_text, send_fn), HandshakeFrameResult::COMPLETE); + EXPECT_EQ(nh.on_text_frame(msg1_text, send_fn, completed), HandshakeFrameResult::COMPLETE); if (captured_msg2.empty()) { return std::nullopt; } // Initiator reads msg2 @@ -159,10 +161,9 @@ static std::optional run_initial_handshake(const std::st return std::nullopt; } - auto outcome = nh.take_result(); - if (!outcome.has_value()) { return std::nullopt; } - r.responder_h = outcome->session.handshake_hash(); - r.responder_session = std::move(outcome->session); + if (!completed.has_value()) { return std::nullopt; } + r.responder_h = completed->session.handshake_hash(); + r.responder_session = std::move(completed->session); return r; } diff --git a/tests/test_noise_transport.cpp b/tests/test_noise_transport.cpp index 563d6be3..5687ae4a 100644 --- a/tests/test_noise_transport.cpp +++ b/tests/test_noise_transport.cpp @@ -250,6 +250,7 @@ TEST(NoiseHandshakeDriver, CounterpartyMismatchAborts) { TestArena arena; NoiseHandshake nh(client_id, rs, NOISE_SUITE_CHACHAPOLY, arena); + std::optional completed; std::string client_init(nh.build_client_init()); std::string server_init_text = make_server_init(server_id.peer_id()); @@ -258,7 +259,8 @@ TEST(NoiseHandshakeDriver, CounterpartyMismatchAborts) { size_t prologue_len = prologue_str.size(); // server/init: NEED_MORE - auto r1 = nh.on_text_frame(server_init_text, [](const JsonDocument&) { return true; }); + auto r1 = + nh.on_text_frame(server_init_text, [](const JsonDocument&) { return true; }, completed); EXPECT_EQ(r1, HandshakeFrameResult::NEED_MORE); // The initiator uses the stored PSK, so only the counterparty binding differs. @@ -272,7 +274,7 @@ TEST(NoiseHandshakeDriver, CounterpartyMismatchAborts) { std::string msg1_text = build_msg1_envelope(init_hs_raw, psk_id_val); ASSERT_FALSE(msg1_text.empty()); - auto r2 = nh.on_text_frame(msg1_text, [](const JsonDocument&) { return true; }); + auto r2 = nh.on_text_frame(msg1_text, [](const JsonDocument&) { return true; }, completed); EXPECT_EQ(r2, HandshakeFrameResult::ABORT); } @@ -314,12 +316,14 @@ Msg1Outcome run_msg1_with_payload( TestArena arena; NoiseHandshake nh(client_id, rs, NOISE_SUITE_CHACHAPOLY, arena); + std::optional completed; const std::string client_init(nh.build_client_init()); const std::string server_init_text = make_server_init(server_id.peer_id()); const std::string prologue_str = client_init + server_init_text; - EXPECT_EQ(nh.on_text_frame(server_init_text, [](const JsonDocument&) { return true; }), - HandshakeFrameResult::NEED_MORE); + EXPECT_EQ( + nh.on_text_frame(server_init_text, [](const JsonDocument&) { return true; }, completed), + HandshakeFrameResult::NEED_MORE); NoiseHandshakeState* init_hs_raw = build_initiator( std::string(NOISE_SUITE_CHACHAPOLY), server_id.private_bytes.data(), @@ -337,18 +341,20 @@ Msg1Outcome run_msg1_with_payload( Msg1Outcome outcome; std::string captured_msg2; - outcome.result = nh.on_text_frame(msg1_text, [&captured_msg2](const JsonDocument& msg) { - captured_msg2 = to_text(msg); - return true; - }); + outcome.result = nh.on_text_frame( + msg1_text, + [&captured_msg2](const JsonDocument& msg) { + captured_msg2 = to_text(msg); + return true; + }, + completed); if (outcome.result != HandshakeFrameResult::COMPLETE) { return outcome; } - auto result = nh.take_result(); - EXPECT_TRUE(result.has_value()); - if (result.has_value()) { - outcome.category = result->resolved_psk.category; + EXPECT_TRUE(completed.has_value()); + if (completed.has_value()) { + outcome.category = completed->psk_category; } // The peer holds the PSK it referenced, so it can only read message 2 if the client bound the @@ -452,10 +458,11 @@ TEST(NoiseHandshakeDriver, ServerErrorWhileAwaitingServerInitAborts) { TestArena arena; NoiseHandshake nh(client_id, rs, NOISE_SUITE_CHACHAPOLY, arena); + std::optional completed; nh.build_client_init(); auto r = nh.on_text_frame(R"({"type":"server/error","payload":{"reason":"unsupported_suite"}})", - [](const JsonDocument&) { return true; }); + [](const JsonDocument&) { return true; }, completed); EXPECT_EQ(r, HandshakeFrameResult::ABORT); EXPECT_EQ(nh.server_error_reason(), "unsupported_suite"); } @@ -468,10 +475,11 @@ TEST(NoiseHandshakeDriver, AbortWithoutServerErrorReportsNoReason) { TestArena arena; NoiseHandshake nh(client_id, rs, NOISE_SUITE_CHACHAPOLY, arena); + std::optional completed; nh.build_client_init(); auto r = nh.on_text_frame(R"({"type":"server/init","payload":{"version":99}})", - [](const JsonDocument&) { return true; }); + [](const JsonDocument&) { return true; }, completed); EXPECT_EQ(r, HandshakeFrameResult::ABORT); EXPECT_TRUE(nh.server_error_reason().empty()); } @@ -485,13 +493,14 @@ TEST(NoiseHandshakeDriver, ServerErrorWhileAwaitingMsg1Aborts) { TestArena arena; NoiseHandshake nh(client_id, rs, NOISE_SUITE_CHACHAPOLY, arena); + std::optional completed; nh.build_client_init(); ASSERT_EQ(nh.on_text_frame(make_server_init(server_id.peer_id()), - [](const JsonDocument&) { return true; }), + [](const JsonDocument&) { return true; }, completed), HandshakeFrameResult::NEED_MORE); auto r = nh.on_text_frame(R"({"type":"server/error","payload":{"reason":"malformed"}})", - [](const JsonDocument&) { return true; }); + [](const JsonDocument&) { return true; }, completed); EXPECT_EQ(r, HandshakeFrameResult::ABORT); EXPECT_EQ(nh.server_error_reason(), "malformed"); } @@ -538,6 +547,7 @@ TEST(NoiseHandshakeDriver, ServerInitIsRefusedUnlessWellFormed) { TestArena arena; NoiseHandshake nh(client_id, rs, NOISE_SUITE_CHACHAPOLY, arena); + std::optional completed; nh.build_client_init(); std::string peer_id = server_id.peer_id(); @@ -552,7 +562,8 @@ TEST(NoiseHandshakeDriver, ServerInitIsRefusedUnlessWellFormed) { pad_with_unknown_field(frame, row.padded_to, 2); ASSERT_FALSE(HasFatalFailure()); } - EXPECT_EQ(nh.on_text_frame(frame, [](const JsonDocument&) { return true; }), row.expected); + EXPECT_EQ(nh.on_text_frame(frame, [](const JsonDocument&) { return true; }, completed), + row.expected); } } @@ -1332,13 +1343,16 @@ TEST(NoiseHandshakeDriver, MalformedMsg1Aborts) { TestArena arena; NoiseHandshake nh(client_id, rs, NOISE_SUITE_CHACHAPOLY, arena); + std::optional completed; const std::string client_init(nh.build_client_init()); const std::string server_init_text = make_server_init(server_id.peer_id()); auto send_fn = [](const JsonDocument&) { return true; }; - ASSERT_EQ(nh.on_text_frame(server_init_text, send_fn), HandshakeFrameResult::NEED_MORE); + ASSERT_EQ(nh.on_text_frame(server_init_text, send_fn, completed), + HandshakeFrameResult::NEED_MORE); if (!row.well_formed) { - EXPECT_EQ(nh.on_text_frame(make_noise_handshake_envelope(row.noise_bytes), send_fn), + EXPECT_EQ(nh.on_text_frame(make_noise_handshake_envelope(row.noise_bytes), send_fn, + completed), row.expected); continue; } @@ -1360,7 +1374,7 @@ TEST(NoiseHandshakeDriver, MalformedMsg1Aborts) { } const std::string msg1_text = build_msg1_envelope_with_payload(init_hs_raw, payload); ASSERT_FALSE(msg1_text.empty()); - EXPECT_EQ(nh.on_text_frame(msg1_text, send_fn), row.expected); + EXPECT_EQ(nh.on_text_frame(msg1_text, send_fn, completed), row.expected); } } From cbd58ba2468923fac616c828d79f17e6cbcc609a Mon Sep 17 00:00:00 2001 From: Kevin Ahrendt Date: Tue, 3 Nov 2026 08:33:59 -0500 Subject: [PATCH 4/5] Build the handshake result in place handle_msg1() emplaces its result in the caller's optional, and run_rehandshake_msg1() returns it as a prvalue, so neither frame holds a result temporary; a named optional would not be elided by GCC, since the re-handshake also returns nullopt. The re-handshake test now checks the result's psk_id. ESP32 frames: handle_msg1 480 -> 304 bytes (-Os), 496 -> 304 (-Og); run_rehandshake_msg1 528 -> 272 at both. No task stack bound changes. --- src/noise_handshake.cpp | 27 ++++++++------------------- tests/test_noise_rehandshake.cpp | 2 ++ 2 files changed, 10 insertions(+), 19 deletions(-) diff --git a/src/noise_handshake.cpp b/src/noise_handshake.cpp index 89451d5a..37ac6314 100644 --- a/src/noise_handshake.cpp +++ b/src/noise_handshake.cpp @@ -262,19 +262,6 @@ std::optional run_msg1_core(HandshakeKind kind, const Identity& .msg2_bytes = msg2_bytes}; } -/// @brief Build a NoiseHandshakeResult from a completed Msg1CoreResult. Shared by -/// NoiseHandshake::handle_msg1 (initial handshake) and run_rehandshake_msg1: both assemble the -/// result identically from the core's session and PSK; only msg2 differs, so the caller sets it -/// afterward. -/// @param core Completed core result (its session is moved out of it). -/// @param server_id Server peer_id to record on the result. -NoiseHandshakeResult make_handshake_result(Msg1CoreResult&& core, const IdText& server_id) { - return NoiseHandshakeResult{.session = std::move(core.session), - .server_id = server_id, - .psk_id = core.psk_id, - .psk_category = core.psk_category}; -} - } // namespace // ============================================================================ @@ -477,7 +464,8 @@ bool NoiseHandshake::handle_msg1(std::span msg1_bytes, SS_LOGI(TAG, "Noise handshake complete: server_id=%s psk_category=%d", this->server_id_.c_str(), static_cast(core->psk_category)); - completed = make_handshake_result(std::move(core.value()), this->server_id_); + // Built in the caller's optional, so no result temporary sits on this frame. + completed.emplace(std::move(core->session), this->server_id_, core->psk_id, core->psk_category); return true; } @@ -506,11 +494,12 @@ std::optional run_rehandshake_msg1( SS_LOGI(TAG, "Re-handshake complete: server_id=%s psk_category=%d", known_server_id.c_str(), static_cast(core->psk_category)); - // The caller wraps msg2 in its noise/handshake envelope and sends it encrypted. - const NoiseMsg2 msg2_bytes = core->msg2_bytes; - NoiseHandshakeResult result = make_handshake_result(std::move(core.value()), known_server_id); - result.msg2_bytes = msg2_bytes; - return result; + // 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); } } // namespace sendspin diff --git a/tests/test_noise_rehandshake.cpp b/tests/test_noise_rehandshake.cpp index bce07eef..f5886164 100644 --- a/tests/test_noise_rehandshake.cpp +++ b/tests/test_noise_rehandshake.cpp @@ -241,6 +241,8 @@ static std::optional run_rehandshake( ADD_FAILURE() << "run_rehandshake_msg1 returned nullopt"; return std::nullopt; } + // The PSK the re-handshake resolved, which becomes the connection's psk_id. + EXPECT_EQ(result->psk_id.view(), rehs_psk_id); // The result carries msg2's Noise bytes; the initiator reads them directly. NoiseMsg2& msg2_bytes = result->msg2_bytes; From 54f3e278975bf18ae507b74113ede466fc502798 Mon Sep 17 00:00:00 2001 From: Kevin Ahrendt Date: Tue, 3 Nov 2026 10:05:51 -0500 Subject: [PATCH 5/5] Mark the transport session dereference as checked by the callers Both encrypt_in_place() callers refuse before it when no session is installed, which clang-tidy cannot see now that the session is an optional held by value (bugprone-unchecked-optional-access). --- src/noise_transport.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/noise_transport.cpp b/src/noise_transport.cpp index 073650e7..a7b303db 100644 --- a/src/noise_transport.cpp +++ b/src/noise_transport.cpp @@ -57,6 +57,7 @@ size_t NoiseTransport::encrypt_in_place(uint8_t* buf, size_t buf_capacity, size_ #endif // noise-c advances the send nonce past a failed encrypt too. + // NOLINTNEXTLINE(bugprone-unchecked-optional-access): callers check the session first const size_t ct_len = this->session_->encrypt(buf, plaintext_len, buf_capacity); if (ct_len == 0) { SS_LOGE(TAG, "Noise encrypt failed");