Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/conventions.md
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ checklists in `.claude/skills/` apply these standards to a diff.
call back into the client. See "Re-entrant Teardown During Callback
Dispatch" in `docs/internals.md` for the guard patterns in use.
- A message handler on the protocol task does the connection work the message
calls for in place (an activation's trust check, admission and role
calls for in place (an activation's admissibility check, admission and role
ownership, a pairing step, a `noise/handshake` re-handshake, the RAM commit
of a pairing record), and hands role and consumer work on through Inbox
slots, role item lists and buffers. It never calls a listener or a
Expand Down
4 changes: 2 additions & 2 deletions docs/internals.md
Original file line number Diff line number Diff line change
Expand Up @@ -277,7 +277,7 @@ Role-bound traffic reaches a role only from the admitted connection that owns it
| Message | Action on the protocol task |
|---------|------------------------------|
| `server/hello` | Records server info and the codecs its source@v1 support object lists on the connection, and sets `server_hello_received_` |
| `server/activate` | `ConnectionManager::on_server_activate()`: trust and pairing-method checks, what the roles owed until the activation (`SendspinClient::on_activation_applied()`), role ownership and removals, and admission of a nursery connection the activation makes operational |
| `server/activate` | `ConnectionManager::on_server_activate()`: admissibility and pairing-method checks, what the roles owed until the activation (`SendspinClient::on_activation_applied()`), role ownership and removals, and admission of a nursery connection the activation makes operational |
| `server/time` | Claims the connection's `client/time` frame in flight, dropping a reply that answers none, and feeds the measurement to the connection's own time burst |
| `server/state` | Writes the controller, metadata, and color `InboxSlot`s |
| `server/command` | Merges the player object into the player's `command_slot`; the source object starts or ends the input stream (see [Source Stream Start and End](#source-stream-start-and-end)) |
Expand Down Expand Up @@ -389,7 +389,7 @@ Every role this client drives has at most one owner among the admitted connectio

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

Expand Down
4 changes: 2 additions & 2 deletions src/admission.h
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
// limitations under the License.

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

// ============================================================================
// Trust enforcement (PSK category -> allowed activities)
// Admissibility (PSK category -> allowed activities)
// ============================================================================

/// @brief Whether an activity set is allowed for the matched PSK category.
Expand Down
4 changes: 2 additions & 2 deletions src/client_dispatch.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -528,7 +528,7 @@ void SendspinClient::process_json_message(SendspinConnection& connection, const
SS_LOGD(TAG, "server/activate received (playback=%d, pairing=%d)",
activate_msg.activities.contains(SendspinActivity::PLAYBACK),
activate_msg.activities.contains(SendspinActivity::PAIRING));
// Applied before the next message is parsed: trust enforcement, role
// Applied before the next message is parsed: the admissibility check, role
// ownership and, for a nursery connection that is now operational, admission
// all land here, so the role traffic the server sends behind this activate
// meets the gate this activation set.
Expand Down Expand Up @@ -757,7 +757,7 @@ void SendspinClient::process_json_message(SendspinConnection& connection, const
break;
}
case SendspinServerToClientMessageType::SERVER_UNPAIR: {
// server/unpair. Trust gating (LONG_TERM only) happens in handle_server_unpair.
// server/unpair. The LONG_TERM-only check happens in handle_server_unpair.
parsed.release();
SS_LOGI(TAG, "server/unpair received (psk_id=%s)", conn->get_psk_id().c_str());
this->connection_manager_->on_server_unpair(conn);
Expand Down
6 changes: 3 additions & 3 deletions src/connection.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -279,8 +279,8 @@ void SendspinConnection::handle_noise_handshake_text(std::string_view text) {
assert(outcome.has_value() && "a completed handshake hands out its result");
// Record the server's identity (public key) and the PSK category/psk_id that admitted
// the connection, resolved by the handshake.
this->set_noise_handshake_result(outcome->server_id.view(), outcome->psk_category,
outcome->psk_id.view());
this->set_noise_handshake_result(outcome->server_id, outcome->psk_category,
outcome->psk_id);
// pairing.md "Pairing index": a fresh handshake starts a fresh count for the
// pairing_index / CPace-sid counter.
this->reset_pairing_index();
Expand Down Expand Up @@ -333,7 +333,7 @@ bool SendspinConnection::handle_noise_rehandshake(std::span<uint8_t> msg1_bytes)
SS_LOGE(TAG, "handle_noise_rehandshake: no handshake hash available");
return false;
}
auto result = run_rehandshake_msg1(msg1_bytes, this->server_id_.view(), *this->noise_identity_,
auto result = run_rehandshake_msg1(msg1_bytes, this->server_id_, *this->noise_identity_,
*this->noise_record_store_, this->noise_suite_name_,
prior_h.value(), *this->json_arena_);
if (!result.has_value()) {
Expand Down
35 changes: 18 additions & 17 deletions src/connection.h
Original file line number Diff line number Diff line change
Expand Up @@ -642,12 +642,12 @@ class SendspinConnection : public std::enable_shared_from_this<SendspinConnectio
void wake_protocol_task() const;

// ========================================
// Configuration setters (called by hub after receiving server/hello message)
// Handshake state (protocol task unless noted)
// ========================================

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

/// @brief Marks that the WebSocket upgrade completed
/// @brief Marks that the WebSocket upgrade completed. Transport thread.
Comment thread
kahrendt marked this conversation as resolved.
Resolved
/// @note Distinct from is_connected(): on ESP the socket is accepted before any WebSocket
/// handshake, so this flag signals that the peer spoke WebSocket.
void mark_ws_upgraded() {
this->ws_upgraded_.store(true, std::memory_order_release);
}

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

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

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

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

// ========================================
// Initialization setters (called by hub before start)
// Initialization setters (ConnectionManager, before the protocol task can reach the connection)
// ========================================

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

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

/// The pairing record staged by the attempt in flight, committed by the
/// server/pair-finalize handler (nullopt = nothing to store). Protocol task only.
std::optional<SendspinPairingRecord> pending_pairing_record_{};
Expand Down Expand Up @@ -1095,6 +1089,12 @@ class SendspinConnection : public std::enable_shared_from_this<SendspinConnectio
/// re-handshake. Protocol task only.
IdText psk_id_{};

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

// Struct fields

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

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

/// The kind of the message in fallback_buf_ (TEXT or BINARY: a continuation frame does not
Expand Down
12 changes: 6 additions & 6 deletions src/connection_manager.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -652,13 +652,13 @@ void ConnectionManager::on_server_activate(SendspinConnection* conn,
msg.active_roles.value_or(playback_capable ? conn->get_active_roles() : ActiveRoles{});
const bool has_roles = !effective_roles.empty();

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

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

// Admission: every nursery entry that has proven itself (is_operational(): hello handshake
// complete and first server/activate applied and admissible; trust was already checked when
// that activate was processed). The activate handler admits at once when the hello completed
// first; this level-triggered pass covers the other order.
// complete and first server/activate applied, its admissibility checked when it was
// processed). The activate handler admits at once when the hello completed first; this
// level-triggered pass covers the other order.
for (auto it = this->nursery_.begin(); it != this->nursery_.end();) {
if (!it->conn->is_operational()) {
++it;
Expand Down
16 changes: 8 additions & 8 deletions src/connection_manager.h
Original file line number Diff line number Diff line change
Expand Up @@ -468,9 +468,9 @@ class ConnectionManager {
// Protocol task: message handlers
// ========================================

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

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

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

private:
Expand Down Expand Up @@ -723,7 +723,7 @@ class ConnectionManager {

/// @brief Decides whether an incoming connection should displace an admitted one.
///
/// Applies admission.h::should_admit_connection; trust enforcement runs earlier, on the
/// Applies admission.h::should_admit_connection; the admissibility check runs earlier, on the
/// activate.
/// @param admitted The admitted connection the incoming one conflicts with, or nullptr.
/// @param new_conn The newly proven candidate connection. Must not be null.
Expand Down Expand Up @@ -769,7 +769,7 @@ class ConnectionManager {
/// Removing a record from the RecordStore does not by itself end a session that is already
/// running on it: a connection caches its resolved psk_id and PSK category at Noise-handshake
/// completion (see SendspinConnection::get_psk_category()) and never re-resolves them against
/// the store. Without this sweep a revoked device would keep its LONG_TERM trust (and with
/// the store. Without this sweep a revoked device would keep its LONG_TERM category (and with
/// it playback) until it happened to disconnect, so revocation would not take effect until
/// the peer's next connection.
///
Expand Down
6 changes: 0 additions & 6 deletions src/crypto/constants.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@

#include "constants.h"

#include "keys.h"
#include "platform/crypto.h"

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

// SENTINEL_PSK_ID = base64url(SHA-256(PSK_ID_LABEL || SENTINEL_PSK))
// Computed once at startup from SENTINEL_PSK.
// NOLINTNEXTLINE(bugprone-throwing-static-initialization)
const std::string SENTINEL_PSK_ID = psk_id_for(SENTINEL_PSK);

} // namespace sendspin
18 changes: 12 additions & 6 deletions src/crypto/constants.h
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@
#include <array>
#include <cstddef>
#include <cstdint>
#include <string>
#include <string_view>

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

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

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

/// @brief Largest server/init the handshake keeps for its prologue: about five times the minimal
/// frame, a version and a PEER_ID_SIZE server_id in about 104 bytes (messaging.md "server/init").
/// It bounds the prologue buffer each handshake holds; the cost is that a later revision's
/// optional fields, which messaging.md "Forward compatibility" has the client ignore, must keep
/// the frame under it. MAX_HANDSHAKE_MESSAGE_BYTES bounds the handshake's other peer input.
static constexpr size_t MAX_SERVER_INIT_BYTES = 512;

/// @brief Per-connection reassembly buffer cap: 1 MiB.
/// Artwork is never fragmented: roles/artwork/v1.md "Artwork (Binary)" caps a message at
/// MAX_TRANSPORT_PLAINTEXT so it fits one Noise transport message. The message that can
Expand Down
3 changes: 2 additions & 1 deletion src/esp/server_connection.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,8 @@ SendspinServerConnection::SendspinServerConnection(httpd_handle_t server, int so
}

void SendspinServerConnection::start() {
// Time filter is initialized by the hub when it sets up the connection.
// No action needed: the ws_server delivers the connection only once its WebSocket upgrade
// completes, so the transport is already established by then.
}

void SendspinServerConnection::disconnect(SendspinGoodbyeReason reason) {
Expand Down
Loading
Loading