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
13 changes: 11 additions & 2 deletions HowToUses/06_ROXWARP_CLUSTER.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,18 @@ roxWarp is a gossip-based state synchronization protocol for multi-device Sandst

## Enable Clustering

### Basic (plain WebSocket, no TLS)
The cluster is fail-closed: without mTLS certificates it starts only with
`--cluster-insecure`. `--cluster` alone, or a broken or incomplete mTLS
setup, leaves the cluster listener and peer connections off (the log says
why); `/api/cluster/status` still answers.

### Basic (plain WebSocket, no TLS, no peer authentication)
```bash
sandstar-engine-server --sox --cluster --node-id sandstar-a-001
sandstar-engine-server --sox --cluster --cluster-insecure --node-id sandstar-a-001
```
Any host that can reach the port can join as a peer. Use it only on an
isolated test network. In this mode `/roxwarp` is also served on the REST
port.

### With Config File
```bash
Expand All @@ -35,6 +43,7 @@ sandstar-engine-server --sox --cluster --node-id sandstar-a-001 \
| `--cluster-cert <path>` | none | Device certificate (PEM) |
| `--cluster-key <path>` | none | Device private key (PEM) |
| `--cluster-ca <path>` | none | CA certificate for peer verification |
| `--cluster-insecure` | off | Allow plain WebSocket with no peer auth when no certificates are given (CLI only, not in the config file) |

## Cluster Config File

Expand Down
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,7 @@ Set via `--config-dir` or `SANDSTAR_CONFIG_DIR`; contains:
| `--no-control` | | false | Disable PID/sequencer engine |
| `--cluster` | | false | Enable roxWarp gossip clustering (see `--cluster-config`) |
| `--cluster-config` | | (none) | Path to `ClusterConfig` JSON (peers, mTLS, mDNS) |
| `--cluster-insecure` | | false | Allow the cluster over plain WebSocket, no peer auth, when no mTLS certificates are given. Without it the cluster network stays off |
| `--tls-cert` | `SANDSTAR_TLS_CERT` | (none) | TLS certificate (PEM) |
| `--tls-key` | `SANDSTAR_TLS_KEY` | (none) | TLS private key (PEM) |
| `--sedona` | | false | Enable Sedona VM |
Expand Down Expand Up @@ -175,7 +176,7 @@ Cluster + SOX WebSocket:
| Endpoint | Method | Description |
|----------|--------|-------------|
| `/api/rows` | GET | RoWS (SOX-over-WebSocket) session — tree, slot, link, readTags/setTags/deleteTag |
| `/roxwarp` | GET | roxWarp cluster peer WebSocket (when `--cluster` is set) |
| `/roxwarp` | GET | roxWarp cluster peer WebSocket (only with `--cluster --cluster-insecure`; with mTLS peers use the cluster port) |

All endpoints support JSON by default; `Accept: text/zinc` returns Haystack Zinc. Per-endpoint details in [`docs/Progress/DRIVER_REST_API.md`](docs/Progress/DRIVER_REST_API.md).

Expand Down
14 changes: 14 additions & 0 deletions crates/sandstar-server/src/args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,12 @@ pub struct ServerArgs {
/// Path to CA certificate (PEM) for verifying roxWarp peer certificates.
#[arg(long, env = "SANDSTAR_CLUSTER_CA")]
pub cluster_ca: Option<String>,

/// Allow the roxWarp cluster over plain WebSocket with no peer auth when
/// no mTLS certificates are given. Without it and without certificates,
/// the cluster listener and outbound peer connections stay off (R-54).
#[arg(long, default_value_t = false)]
pub cluster_insecure: bool,
}

fn default_socket() -> String {
Expand Down Expand Up @@ -378,6 +384,14 @@ mod tests {
assert!(args.cluster_cert.is_none());
assert!(args.cluster_key.is_none());
assert!(args.cluster_ca.is_none());
assert!(!args.cluster_insecure);
}

#[test]
fn test_cluster_insecure_flag() {
let args =
ServerArgs::parse_from(["sandstar-engine-server", "--cluster", "--cluster-insecure"]);
assert!(args.cluster_insecure);
}

#[test]
Expand Down
92 changes: 41 additions & 51 deletions crates/sandstar-server/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -481,6 +481,8 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {

// Override port from CLI
cluster_config.port = args.cluster_port;
// Plain WS without peer auth only on explicit request (R-54, S-36).
cluster_config.allow_plain = args.cluster_insecure;

// Set mTLS paths from CLI args
if args.cluster_cert.is_some() || args.cluster_key.is_some() || args.cluster_ca.is_some() {
Expand All @@ -504,7 +506,8 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
node_id = %cluster_config.node_id,
port = cluster_config.port,
peers = cluster_config.peers.len(),
mtls = cluster_config.cert_path.is_some(),
// Paths only; whether mTLS builds is logged by `roxwarp::transport`.
mtls_paths = cluster_config.cert_path.is_some(),
"roxWarp cluster mode enabled"
);

Expand All @@ -519,73 +522,60 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
sox_tree: sox_api_state.as_ref().map(|s| s.tree.clone()),
};

// Start separate roxWarp listener on cluster port (default 7443)
// Separate roxWarp listener on the cluster port (default 7443).
// Fail-closed (R-54, S-36): mTLS, or plain WS only with
// --cluster-insecure; a broken mTLS setup keeps the port closed.
// `server_transport` logs why the listener is off.
let cluster_port = cluster_config.port;
let transport = sandstar_server::roxwarp::transport::server_transport(&cluster_config);
let rw_state_for_listener = rw_state.clone();
tokio::spawn(async move {
use axum::routing::get;
use axum::Router;
use sandstar_server::roxwarp::transport::Transport;

// Outside the REST auth layer (R-2): peers authenticate with mTLS
// on this port when certificates are configured. Without them, or
// if the mTLS config fails to build, this serves plain WS with no
// peer auth (known gap, see 06).
// on this port; plain WS (no peer auth) only with --cluster-insecure.
let cluster_app = Router::new()
.route(
"/roxwarp",
get(sandstar_server::roxwarp::handler::roxwarp_upgrade),
)
.with_state(rw_state_for_listener);

let bind_addr: std::net::SocketAddr = format!("0.0.0.0:{cluster_port}")
.parse()
.expect("valid cluster bind address");

// Build mTLS server config if certificates are configured
if let (Some(ref cert), Some(ref key), Some(ref ca)) = (
&cluster_config.cert_path,
&cluster_config.key_path,
&cluster_config.ca_path,
) {
match sandstar_server::roxwarp::mtls::build_mtls_server_config(cert, key, ca) {
Ok(server_tls_config) => {
info!(port = cluster_port, "roxWarp: starting mTLS listener");
let rustls_config =
axum_server::tls_rustls::RustlsConfig::from_config(server_tls_config);
if let Err(e) = axum_server::bind_rustls(bind_addr, rustls_config)
.serve(cluster_app.into_make_service())
.await
{
error!(port = cluster_port, error = %e, "roxWarp: mTLS listener failed");
}
}
Err(e) => {
error!(error = %e, "roxWarp: failed to build mTLS server config, falling back to plain WS");
let listener = match tokio::net::TcpListener::bind(&bind_addr).await {
Ok(l) => l,
Err(e) => {
error!(port = cluster_port, error = %e, "roxWarp: failed to bind cluster port");
return;
}
};
info!(
port = cluster_port,
"roxWarp: listening (plain WS, mTLS config failed)"
);
axum::serve(listener, cluster_app).await.ok();
let bind_addr = std::net::SocketAddr::from(([0, 0, 0, 0], cluster_port));

match transport {
Transport::Mtls(server_tls_config) => {
info!(port = cluster_port, "roxWarp: starting mTLS listener");
let rustls_config =
axum_server::tls_rustls::RustlsConfig::from_config(server_tls_config);
if let Err(e) = axum_server::bind_rustls(bind_addr, rustls_config)
.serve(cluster_app.into_make_service())
.await
{
error!(port = cluster_port, error = %e, "roxWarp: mTLS listener failed");
}
}
} else {
// No mTLS configured — plain WebSocket listener
let listener = match tokio::net::TcpListener::bind(&bind_addr).await {
Ok(l) => l,
Err(e) => {
error!(port = cluster_port, error = %e, "roxWarp: failed to bind cluster port");
return;
Transport::Plain => {
let listener = match tokio::net::TcpListener::bind(&bind_addr).await {
Ok(l) => l,
Err(e) => {
error!(port = cluster_port, error = %e, "roxWarp: failed to bind cluster port");
return;
}
};
info!(
port = cluster_port,
"roxWarp: listening (plain WS, --cluster-insecure)"
);
if let Err(e) = axum::serve(listener, cluster_app).await {
error!(port = cluster_port, error = %e, "roxWarp: plain WS listener failed");
}
};
info!(port = cluster_port, "roxWarp: listening (plain WS)");
axum::serve(listener, cluster_app).await.ok();
}
Transport::Off => {
info!(port = cluster_port, "roxWarp: cluster listener not started");
}
}
});

Expand Down
16 changes: 11 additions & 5 deletions crates/sandstar-server/src/rest/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1261,11 +1261,17 @@ async fn cluster_disabled_handler() -> impl IntoResponse {
pub fn roxwarp_router(state: crate::roxwarp::RoxWarpState, auth_state: AuthState) -> Router {
use crate::roxwarp::handler;

// Outside the auth layer (R-2): cluster peers connect here without a
// bearer token; gating it needs a peer-auth decision first.
let ws_route = Router::new()
.route("/roxwarp", get(handler::roxwarp_upgrade))
.with_state(state.clone());
// Peer WebSocket on the REST port: outside the auth layer (R-2) and with
// no TLS, so it is mounted only in plain mode (`--cluster-insecure`, no
// mTLS paths). With mTLS, or with the cluster network off, peers cannot
// bypass the cluster port through here (R-54, S-36).
let ws_route = if crate::roxwarp::transport::plain_ws_allowed(&state.config) {
Router::new()
.route("/roxwarp", get(handler::roxwarp_upgrade))
.with_state(state.clone())
} else {
Router::new()
};

let status_route = Router::new()
.route("/api/cluster/status", get(cluster_status_handler))
Expand Down
106 changes: 78 additions & 28 deletions crates/sandstar-server/src/roxwarp/cluster.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,11 @@ pub struct ClusterConfig {
/// only the static list is used — no multicast traffic.
#[serde(default)]
pub enable_mdns: bool,
/// Allow plain WebSocket without peer auth when no mTLS is configured.
/// Set only by `--cluster-insecure`, never from the config file
/// (R-54, S-36). See [`super::transport`].
#[serde(skip)]
pub allow_plain: bool,
}

fn default_cluster_port() -> u16 {
Expand Down Expand Up @@ -99,6 +104,7 @@ impl Default for ClusterConfig {
key_path: None,
ca_path: None,
enable_mdns: false,
allow_plain: false,
}
}
}
Expand Down Expand Up @@ -510,6 +516,36 @@ impl ClusterManager {
"roxWarp cluster manager starting"
);

// Spawn the channel feed loop
let feed_engine = self.delta_engine.clone();
let feed_handle = self.engine_handle.clone();
let feed_interval = self.config.feed_interval_secs;
tokio::spawn(async move {
channel_feed_loop(feed_engine, feed_handle, feed_interval).await;
});

// Outbound transport, fail-closed (R-54, S-36): mTLS, or plain WS only
// with --cluster-insecure. `client_transport` logs why it is off.
use super::transport::{client_transport, Transport};
let mtls_client: super::peer::MtlsClientConfig = match client_transport(&self.config) {
Transport::Mtls(cfg) => {
info!("roxWarp: mTLS client config loaded for outbound connections");
Some(cfg)
}
Transport::Plain => None,
Transport::Off => {
// The local feed above still runs, so /api/cluster/status and
// /api/cluster/query keep answering for this node. Peers are
// not registered, so status shows none instead of "offline".
warn!(
peers = self.config.peers.len(),
mdns = self.config.enable_mdns,
"roxWarp: cluster transport off, outbound peers and mDNS not started"
);
return;
}
};

// Initialize peer states
{
let mut states = self.peer_states.write().await;
Expand All @@ -520,34 +556,6 @@ impl ClusterManager {
}
}

// Build mTLS client config for outbound connections (if configured)
let mtls_client: super::peer::MtlsClientConfig = if let (Some(cert), Some(key), Some(ca)) = (
&self.config.cert_path,
&self.config.key_path,
&self.config.ca_path,
) {
match super::mtls::build_mtls_client_config(cert, key, ca) {
Ok(cfg) => {
info!("roxWarp: mTLS client config loaded for outbound connections");
Some(cfg)
}
Err(e) => {
warn!(error = %e, "roxWarp: failed to load mTLS client config, using plain WS");
None
}
}
} else {
None
};

// Spawn the channel feed loop
let feed_engine = self.delta_engine.clone();
let feed_handle = self.engine_handle.clone();
let feed_interval = self.config.feed_interval_secs;
tokio::spawn(async move {
channel_feed_loop(feed_engine, feed_handle, feed_interval).await;
});

// Spawn outbound peer connections for the static peer list.
for peer_config in &self.config.peers {
if !peer_config.enabled {
Expand Down Expand Up @@ -885,6 +893,48 @@ mod tests {
assert!(ClusterConfig::default().validate().is_ok());
}

#[test]
fn config_file_cannot_enable_plain_ws() {
let c = load_json(r#"{"node_id":"a","allow_plain":true}"#).unwrap();
assert!(!c.allow_plain);
}

/// Peers registered by `run` for a config with one static peer.
async fn peers_after_run(allow_plain: bool) -> Vec<String> {
let config = ClusterConfig {
node_id: "s36".to_string(),
peers: vec![PeerConfig {
node_id: "peer-b".to_string(),
// Nothing listens here; a dial attempt just fails.
address: "127.0.0.1:1".to_string(),
enabled: true,
}],
allow_plain,
..ClusterConfig::default()
};
let (tx, _rx) = tokio::sync::mpsc::channel(8);
let manager = ClusterManager::new(
config,
Arc::new(DeltaEngine::new("s36".to_string())),
EngineHandle::new(tx),
);
manager.run().await;
let states = manager.peer_states().read().await;
states.keys().cloned().collect()
}

#[tokio::test]
async fn run_without_transport_registers_no_peers() {
// No mTLS, no --cluster-insecure: no peer connection, no "offline"
// peer in /api/cluster/status (R-54, S-36).
assert!(peers_after_run(false).await.is_empty());
}

#[tokio::test]
async fn run_with_plain_transport_registers_static_peers() {
assert_eq!(peers_after_run(true).await, vec!["peer-b".to_string()]);
}

#[test]
fn load_rejects_zero_intervals() {
for field in [
Expand Down
1 change: 1 addition & 0 deletions crates/sandstar-server/src/roxwarp/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ pub mod mtls;
pub mod peer;
pub mod protocol;
pub mod string_table;
pub mod transport;

pub use binary_trio::{TrioDict, TrioValue};
pub use cluster::{
Expand Down
Loading
Loading