diff --git a/docs/playback-sync.md b/docs/playback-sync.md index 44f93a26..825bfa6a 100644 --- a/docs/playback-sync.md +++ b/docs/playback-sync.md @@ -10,7 +10,7 @@ Each connection owns one `SendspinTimeFilter` (`src/time_filter.h`), created onc Each `client/time` round trip is timed from the socket write, not from the time the message carries: `SendspinConnection::send_time_message()` hands `NoiseTransport::send_staged_json()` a hook that the transport runs immediately before writing the message's frame, and the echoed `client_transmitted` only identifies the frame a `server/time` answers (`SendspinConnection::claim_time_frame()`). Recording the write time before the write, never after it, keeps every scheduling delay on the side that lengthens the measured round trip, which `max_error` reports and the burst's lowest-round-trip selection discards. -The filter is a two-state `[offset, drift]` Kalman filter, tuned by `SendspinTimeFilter::Config`. Drift is estimated from the second measurement on, but applied to time conversions only once it is statistically significant (`drift_significance_threshold`). Once `min_samples` measurements have accumulated, a residual larger than `adaptive_cutoff` times the measurement's round-trip error inflates the covariances, so the filter recovers quickly from a step change in the server's clock. The protocol task alone updates and reads it; the sync task and the visualizer drain thread convert timestamps through the copy of its transform it publishes. +The filter is a two-state `[offset, drift]` Kalman filter, tuned by the constants in `src/time_filter.cpp`. Drift is estimated from the second measurement on, but applied to time conversions only once it is statistically significant (`DRIFT_SIGNIFICANCE_THRESHOLD_SQUARED`). Once `MIN_SAMPLES_FOR_FORGETTING` measurements have accumulated, a residual larger than `ADAPTIVE_CUTOFF` times the measurement's round-trip error inflates the covariances, so the filter recovers quickly from a step change in the server's clock. The protocol task alone updates and reads it; the sync task and the visualizer drain thread convert timestamps through the copy of its transform it publishes. The filter's first measurement gates playback: the sync task decodes no audio until the clock is synced. While the player or source role is active, it also gates the connection's `client/state` (messaging.md "Clock Synchronization", "stream/start"). diff --git a/src/client_dispatch.cpp b/src/client_dispatch.cpp index 9064fe21..c81fb38d 100644 --- a/src/client_dispatch.cpp +++ b/src/client_dispatch.cpp @@ -114,7 +114,7 @@ namespace { /// close_silently()). Protocol task only. [[maybe_unused]] void close_on_malformed_binary(SendspinConnection* conn, SendspinRole role) { SS_LOGW(TAG, "Malformed %s message; closing connection", to_cstr(role)); - conn->close_silently(SendspinGoodbyeReason::UNAUTHORIZED); + conn->close_silently(); } } // namespace @@ -628,12 +628,8 @@ void SendspinClient::process_json_message(SendspinConnection& connection, const if (!msg1_bytes.has_value() || !conn->handle_noise_rehandshake({msg1_bytes->data(), msg1_bytes->size()})) { SS_LOGW(TAG, "noise/handshake re-handshake failed; closing connection"); - // Do not leave a half-swapped session. UNAUTHORIZED is the closest available - // reason for a crypto failure, though close_silently() never transmits it - // (connection.md "Failure Handling": close without any application-level - // message). disconnect() can block on a transport join, which close_silently() - // avoids; see close_transport_now()'s doc comment in connection.h. - conn->close_silently(SendspinGoodbyeReason::UNAUTHORIZED); + // Do not leave a half-swapped session (connection.md "Failure Handling"). + conn->close_silently(); } break; } @@ -706,7 +702,7 @@ void SendspinClient::process_json_message(SendspinConnection& connection, const // error the client MUST close the connection on, so nothing else in the message is // applied. Closed silently, like every other protocol error the receive path finds // (see close_silently()). - conn->close_silently(SendspinGoodbyeReason::UNAUTHORIZED); + conn->close_silently(); break; } #endif @@ -787,7 +783,7 @@ void SendspinClient::process_json_message(SendspinConnection& connection, const // close_silently()). One the client had no memory to normalize closes it too, // rather than applying the rest of the update under the previous group's id; on the // next connection the server sends the group again after its first server/activate. - conn->close_silently(SendspinGoodbyeReason::UNAUTHORIZED); + conn->close_silently(); break; } if (group_msg.group_id_normalized && conn->note_group_id_normalized()) { diff --git a/src/connection.cpp b/src/connection.cpp index 1edcde02..de50642d 100644 --- a/src/connection.cpp +++ b/src/connection.cpp @@ -142,7 +142,7 @@ SsErr SendspinConnection::settle_noise_send(SsErr err) { this->is_connected()) { SS_LOGW(TAG, "Send failed after its frame was encrypted (err=%d); closing the connection", static_cast(err)); - this->close_silently(SendspinGoodbyeReason::UNAUTHORIZED); + this->close_silently(); } return err; } @@ -237,7 +237,7 @@ void SendspinConnection::send_noise_client_init() { // No memory for the prologue: without client/init the peer never proceeds, so the // connection would only hold its nursery slot until the establish deadline. this->noise_handshake_.reset(); - this->close_silently(SendspinGoodbyeReason::UNAUTHORIZED); + this->close_silently(); return; } #ifdef SENDSPIN_ENABLE_MESSAGE_TRACE @@ -271,7 +271,7 @@ void SendspinConnection::handle_noise_handshake_text(std::string_view text) { // connection.md "Failure Handling": a handshake-phase failure closes the WebSocket // without sending any application-level message. this->noise_handshake_.reset(); - this->close_silently(SendspinGoodbyeReason::UNAUTHORIZED); + this->close_silently(); return; } @@ -424,7 +424,7 @@ SS_HOT SendspinConnection::InboundDispatch SendspinConnection::process_inbound_m // connection.md "Failure Handling": a cleartext message after the switch to transport // mode is a silent failure. SS_LOGW(TAG, "TEXT frame in transport mode; closing connection"); - this->close_silently(SendspinGoodbyeReason::UNAUTHORIZED); + this->close_silently(); return InboundDispatch::NONE; } SS_LOGW(TAG, "TEXT frame before the Noise handshake started; dropping"); @@ -439,7 +439,7 @@ SS_HOT SendspinConnection::InboundDispatch SendspinConnection::process_inbound_m // with the Noise/PSK/admission chain bypassed. Treated as a handshake-phase failure // per connection.md "Failure Handling": close without any application-level message. SS_LOGW(TAG, "Binary frame before the Noise handshake completed; closing connection"); - this->close_silently(SendspinGoodbyeReason::UNAUTHORIZED); + this->close_silently(); return InboundDispatch::NONE; } SS_LOGW(TAG, "Binary frame before the Noise handshake started; dropping"); @@ -456,7 +456,7 @@ SS_HOT SendspinConnection::InboundDispatch SendspinConnection::process_inbound_m // advances the receive-direction nonce counter on an auth failure, so every later frame // on this connection would fail authentication forever too. SS_LOGW(TAG, "Noise AEAD failure in transport mode; closing connection"); - this->close_silently(SendspinGoodbyeReason::UNAUTHORIZED); + this->close_silently(); return InboundDispatch::NONE; } // Route through the fragment state machine; hand any completed message to the caller. @@ -466,7 +466,7 @@ SS_HOT SendspinConnection::InboundDispatch SendspinConnection::process_inbound_m // A protocol error the receiver MUST close the connection for; // NoiseTransport::CompleteMessage::malformed enumerates the cases that set it. SS_LOGW(TAG, "Malformed binary message; closing connection"); - this->close_silently(SendspinGoodbyeReason::UNAUTHORIZED); + this->close_silently(); return InboundDispatch::NONE; } if (reassembled.data == nullptr) { diff --git a/src/connection.h b/src/connection.h index 79bbc338..cc27eafe 100644 --- a/src/connection.h +++ b/src/connection.h @@ -201,7 +201,7 @@ class SendspinConnection : public std::enable_shared_from_thisnoise_suite_name_; } @@ -337,7 +337,7 @@ class SendspinConnection : public std::enable_shared_from_thisdetach_inbound(); this->close_transport_now(); } diff --git a/src/connection_manager.cpp b/src/connection_manager.cpp index 2f6bfc5e..2d0d3762 100644 --- a/src/connection_manager.cpp +++ b/src/connection_manager.cpp @@ -1204,7 +1204,7 @@ uint32_t ConnectionManager::maybe_start_ws_server(int64_t now_us) { this->ws_server_->set_discard_capacity( std::max(ring != nullptr ? ring->largest_message_bytes() : INBOUND_MAX_MESSAGE_BYTES, InboundGate::PRE_ADMISSION_MESSAGE_BYTES)); - if (!this->ws_server_->start(this->client_, this->client_->config_.httpd_psram_stack, + if (!this->ws_server_->start(this->client_->config_.httpd_psram_stack, this->client_->config_.httpd_priority, this->client_->config_.httpd_stack_size)) { // A persistent failure (e.g. the server port is already in use) is retried with backoff diff --git a/src/connection_manager_pairing.cpp b/src/connection_manager_pairing.cpp index ddeb4fb4..7fdccf28 100644 --- a/src/connection_manager_pairing.cpp +++ b/src/connection_manager_pairing.cpp @@ -756,7 +756,7 @@ void ConnectionManager::close_on_malformed_message(SendspinConnection* conn) { SendspinPairAbortReason::UNKNOWN); return; } - conn->close_silently(SendspinGoodbyeReason::UNAUTHORIZED); + conn->close_silently(); } void ConnectionManager::close_on_sequence_violation(SendspinConnection* conn, diff --git a/src/crypto/pairing_code.cpp b/src/crypto/pairing_code.cpp index 1e387be0..28e2f7a0 100644 --- a/src/crypto/pairing_code.cpp +++ b/src/crypto/pairing_code.cpp @@ -58,22 +58,6 @@ std::optional> pairing_code_commit(cons return commitment; } -// ============================================================================ -// pairing_code_verify_commit -// ============================================================================ - -bool pairing_code_verify_commit(const uint8_t* nonce, size_t nonce_len, const uint8_t* commitment, - size_t commitment_len) { - if (commitment_len != PAIRING_COMMIT_SIZE || nonce_len != PAIRING_NONCE_SIZE) { - return false; - } - auto computed = pairing_code_commit(nonce, nonce_len); - if (!computed.has_value()) { - return false; - } - return constant_time_equal(computed->data(), commitment, PAIRING_COMMIT_SIZE); -} - // ============================================================================ // pairing_code_digest // ============================================================================ diff --git a/src/crypto/pairing_code.h b/src/crypto/pairing_code.h index edf7ff6a..992e3b17 100644 --- a/src/crypto/pairing_code.h +++ b/src/crypto/pairing_code.h @@ -95,11 +95,6 @@ std::array pairing_generate_nonce(); std::optional> pairing_code_commit(const uint8_t* nonce, size_t nonce_len); -/// @brief Return true if SHA-256(PAIRING_COMMIT_LABEL || nonce) equals commitment -/// (constant-time) -bool pairing_code_verify_commit(const uint8_t* nonce, size_t nonce_len, const uint8_t* commitment, - size_t commitment_len); - /// @brief Derive the dynamic pairing code's digest from the Noise handshake hash and both nonces. /// /// digest = SHA-256(PAIRING_CODE_DERIVE_LABEL || handshake_hash || nonce_a || nonce_b): the diff --git a/src/esp/ws_server.cpp b/src/esp/ws_server.cpp index 45adf3ce..49d20d66 100644 --- a/src/esp/ws_server.cpp +++ b/src/esp/ws_server.cpp @@ -55,15 +55,13 @@ SendspinWsServer::~SendspinWsServer() { this->stop(); } -bool SendspinWsServer::start(SendspinClient* client, bool task_stack_in_psram, - unsigned task_priority, size_t task_stack_size) { +bool SendspinWsServer::start(bool task_stack_in_psram, unsigned task_priority, + size_t task_stack_size) { if (this->server_ != nullptr) { SS_LOGW(TAG, "Server already started"); return true; } - this->client_ = client; - // Configure the HTTP server httpd_config_t config = HTTPD_DEFAULT_CONFIG(); if (task_stack_in_psram) { diff --git a/src/esp/ws_server.h b/src/esp/ws_server.h index f0b16401..44bf7672 100644 --- a/src/esp/ws_server.h +++ b/src/esp/ws_server.h @@ -34,10 +34,6 @@ namespace sendspin { -// Forward declarations -class SendspinClient; -class SendspinConnection; - /// @brief An accepted httpd session whose WebSocket upgrade has not yet been observed. /// /// The session slot (SendspinWsServer::sessions_) remains the authoritative owner of the @@ -92,14 +88,12 @@ class SendspinWsServer { using WakeCallback = std::function; /// @brief Starts the HTTP server and begins listening for WebSocket connections - /// @param client Pointer to the SendspinClient (used for context in callbacks). /// @param task_stack_in_psram Whether to allocate the HTTP server task stack in PSRAM. /// @param task_priority Priority for the HTTP server task. /// @param task_stack_size HTTP server task stack size in bytes. Clamped up to /// SendspinClientConfig::DEFAULT_HTTPD_STACK_SIZE if lower. /// @return true if server started successfully, false otherwise. - bool start(SendspinClient* client, bool task_stack_in_psram, unsigned task_priority, - size_t task_stack_size); + bool start(bool task_stack_in_psram, unsigned task_priority, size_t task_stack_size); /// @brief Stops the HTTP server void stop(); @@ -244,9 +238,6 @@ class SendspinWsServer { // Pointer fields - /// @brief Stored as the httpd user context for the static callbacks - SendspinClient* client_{nullptr}; - httpd_handle_t server_{nullptr}; // Numeric fields diff --git a/src/host/ws_server.cpp b/src/host/ws_server.cpp index 9f6b20be..38beedee 100644 --- a/src/host/ws_server.cpp +++ b/src/host/ws_server.cpp @@ -46,8 +46,8 @@ SendspinWsServer::~SendspinWsServer() { this->stop(); } -bool SendspinWsServer::start(SendspinClient* client, bool /*task_stack_in_psram*/, - unsigned /*task_priority*/, size_t /*task_stack_size*/) { +bool SendspinWsServer::start(bool /*task_stack_in_psram*/, unsigned /*task_priority*/, + size_t /*task_stack_size*/) { if (this->server_ != nullptr) { SS_LOGW(TAG, "Server already started"); return true; @@ -61,8 +61,6 @@ bool SendspinWsServer::start(SendspinClient* client, bool /*task_stack_in_psram* return false; } - this->client_ = client; - // Create IXWebSocket server on the configured port. max_connections_ is enforced here (IX // closes surplus sockets at accept), so the configured budget is real on host, matching the // ESP build's httpd max_open_sockets. diff --git a/src/host/ws_server.h b/src/host/ws_server.h index e2d91d1c..6081fa5f 100644 --- a/src/host/ws_server.h +++ b/src/host/ws_server.h @@ -30,8 +30,6 @@ namespace sendspin { // Forward declarations -class SendspinClient; -class SendspinConnection; class SendspinServerConnection; /** @@ -67,8 +65,7 @@ class SendspinWsServer { /// @brief Starts the WebSocket server on the configured port; the three task parameters are /// ESP-IDF httpd settings and are ignored here. - bool start(SendspinClient* client, bool task_stack_in_psram, unsigned task_priority, - size_t task_stack_size); + bool start(bool task_stack_in_psram, unsigned task_priority, size_t task_stack_size); /// @brief Stops the WebSocket server and releases its resources void stop(); @@ -129,9 +126,6 @@ class SendspinWsServer { // Pointer fields - /// @brief Stored as the user context for the IX callbacks - SendspinClient* client_{nullptr}; - std::unique_ptr server_; // Numeric fields diff --git a/src/inbound_ring.cpp b/src/inbound_ring.cpp index 4ae1c898..9b5d4d58 100644 --- a/src/inbound_ring.cpp +++ b/src/inbound_ring.cpp @@ -247,7 +247,7 @@ bool InboundGate::wait_until_writable(uint32_t timeout_ms) { } wait_ms = static_cast((remaining_us + US_PER_MS - 1) / US_PER_MS); } - this->consumed_flags_.wait(CONSUMED, false, true, wait_ms); + this->consumed_flags_.wait(CONSUMED, true, wait_ms); } return true; } @@ -315,7 +315,7 @@ void* InboundItemList::take(uint32_t timeout_ms) { // An append between the pop above and this wait has already set ITEMS_APPENDED, so the wait // returns at once rather than missing it. A bit left by an append whose item an earlier pop // took returns here with nothing to pop, which the caller treats as a retry. - this->flags_.wait(ITEMS_APPENDED | WAKE, false, true, timeout_ms); + this->flags_.wait(ITEMS_APPENDED | WAKE, true, timeout_ms); return this->pop(); } diff --git a/src/inbound_ring.h b/src/inbound_ring.h index 4289b2d5..da2d88a0 100644 --- a/src/inbound_ring.h +++ b/src/inbound_ring.h @@ -343,11 +343,6 @@ class InboundRing { bool create(size_t storage_bytes, MemoryLocation location, size_t largest_message_bytes = INBOUND_MAX_MESSAGE_BYTES); - /// @brief Whether create() succeeded - bool is_created() const { - return this->ring_.is_created(); - } - /// @brief The longest received message a transport writes into a ring item: /// max_item_message_bytes() capped at INBOUND_MAX_MESSAGE_BYTES, since a conforming peer's /// WebSocket message is at most one Noise frame. The derivation sizes the ring for the @@ -591,7 +586,7 @@ class InboundItemList { /// only. /// @return The bits among `bits` that were set; 0 on timeout. uint32_t take_signals(uint32_t bits, uint32_t timeout_ms) { - return this->flags_.wait(bits, false, true, timeout_ms) & bits; + return this->flags_.wait(bits, true, timeout_ms) & bits; } /// @brief Clears every bit. Before the consumer thread starts, while the list is empty. @@ -1203,12 +1198,8 @@ static constexpr size_t INBOUND_MIN_AUDIO_FRAME_BYTES = 160; /// Frames per second at INBOUND_MIN_AUDIO_FRAME_BYTES: one every 20 ms, Opus's default frame. static constexpr size_t INBOUND_MIN_AUDIO_FRAMES_PER_SECOND = 50; -/// The lowest audio rate the library budgets for, in encoded bytes per second (64 kbit/s). -static constexpr size_t MIN_ADVERTISED_AUDIO_BYTES_PER_SECOND = - INBOUND_MIN_AUDIO_FRAME_BYTES * INBOUND_MIN_AUDIO_FRAMES_PER_SECOND; - -/// Ring storage per second of audio at MIN_ADVERTISED_AUDIO_BYTES_PER_SECOND: each frame stored -/// as one item with its chunk header and the stored overhead. +/// Ring storage per second of INBOUND_MIN_AUDIO_FRAMES_PER_SECOND frames of +/// INBOUND_MIN_AUDIO_FRAME_BYTES, each stored as one item with its chunk header and overhead. static constexpr size_t INBOUND_MIN_AUDIO_STORED_BYTES_PER_SECOND = (INBOUND_MIN_AUDIO_FRAME_BYTES + INBOUND_AUDIO_CHUNK_HEADER_BYTES + INBOUND_ITEM_STORED_OVERHEAD_BYTES) * diff --git a/src/noise_handshake.cpp b/src/noise_handshake.cpp index 08bc94b9..82e86365 100644 --- a/src/noise_handshake.cpp +++ b/src/noise_handshake.cpp @@ -143,10 +143,10 @@ std::optional run_msg1_core(HandshakeKind kind, const Identity& // psk_id lives inside msg1's encrypted payload, so the PSK is not known yet when the // session is built. KKpsk2 mixes the PSK only into msg2, so msg1 authenticates under the - // static keys alone (KK's "es"/"ss" tokens); build the responder with no PSK bound and - // defer that until it is resolved below (see NoiseSession::set_psk). + // static keys alone (KK's "es"/"ss" tokens); the PSK is bound once it is resolved below + // (see NoiseSession::set_psk). auto session = NoiseSession::as_responder(suite_name, identity.private_bytes.data(), - server_pub->data(), prologue, prologue_len, nullptr); + server_pub->data(), prologue, prologue_len); if (!session.has_value()) { SS_LOGE(TAG, "%s: failed to build session", log_prefix); return std::nullopt; diff --git a/src/noise_session.cpp b/src/noise_session.cpp index 8bfff919..d35630ef 100644 --- a/src/noise_session.cpp +++ b/src/noise_session.cpp @@ -93,7 +93,7 @@ NoiseSession& NoiseSession::operator=(NoiseSession&& other) noexcept { /// Returns nullptr on any error; the caller must free on failure. static NoiseHandshakeState* build_responder_hs(const char* suite_name, const uint8_t* local_priv, const uint8_t* remote_pub, const uint8_t* prologue, - size_t prologue_len, const uint8_t* psk) { + size_t prologue_len) { NoiseHandshakeState* hs = nullptr; const int err = noise_handshakestate_new_by_name(&hs, suite_name, NOISE_ROLE_RESPONDER); if (err != NOISE_ERROR_NONE) { @@ -128,17 +128,6 @@ static NoiseHandshakeState* build_responder_hs(const char* suite_name, const uin } } - // PSK: optional at this point. noise-c allows the PSK to be set any time before the - // "psk" token is processed (KKpsk2 mixes it only in msg2), so a null psk here just - // defers binding to a later NoiseSession::set_psk call. - if (psk) { - if (noise_handshakestate_set_pre_shared_key(hs, psk, NOISE_PSK_SIZE) != NOISE_ERROR_NONE) { - SS_LOGE(TAG, "noise_handshakestate_set_pre_shared_key failed"); - noise_handshakestate_free(hs); - return nullptr; - } - } - if (noise_handshakestate_start(hs) != NOISE_ERROR_NONE) { SS_LOGE(TAG, "noise_handshakestate_start failed"); noise_handshakestate_free(hs); @@ -155,10 +144,10 @@ static NoiseHandshakeState* build_responder_hs(const char* suite_name, const uin std::optional NoiseSession::as_responder(const char* suite_name, const uint8_t* local_priv, const uint8_t* remote_pub, - const uint8_t* prologue, size_t prologue_len, - const uint8_t* psk) { + const uint8_t* prologue, + size_t prologue_len) { NoiseHandshakeState* hs = - build_responder_hs(suite_name, local_priv, remote_pub, prologue, prologue_len, psk); + build_responder_hs(suite_name, local_priv, remote_pub, prologue, prologue_len); if (!hs) { return std::nullopt; } diff --git a/src/noise_session.h b/src/noise_session.h index ea8d9580..d3b422ea 100644 --- a/src/noise_session.h +++ b/src/noise_session.h @@ -56,8 +56,7 @@ using NoiseMsg2 = std::array; /// @brief Noise KKpsk2 session: handshake and transport state. /// /// Construct via the factory `NoiseSession::as_responder()`. -/// Call `read_msg1()`, then `set_psk()` (if the PSK was not supplied at -/// construction), then `write_msg2_and_split()` to complete the handshake. +/// Call `read_msg1()`, then `set_psk()`, then `write_msg2_and_split()` to complete the handshake. /// After split(), use `encrypt()` / `decrypt()` for transport traffic. class NoiseSession { public: @@ -73,25 +72,14 @@ class NoiseSession { // Factory // ======================================== - /// @brief Build a KKpsk2 responder session (the Sendspin client role). - /// - /// The real PSK is only known after `read_msg1` reveals the psk_id carried in its - /// payload, so `psk` may be null here: noise-c permits - /// `noise_handshakestate_set_pre_shared_key` to be called at any point before the "psk" - /// token is processed, which for KKpsk2 happens in msg2. The handshake driver - /// (noise_handshake.cpp run_msg1_core) builds the session with `psk = nullptr`, calls - /// `read_msg1` to expose the psk_id (KK's "es"/"ss" msg1 tokens authenticate against the - /// static keys and do not involve the PSK), resolves the real PSK via the record store, - /// binds it with `set_psk`, and only then calls `write_msg2_and_split`. - /// + /// @brief Build a KKpsk2 responder session (the Sendspin client role) with no PSK; set_psk() + /// binds it before write_msg2_and_split(). /// @param prologue Exact prologue bytes (init messages, or prior hash on re-handshake). - /// @param psk 32-byte PSK, or nullptr to bind it later via `set_psk`. /// @return Session ready for `read_msg1`, or nullopt on error. static std::optional as_responder(const char* suite_name, const uint8_t* local_priv, const uint8_t* remote_pub, - const uint8_t* prologue, size_t prologue_len, - const uint8_t* psk); + const uint8_t* prologue, size_t prologue_len); // ======================================== // Handshake diff --git a/src/outbound_ring.h b/src/outbound_ring.h index 566928b8..cdfa6c98 100644 --- a/src/outbound_ring.h +++ b/src/outbound_ring.h @@ -138,11 +138,6 @@ class OutboundRing { /// @return false when the storage cannot be allocated or the size is refused. bool create(size_t storage_bytes, MemoryLocation location); - /// @brief Whether create() succeeded - bool is_created() const { - return this->ring_.is_created(); - } - /// @brief The largest message capacity an acquire() can succeed for: what an item of the /// ring's largest size (SharedRingLayout::max_item_size(), half its storage) holds after its /// header. Written by create(); read by any thread after it. diff --git a/src/platform/crypto.h b/src/platform/crypto.h index 1f814b85..70b00291 100644 --- a/src/platform/crypto.h +++ b/src/platform/crypto.h @@ -27,9 +27,6 @@ #include #include #include -#include -#include -#include // noise-c is a C library; wrap the includes in extern "C" to avoid C++ // name-mangling issues when compiling under -Wpedantic. @@ -46,7 +43,7 @@ namespace sendspin { /// @brief Number of bytes in a SHA-256 digest. static constexpr size_t SHA256_DIGEST_SIZE = 32; -/// @brief Streaming SHA-256. For one or two buffers, use the sha256_oneshot() overloads below. +/// @brief Streaming SHA-256. class Sha256 { public: Sha256() { @@ -110,25 +107,6 @@ class Sha256 { bool failed_{false}; }; -/// @brief Compute SHA-256(data, len). -inline std::array sha256_oneshot(const uint8_t* data, size_t len) { - Sha256 h; - h.update(data, len); - return h.finalize(); -} - -/// @brief Compute SHA-256(prefix, prefix_len || suffix, suffix_len). -/// Used for psk_id derivation: SHA-256(PSK_ID_LABEL || psk). -inline std::array sha256_oneshot(const uint8_t* prefix, - size_t prefix_len, - const uint8_t* suffix, - size_t suffix_len) { - Sha256 h; - h.update(prefix, prefix_len); - h.update(suffix, suffix_len); - return h.finalize(); -} - // ============================================================================ // SHA-512 // ============================================================================ @@ -393,13 +371,6 @@ std::array hmac_sha512_streamed(const uint8_t* key, return mac; } -/// @brief Compute HMAC-SHA-512(key, data); see hmac_sha512_streamed(). -inline std::array hmac_sha512(const uint8_t* key, size_t key_len, - const uint8_t* data, size_t data_len) { - return hmac_sha512_streamed(key, key_len, - [data, data_len](Sha512& inner) { inner.update(data, data_len); }); -} - // ============================================================================ // CSPRNG // ============================================================================ @@ -474,11 +445,8 @@ class DhState { /// (ChaChaPoly uses a 16-byte tag). static constexpr size_t AEAD_TAG_SIZE = 16; -/// @brief Number of bytes in the fixed nonce used by aead_oneshot_encrypt/decrypt. -static constexpr size_t AEAD_ONESHOT_NONCE_SIZE = 12; - /// @brief Map a full Noise suite name (e.g. "Noise_KKpsk2_25519_ChaChaPoly_SHA256") to the -/// noise-c cipher name ("ChaChaPoly") for use with aead_oneshot_encrypt/decrypt. The client only +/// noise-c cipher name ("ChaChaPoly") for use with aead_oneshot_encrypt(). The client only /// ever negotiates ChaChaPoly, so this validates the suite string rather than selecting between /// alternatives. Returns nullptr if the suite name does not contain the expected cipher /// component. @@ -528,41 +496,6 @@ inline bool aead_oneshot_encrypt(const char* cipher_name, const uint8_t* key, si return sealed; } -/// @brief Decrypt `ciphertext` (ciphertext || tag) with the named AEAD cipher, key `key`, an -/// all-zero 12-byte nonce, and empty associated data. Returns the plaintext, or nullopt on any -/// cipher-allocation failure or AEAD authentication failure (wrong key or corrupted input). -inline std::optional> aead_oneshot_decrypt(const char* cipher_name, - const uint8_t* key, size_t key_len, - const uint8_t* ciphertext, - size_t ciphertext_len) { - NoiseCipherState* cipher = nullptr; - int err = noise_cipherstate_new_by_name(&cipher, cipher_name); - if (err != NOISE_ERROR_NONE || cipher == nullptr) { - return std::nullopt; - } - err = noise_cipherstate_init_key(cipher, key, key_len); - if (err != NOISE_ERROR_NONE) { - noise_cipherstate_free(cipher); - return std::nullopt; - } - err = noise_cipherstate_set_nonce(cipher, 0); - if (err != NOISE_ERROR_NONE) { - noise_cipherstate_free(cipher); - return std::nullopt; - } - - std::vector buf(ciphertext, ciphertext + ciphertext_len); - NoiseBuffer nbuf; - noise_buffer_set_inout(nbuf, buf.data(), buf.size(), buf.size()); - err = noise_cipherstate_decrypt_with_ad(cipher, nullptr, 0, &nbuf); - noise_cipherstate_free(cipher); - if (err != NOISE_ERROR_NONE) { - return std::nullopt; - } - buf.resize(nbuf.size); - return buf; -} - // ============================================================================ // Constant-time comparison // ============================================================================ diff --git a/src/platform/event_flags.h b/src/platform/event_flags.h index 8e9574d1..773c81e4 100644 --- a/src/platform/event_flags.h +++ b/src/platform/event_flags.h @@ -33,7 +33,7 @@ namespace sendspin { * @brief Bit-flag group that supports blocking waits on one or more bits * * Backed by a FreeRTOS event group on ESP and a mutex/condition-variable pair on host. - * Threads can block until any or all of a set of bits are set, with an optional timeout. + * Threads can block until any of a set of bits is set, with an optional timeout. * Call create() before any other method. * * Usage: @@ -50,7 +50,7 @@ namespace sendspin { * flags.set(0x01); * * // In another thread: - * uint32_t bits = flags.wait(0x01, false, true, 1000); + * uint32_t bits = flags.wait(0x01, true, 1000); * @endcode */ class EventFlags { @@ -108,15 +108,14 @@ class EventFlags { return xEventGroupGetBits(this->handle_); } - /// @brief Waits for bits to be set + /// @brief Waits for any of the given bits to be set /// @param bits_to_wait Bitmask of bits to wait for. - /// @param wait_all If true, wait for ALL bits; if false, wait for ANY bit. /// @param clear_on_exit If true, clear the waited bits before returning. /// @param timeout_ms Milliseconds to wait (UINT32_MAX = wait forever). /// @return The bit pattern at the time the wait completed or timed out. - uint32_t wait(uint32_t bits_to_wait, bool wait_all, bool clear_on_exit, uint32_t timeout_ms) { + uint32_t wait(uint32_t bits_to_wait, bool clear_on_exit, uint32_t timeout_ms) { return xEventGroupWaitBits(this->handle_, bits_to_wait, clear_on_exit ? pdTRUE : pdFALSE, - wait_all ? pdTRUE : pdFALSE, platform_ms_to_ticks(timeout_ms)); + pdFALSE, platform_ms_to_ticks(timeout_ms)); } private: @@ -145,9 +144,8 @@ namespace sendspin { /** * @brief Bit-flag group that supports blocking waits on one or more bits * - * Backed by a mutex/condition-variable pair on host. Threads can block until any or - * all of a set of bits are set, with an optional timeout. Call create() before any - * other method. + * Backed by a mutex/condition-variable pair on host. Threads can block until any of a set + * of bits is set, with an optional timeout. Call create() before any other method. * * Usage: * 1. Declare an EventFlags member and call create() during initialization @@ -163,7 +161,7 @@ namespace sendspin { * flags.set(0x01); * * // In another thread: - * uint32_t bits = flags.wait(0x01, false, true, 1000); + * uint32_t bits = flags.wait(0x01, true, 1000); * @endcode */ class EventFlags { @@ -224,21 +222,15 @@ class EventFlags { return this->bits_; } - /// @brief Waits for bits to be set + /// @brief Waits for any of the given bits to be set /// @param bits_to_wait Bitmask of bits to wait for. - /// @param wait_all If true, wait for ALL bits; if false, wait for ANY bit. /// @param clear_on_exit If true, clear the waited bits before returning. /// @param timeout_ms Milliseconds to wait (UINT32_MAX = wait forever). /// @return The bit pattern at the time the wait completed or timed out. - uint32_t wait(uint32_t bits_to_wait, bool wait_all, bool clear_on_exit, uint32_t timeout_ms) { + uint32_t wait(uint32_t bits_to_wait, bool clear_on_exit, uint32_t timeout_ms) { std::unique_lock lock(this->mtx_); - auto pred = [&]() -> bool { - if (wait_all) { - return (this->bits_ & bits_to_wait) == bits_to_wait; - } - return (this->bits_ & bits_to_wait) != 0; - }; + auto pred = [&]() -> bool { return (this->bits_ & bits_to_wait) != 0; }; if (!pred()) { if (timeout_ms == 0) { diff --git a/src/platform/memory.h b/src/platform/memory.h index 0f760d8b..ca58eec7 100644 --- a/src/platform/memory.h +++ b/src/platform/memory.h @@ -169,11 +169,6 @@ class PlatformBuffer { return true; } - /// @brief Returns the location preference last passed to allocate() - MemoryLocation location() const { - return this->location_; - } - /// @brief Frees the held memory void reset() { if (this->ptr_ != nullptr) { diff --git a/src/platform/types.h b/src/platform/types.h index 9e1eca9d..a0b63cfc 100644 --- a/src/platform/types.h +++ b/src/platform/types.h @@ -32,12 +32,7 @@ enum class SsErr : int16_t { // Named error codes (> 0, mirrors esp_err_t values) NO_MEM = 0x101, // Out of memory - INVALID_ARG = 0x102, // Invalid argument INVALID_STATE = 0x103, // Invalid state for the operation - INVALID_SIZE = 0x104, // Invalid size - NOT_FOUND = 0x105, // Resource not found - NOT_SUPPORTED = 0x106, // Operation not supported - TIMEOUT = 0x107, // Operation timed out // Errors (< 0) FAIL = -1, // Generic failure diff --git a/src/protocol.cpp b/src/protocol.cpp index b81bf299..41362c30 100644 --- a/src/protocol.cpp +++ b/src/protocol.cpp @@ -195,22 +195,12 @@ static bool decode_flac_codec_header(std::string_view encoded, FlacCodecHeader* } static bool process_player_stream_object(const JsonObject player_object, - PlayerStreamPayload* player, bool require_all_fields) { + PlayerStreamPayload* player) { if (player == nullptr) { return false; } PlayerStreamParams* player_obj = &player->params; - if (require_all_fields) { - if (!player_object["bit_depth"].is() || - !player_object["channels"].is() || - !player_object["sample_rate"].is() || - !player_object["codec"].is()) { - SS_LOGE(TAG, "Invalid player object: missing required fields"); - return false; - } - } - if (player_object["codec"].is()) { auto codec = codec_format_from_string(player_object["codec"].as()); player_obj->codec = codec.value_or(SendspinCodecFormat::UNSUPPORTED); @@ -886,7 +876,7 @@ static bool process_stream_start_player(JsonObject payload, return true; } PlayerStreamPayload& player_obj = player->emplace(); - if (!process_player_stream_object(payload["player"], &player_obj, true)) { + if (!process_player_stream_object(payload["player"], &player_obj)) { return false; } if (!player_obj.params.is_complete()) { diff --git a/src/protocol_task.cpp b/src/protocol_task.cpp index 5536cb60..8f9b9c7e 100644 --- a/src/protocol_task.cpp +++ b/src/protocol_task.cpp @@ -102,7 +102,7 @@ void ProtocolTask::thread_entry(ProtocolTask* self) { const uint32_t next_deadline_ms = self->tick_(); // NO_DEADLINE is UINT32_MAX, which EventFlags::wait() takes as no timeout. const uint32_t bits = - self->event_flags_.wait(COMMAND_STOP | WORK_PENDING, false, true, next_deadline_ms); + self->event_flags_.wait(COMMAND_STOP | WORK_PENDING, true, next_deadline_ms); if ((bits & COMMAND_STOP) != 0) { // One final tick, so the work queued and posted before stop() was called is seen by // the task. diff --git a/src/source_task.cpp b/src/source_task.cpp index 91f4a689..6b577c5d 100644 --- a/src/source_task.cpp +++ b/src/source_task.cpp @@ -160,7 +160,7 @@ bool SourceTask::start(ProtocolTask* protocol_task) { config.psram_stack); this->task_thread_ = std::thread(thread_entry, this); this->event_flags_.wait(SourceTaskBits::SOURCE_TASK_IDLE | SourceTaskBits::SOURCE_TASK_STOPPED, - false, false, UINT32_MAX); + false, UINT32_MAX); return true; } diff --git a/src/sync_task.cpp b/src/sync_task.cpp index 8e91d2b2..64a3da1b 100644 --- a/src/sync_task.cpp +++ b/src/sync_task.cpp @@ -201,7 +201,7 @@ bool SyncTask::start(InboundRing* ring, bool task_stack_in_psram, unsigned prior this->sync_thread_ = std::thread(thread_entry, this); // Wait for the thread to reach IDLE before returning - this->event_flags_.wait(EventGroupBits::TASK_IDLE | EventGroupBits::TASK_STOPPED, false, false, + this->event_flags_.wait(EventGroupBits::TASK_IDLE | EventGroupBits::TASK_STOPPED, false, UINT32_MAX); return true; @@ -903,8 +903,7 @@ bool SyncTask::wait_for_start_acknowledgement(SyncContext& sync_context) { // reads idle, and this task never ran it, so note idle for it again. this->player_impl_->note_sync_idle(); } - this->event_flags_.wait(EventGroupBits::COMMAND_START | LEAVE_BITS, false, false, - UINT32_MAX); + this->event_flags_.wait(EventGroupBits::COMMAND_START | LEAVE_BITS, false, UINT32_MAX); } } diff --git a/src/time_filter.cpp b/src/time_filter.cpp index 19fd2a40..b0b605d2 100644 --- a/src/time_filter.cpp +++ b/src/time_filter.cpp @@ -20,21 +20,31 @@ namespace sendspin { -// ============================================================================ -// Lifecycle -// ============================================================================ +/// Offset random-walk variance per us of elapsed time (diffusion coefficient squared), modeling +/// clock jitter. +static constexpr double PROCESS_VARIANCE = 0.0; + +/// Drift random-walk variance per us of elapsed time, modeling frequency wander: the square of a +/// 1e-11 / sqrt(us) diffusion coefficient. +static constexpr double DRIFT_PROCESS_VARIANCE = 1e-11 * 1e-11; + +/// Factor applied to the covariances when a large residual is detected: the square of a forgetting +/// factor of 2. Higher values recover faster from disruptions but reduce stability. +static constexpr double FORGET_VARIANCE_FACTOR = 2.0 * 2.0; -SendspinTimeFilter::SendspinTimeFilter() : SendspinTimeFilter(Config{}) {} +/// Multiple of max_error a residual must exceed to trigger adaptive forgetting. +static constexpr double ADAPTIVE_CUTOFF = 3.0; -SendspinTimeFilter::SendspinTimeFilter(const Config& config) - : adaptive_forgetting_cutoff(config.adaptive_cutoff), - drift_process_variance(config.drift_process_std_dev * config.drift_process_std_dev), - drift_significance_threshold_squared(config.drift_significance_threshold * - config.drift_significance_threshold), - forget_variance_factor(config.forget_factor * config.forget_factor), - max_error_scale(config.max_error_scale), - process_variance(config.process_std_dev * config.process_std_dev), - min_samples_for_forgetting(config.min_samples) {} +/// Measurements taken before adaptive forgetting is enabled. +static constexpr uint8_t MIN_SAMPLES_FOR_FORGETTING = 100U; + +/// Drift compensation applies only when drift^2 > this * drift_covariance: the square of an SNR +/// threshold of 2. +static constexpr double DRIFT_SIGNIFICANCE_THRESHOLD_SQUARED = 2.0 * 2.0; + +/// Scale applied to max_error to give the measurement standard deviation; below 1 because the +/// round-trip half-delay overestimates the true measurement noise. +static constexpr double MAX_ERROR_SCALE = 0.5; // ============================================================================ // Core API @@ -51,7 +61,7 @@ void SendspinTimeFilter::update(int64_t measurement, int64_t max_error, int64_t const double dt_squared = dt * dt; this->last_update_ = time_added; - const double update_std_dev = max_error * this->max_error_scale; + const double update_std_dev = max_error * MAX_ERROR_SCALE; const double measurement_variance = update_std_dev * update_std_dev; // Filter initialization: First measurement establishes offset baseline @@ -88,30 +98,30 @@ void SendspinTimeFilter::update(int64_t measurement, int64_t max_error, int64_t // Process noise for both offset and drift (full random walk model) // We assume clock jitter (offset noise) and wander (drift noise) are independent processes - const double drift_process_variance_dt = dt * this->drift_process_variance; + const double drift_process_variance_dt = dt * DRIFT_PROCESS_VARIANCE; double new_drift_covariance = this->drift_covariance_ + drift_process_variance_dt; double new_offset_drift_covariance = this->offset_drift_covariance_ + this->drift_covariance_ * dt; - const double offset_process_variance = dt * this->process_variance; + const double offset_process_variance = dt * PROCESS_VARIANCE; double new_offset_covariance = this->offset_covariance_ + 2 * this->offset_drift_covariance_ * dt + this->drift_covariance_ * dt_squared + offset_process_variance; /*** Innovation and Adaptive Forgetting ***/ const double residual = measurement - offset; // Innovation: y_k = z_k - H * x_k|k-1 - const double max_residual_cutoff = max_error * this->adaptive_forgetting_cutoff; + const double max_residual_cutoff = max_error * ADAPTIVE_CUTOFF; - if (this->count_ < this->min_samples_for_forgetting) { + if (this->count_ < MIN_SAMPLES_FOR_FORGETTING) { // Build sufficient history before enabling adaptive forgetting ++this->count_; } else if (std::abs(residual) > max_residual_cutoff) { // Large prediction error detected - likely network disruption or clock adjustment // Apply forgetting factor to increase Kalman gain and accelerate convergence - new_drift_covariance *= this->forget_variance_factor; - new_offset_drift_covariance *= this->forget_variance_factor; - new_offset_covariance *= this->forget_variance_factor; + new_drift_covariance *= FORGET_VARIANCE_FACTOR; + new_offset_drift_covariance *= FORGET_VARIANCE_FACTOR; + new_offset_covariance *= FORGET_VARIANCE_FACTOR; } /*** Kalman Update Step ***/ @@ -137,7 +147,7 @@ void SendspinTimeFilter::update(int64_t measurement, int64_t max_error, int64_t // Only apply drift compensation if statistically significant (SNR check) const double drift_squared = this->drift_ * this->drift_; this->use_drift_ = - drift_squared > this->drift_significance_threshold_squared * this->drift_covariance_; + drift_squared > DRIFT_SIGNIFICANCE_THRESHOLD_SQUARED * this->drift_covariance_; } int64_t SendspinTimeFilter::compute_server_time(int64_t client_time) const { @@ -163,10 +173,6 @@ void SendspinTimeFilter::reset() { // Accessors // ============================================================================ -int64_t SendspinTimeFilter::get_covariance() const { - return std::round(this->offset_covariance_); -} - int64_t SendspinTimeFilter::get_error() const { return std::round(sqrt(this->offset_covariance_)); } diff --git a/src/time_filter.h b/src/time_filter.h index abdbff66..78c63542 100644 --- a/src/time_filter.h +++ b/src/time_filter.h @@ -62,46 +62,6 @@ struct TimeTransform { /// other threads read its transform(). class SendspinTimeFilter { public: - /// @brief Configuration parameters for the time synchronization filter. - struct Config { - /// Diffusion coefficient for offset random walk, in µs / sqrt(µs), modeling clock jitter. - /// Offset variance grows by process_std_dev² * dt per µs of elapsed time. - double process_std_dev = 0.0; - /// Diffusion coefficient for drift random walk, in 1 / sqrt(µs), modeling frequency wander. - /// Drift is dimensionless (µs of offset per µs of time), so its variance grows by - /// drift_process_std_dev² * dt per µs of elapsed time. - double drift_process_std_dev = 1e-11; - /// Forgetting factor (>1) applied to covariances when large residuals are detected. - /// Higher values enable faster recovery from disruptions but may reduce stability. - double forget_factor = 2.0; - /// Multiple of max_error that triggers adaptive forgetting. - /// When residual > adaptive_cutoff * max_error, forgetting is applied; values > 1 require - /// larger residuals. - double adaptive_cutoff = 3.0; - /// Minimum number of samples before adaptive forgetting is enabled. - /// Building sufficient history before enabling forgetting improves stability. - uint8_t min_samples = 100U; // NOLINT(readability-magic-numbers) - /// SNR threshold for applying drift compensation in time conversions. - /// Drift is only used when drift² > threshold² * drift_covariance, ensuring - /// the drift estimate is statistically significant before applying corrections. - double drift_significance_threshold = 2.0; - /// Scale factor applied to max_error before it is used as the measurement standard - /// deviation. Values < 1 indicate the round-trip half-delay overestimates true measurement - /// noise. - double max_error_scale = 0.5; - }; - - // ======================================== - // Lifecycle - // ======================================== - - /// @brief Constructs a Kalman filter for time synchronization. - /// - /// @param config Filter configuration parameters. See Config for field documentation and - /// defaults. - explicit SendspinTimeFilter(const Config& config); - SendspinTimeFilter(); - // ======================================== // Core API // ======================================== @@ -149,14 +109,6 @@ class SendspinTimeFilter { // Accessors // ======================================== - /// @brief Returns the offset variance in microseconds squared. - /// - /// Provides the raw variance value from the Kalman filter's covariance matrix. This represents - /// the statistical uncertainty in the offset estimate. - /// - /// @return Variance of the offset estimate in microseconds squared. - int64_t get_covariance() const; - /// @brief Returns the estimated standard deviation of the offset in microseconds. /// /// Provides a measure of the current synchronization accuracy by computing the square root of @@ -179,22 +131,15 @@ class SendspinTimeFilter { // ======================================== // 64-bit fields - const double adaptive_forgetting_cutoff; double drift_{0.0}; double drift_covariance_{0.0}; - const double drift_process_variance; - const double drift_significance_threshold_squared; - const double forget_variance_factor; int64_t last_update_{0}; - const double max_error_scale; double offset_{0.0}; double offset_covariance_{std::numeric_limits::infinity()}; double offset_drift_covariance_{0.0}; - const double process_variance; // 8-bit fields uint8_t count_{0}; - const uint8_t min_samples_for_forgetting; bool use_drift_{false}; }; diff --git a/tests/crypto_test_helpers.h b/tests/crypto_test_helpers.h new file mode 100644 index 00000000..a16a086a --- /dev/null +++ b/tests/crypto_test_helpers.h @@ -0,0 +1,35 @@ +// Copyright 2026 Sendspin Contributors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +/// @file crypto_test_helpers.h +/// @brief A one-buffer wrapper over the library's streamed HMAC-SHA-512, for the KATs. + +#pragma once + +#include "platform/crypto.h" + +#include +#include +#include + +namespace sendspin { + +/// Compute HMAC-SHA-512(key, data) through hmac_sha512_streamed(). +inline std::array hmac_sha512(const uint8_t* key, size_t key_len, + const uint8_t* data, size_t data_len) { + return hmac_sha512_streamed(key, key_len, + [data, data_len](Sha512& inner) { inner.update(data, data_len); }); +} + +} // namespace sendspin diff --git a/tests/record_test_helpers.h b/tests/record_test_helpers.h index e8905b99..7debcb7c 100644 --- a/tests/record_test_helpers.h +++ b/tests/record_test_helpers.h @@ -65,7 +65,9 @@ inline std::array make_random_psk() { /// server_id form a record can be stored under. Deterministic, so a test can spell the same /// server twice. inline std::string test_peer_id(const std::string& name) { - auto key = sha256_oneshot(reinterpret_cast(name.data()), name.size()); + Sha256 hash; + hash.update(reinterpret_cast(name.data()), name.size()); + auto key = hash.finalize(); return b64url_encode(key.data(), key.size()); } diff --git a/tests/test_cpace.cpp b/tests/test_cpace.cpp index f0adc797..5a1d058b 100644 --- a/tests/test_cpace.cpp +++ b/tests/test_cpace.cpp @@ -20,6 +20,7 @@ // except CPaceDraft21Vectors, which come from the spec itself. #include "crypto/cpace.h" +#include "crypto_test_helpers.h" #include "test_util.h" #include "field25519.h" #include "platform/crypto.h" diff --git a/tests/test_crypto.cpp b/tests/test_crypto.cpp index 6c43aa6a..de2d6358 100644 --- a/tests/test_crypto.cpp +++ b/tests/test_crypto.cpp @@ -20,6 +20,7 @@ // aiosendspin/tests/noise/test_keys.py #include "crypto/constants.h" +#include "crypto_test_helpers.h" #include "test_util.h" #include "crypto/keys.h" #include "platform/base64.h" @@ -133,8 +134,8 @@ TEST(HmacSha512, Rfc4231Case2) { "9758bf75c05a994a6d034f65f8f0e6fdcaeab1a34d4a6b4b636e070a38bce737"); } -// The long-key branch (key_len > 128 is hashed down to 64 bytes first). Currently dead in -// production - CPace's mac_key is 64 bytes - but hmac_sha512() claims generic HMAC. +// The long-key branch (key_len > 128 is hashed down to 64 bytes first). Dead in production, where +// CPace's mac_key is 64 bytes, but hmac_sha512_streamed() claims generic HMAC. TEST(HmacSha512, Rfc4231Case6) { std::vector key(131, 0xaa); const char* data = "Test Using Larger Than Block-Size Key - Hash Key First"; @@ -159,7 +160,7 @@ TEST(HmacSha512, BlockSizeKeyIsUsedWithoutHashing) { } // ============================================================================ -// SHA-256 (Sha256 class / sha256_oneshot) KATs +// SHA-256 (Sha256 class) KATs // // noise-c's SHA256 backend has no test hook to force an allocation/finalize failure, so the // failure branch inside Sha256::ok() cannot be exercised here; the callers that must surface it @@ -168,14 +169,11 @@ TEST(HmacSha512, BlockSizeKeyIsUsedWithoutHashing) { // ============================================================================ TEST(Sha256, KatAbc) { - // NIST FIPS 180-4 SHA-256("abc"), via both the one-shot helper and the streaming class. + // NIST FIPS 180-4 SHA-256("abc"). const char* m = "abc"; const std::string expected = "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"; - auto d = sha256_oneshot(reinterpret_cast(m), std::strlen(m)); - EXPECT_EQ(to_hex(d), expected); - Sha256 h; h.update(reinterpret_cast(m), std::strlen(m)); EXPECT_EQ(to_hex(h.finalize()), expected); diff --git a/tests/test_pairing_code.cpp b/tests/test_pairing_code.cpp index a165259c..83e443ad 100644 --- a/tests/test_pairing_code.cpp +++ b/tests/test_pairing_code.cpp @@ -63,34 +63,10 @@ std::optional> digest_of(const DeriveInputs& in) { } // namespace // ============================================================================ -// pairing_code_commit / pairing_code_verify_commit +// pairing_code_commit // ============================================================================ -TEST(PairingCodeCommit, RoundTripSucceeds) { - auto nonce = pairing_generate_nonce(); - auto commitment = pairing_code_commit(nonce.data(), nonce.size()); - ASSERT_TRUE(commitment.has_value()); - EXPECT_TRUE(pairing_code_verify_commit(nonce.data(), nonce.size(), commitment->data(), - commitment->size())); -} - -TEST(PairingCodeCommit, WrongNonceFailsVerify) { - auto nonce = pairing_generate_nonce(); - auto commitment = pairing_code_commit(nonce.data(), nonce.size()); - ASSERT_TRUE(commitment.has_value()); - nonce[0] ^= 0xFF; - EXPECT_FALSE(pairing_code_verify_commit(nonce.data(), nonce.size(), commitment->data(), - commitment->size())); -} - -// The commit/verify length guards. pairing_code_commit() and pairing_code_verify_commit() are -// one family: a commitment is only ever checked against the nonce that produced it, so both -// lengths are guarded on both sides. -TEST(PairingCodeCommit, LengthGuardsRejectWrongSizedArguments) { - const auto nonce = pairing_generate_nonce(); - const auto commitment = pairing_code_commit(nonce.data(), nonce.size()); - ASSERT_TRUE(commitment.has_value()); - +TEST(PairingCodeCommit, LengthGuardRejectsWrongSizedNonce) { struct CommitRow { const char* name; size_t nonce_len; @@ -108,29 +84,6 @@ TEST(PairingCodeCommit, LengthGuardsRejectWrongSizedArguments) { SCOPED_TRACE(row.name); EXPECT_EQ(pairing_code_commit(spare.data(), row.nonce_len).has_value(), row.expect_ok); } - - // The verify rows pin the composed contract, not one line: the nonce clause cannot be seen on - // its own from here, since pairing_code_commit() rejects the same length and the call would - // return false without it. - struct VerifyRow { - const char* name; - size_t nonce_len; - size_t commitment_len; - bool expect_ok; - }; - const VerifyRow verify_rows[] = { - {"verify/short-commitment", PAIRING_NONCE_SIZE, 16, false}, - {"verify/short-nonce", 16, PAIRING_COMMIT_SIZE, false}, - {"verify/both-short", 16, 16, false}, - // Control: both arguments at their defined lengths verify. - {"verify/both-defined-lengths", PAIRING_NONCE_SIZE, PAIRING_COMMIT_SIZE, true}, - }; - for (const VerifyRow& row : verify_rows) { - SCOPED_TRACE(row.name); - EXPECT_EQ(pairing_code_verify_commit(nonce.data(), row.nonce_len, commitment->data(), - row.commitment_len), - row.expect_ok); - } } TEST(PairingCodeCommit, Kat) { diff --git a/tests/test_pairing_state_machine.cpp b/tests/test_pairing_state_machine.cpp index 66cba5be..5031606d 100644 --- a/tests/test_pairing_state_machine.cpp +++ b/tests/test_pairing_state_machine.cpp @@ -58,6 +58,7 @@ #include #include +#include #include #include #include @@ -88,7 +89,11 @@ namespace { /// so this harness's needs can diverge without disturbing that file's fixture. class FakeConnection : public SendspinConnection { public: - FakeConnection() = default; + /// The suite name init_noise_handshake() would record, so the wrapping (pairing.md + /// "Wrapping") resolves an AEAD cipher without an active Noise session. + FakeConnection() { + this->noise_suite_name_ = "Noise_KKpsk2_25519_ChaChaPoly_SHA256"; + } ~FakeConnection() override = default; // Interface stubs @@ -122,12 +127,6 @@ class FakeConnection : public SendspinConnection { return this->canned_hash_; } - /// Report a canned Noise suite name without an active Noise session, so the wrapping - /// (pairing.md "Wrapping") can resolve an AEAD cipher during the PAIR_CONFIRM step. - const char* get_noise_suite_name() const override { - return this->canned_suite_name_.c_str(); - } - // Accumulated outgoing messages / disconnect bookkeeping std::vector sent_text_; @@ -138,7 +137,6 @@ class FakeConnection : public SendspinConnection { private: std::optional> canned_hash_{std::array{}}; - std::string canned_suite_name_{"Noise_KKpsk2_25519_ChaChaPoly_SHA256"}; bool connected_{true}; }; @@ -960,8 +958,10 @@ class PairingStateMachineTest : public ::testing::Test { auto nonce_b = unwrap_value_as_server(NONCE_WRAP_LABEL, "ChaChaPoly", server.initiator.sid(), server.initiator.isk().value(), wrapped); ASSERT_TRUE(nonce_b.has_value()) << "server-side unwrap of wrapped_nonce_B failed"; - EXPECT_TRUE(pairing_code_verify_commit(nonce_b->data(), nonce_b->size(), commit_b->data(), - commit_b->size())) + auto reopened = pairing_code_commit(nonce_b->data(), nonce_b->size()); + ASSERT_TRUE(reopened.has_value()); + EXPECT_TRUE(std::equal(reopened->begin(), reopened->end(), commit_b->begin(), + commit_b->end())) << "the revealed nonce does not open the commitment sent in client/pair-init"; } diff --git a/tests/wrap_test_helpers.h b/tests/wrap_test_helpers.h index 9281472c..600ade59 100644 --- a/tests/wrap_test_helpers.h +++ b/tests/wrap_test_helpers.h @@ -27,6 +27,7 @@ #include "platform/crypto.h" #include +#include #include #include #include @@ -34,6 +35,33 @@ #include #include +/// @brief Decrypts `ciphertext` (ciphertext || tag) with the named AEAD cipher, an all-zero +/// nonce and empty associated data: the inverse of sendspin::aead_oneshot_encrypt(). +/// @return The plaintext, or nullopt on a cipher-allocation or authentication failure. +inline std::optional> aead_oneshot_decrypt(const char* cipher_name, + const uint8_t* key, size_t key_len, + const uint8_t* ciphertext, + size_t ciphertext_len) { + NoiseCipherState* cipher = nullptr; + if (noise_cipherstate_new_by_name(&cipher, cipher_name) != NOISE_ERROR_NONE || + cipher == nullptr) { + return std::nullopt; + } + std::vector buf(ciphertext, ciphertext + ciphertext_len); + NoiseBuffer nbuf; + noise_buffer_set_inout(nbuf, buf.data(), buf.size(), buf.size()); + const bool opened = noise_cipherstate_init_key(cipher, key, key_len) == NOISE_ERROR_NONE && + noise_cipherstate_set_nonce(cipher, 0) == NOISE_ERROR_NONE && + noise_cipherstate_decrypt_with_ad(cipher, nullptr, 0, &nbuf) == + NOISE_ERROR_NONE; + noise_cipherstate_free(cipher); + if (!opened) { + return std::nullopt; + } + buf.resize(nbuf.size); + return buf; +} + /// @brief Opens a field sealed by sendspin::wrap_value(), as the server does. /// @param label Per-field wrap label (PSK_WRAP_LABEL or NONCE_WRAP_LABEL). /// @param cipher_name Noise-c cipher name for the connection's negotiated suite. @@ -49,8 +77,8 @@ inline std::optional> unwrap_value_as_server( if (!k_wrap.has_value()) { return std::nullopt; } - auto pt = sendspin::aead_oneshot_decrypt(cipher_name, k_wrap->data(), k_wrap->size(), - wrapped.data(), wrapped.size()); + auto pt = aead_oneshot_decrypt(cipher_name, k_wrap->data(), k_wrap->size(), wrapped.data(), + wrapped.size()); sendspin::secure_zero_container(k_wrap.value()); if (!pt.has_value() || pt->size() != 32) { return std::nullopt;