diff --git a/src/connection.cpp b/src/connection.cpp index d2f66e81..d3620a8b 100644 --- a/src/connection.cpp +++ b/src/connection.cpp @@ -26,6 +26,7 @@ #include "time_filter.h" #include +#include #include #include #include @@ -225,8 +226,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; @@ -264,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(); @@ -283,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(); @@ -372,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/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/src/noise_handshake.cpp b/src/noise_handshake.cpp index 1a7bef33..37ac6314 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,21 +256,10 @@ std::optional run_msg1_core(HandshakeKind kind, const Identity& return std::nullopt; } - return Msg1CoreResult{std::move(session.value()), std::move(resolved.value()), 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). -/// @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 Msg1CoreResult{.session = std::move(session.value()), + .psk_id = resolved->psk_id, + .psk_category = resolved->category, + .msg2_bytes = msg2_bytes}; } } // namespace @@ -340,7 +332,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; @@ -401,7 +394,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; } @@ -448,7 +441,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_; @@ -468,9 +462,10 @@ 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_); + // 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; } @@ -497,13 +492,14 @@ 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)); - - // 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; + 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); } } // namespace sendspin diff --git a/src/noise_handshake.h b/src/noise_handshake.h index 000ad309..6efa79b8 100644 --- a/src/noise_handshake.h +++ b/src/noise_handshake.h @@ -48,7 +48,6 @@ #include #include #include -#include #include #include #include @@ -62,11 +61,14 @@ 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. - 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). @@ -147,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). @@ -182,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. /// @@ -196,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 @@ -226,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/src/noise_transport.cpp b/src/noise_transport.cpp index 024af955..a7b303db 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 { @@ -58,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"); @@ -147,7 +147,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..7030d5e8 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; @@ -247,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()); @@ -283,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 @@ -311,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"; @@ -352,16 +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_TRUE(outcome->session != nullptr); - 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_allocations.cpp b/tests/test_allocations.cpp index aa98c61f..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 = 6; +constexpr size_t ADMISSION_ALLOCATIONS = 4; #else -constexpr size_t ADMISSION_ALLOCATIONS = 8; +constexpr size_t ADMISSION_ALLOCATIONS = 6; #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..f5886164 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; @@ -100,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; } @@ -117,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()); @@ -134,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 @@ -160,10 +161,9 @@ static std::optional run_initial_handshake(const std::st return std::nullopt; } - auto outcome = nh.take_result(); - if (!outcome.has_value() || !outcome->session) { 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; } @@ -205,7 +205,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 }; @@ -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; @@ -267,7 +269,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..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,19 +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_NE(result->session, nullptr) << "a completed handshake must carry its session"; + 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 @@ -453,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"); } @@ -469,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()); } @@ -486,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"); } @@ -539,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(); @@ -553,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); } } @@ -1266,7 +1276,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); } @@ -1333,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; } @@ -1361,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); } }