diff --git a/HowToUses/06_ROXWARP_CLUSTER.md b/HowToUses/06_ROXWARP_CLUSTER.md index bdd7153..3112335 100644 --- a/HowToUses/06_ROXWARP_CLUSTER.md +++ b/HowToUses/06_ROXWARP_CLUSTER.md @@ -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 @@ -35,6 +43,7 @@ sandstar-engine-server --sox --cluster --node-id sandstar-a-001 \ | `--cluster-cert ` | none | Device certificate (PEM) | | `--cluster-key ` | none | Device private key (PEM) | | `--cluster-ca ` | 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 diff --git a/README.md b/README.md index 9d6df78..51813db 100644 --- a/README.md +++ b/README.md @@ -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 | @@ -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). diff --git a/crates/sandstar-server/src/args.rs b/crates/sandstar-server/src/args.rs index e4735e5..102d777 100644 --- a/crates/sandstar-server/src/args.rs +++ b/crates/sandstar-server/src/args.rs @@ -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, + + /// 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 { @@ -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] diff --git a/crates/sandstar-server/src/main.rs b/crates/sandstar-server/src/main.rs index a45f187..0be9514 100644 --- a/crates/sandstar-server/src/main.rs +++ b/crates/sandstar-server/src/main.rs @@ -481,6 +481,8 @@ async fn main() -> Result<(), Box> { // 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() { @@ -504,7 +506,8 @@ async fn main() -> Result<(), Box> { 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" ); @@ -519,17 +522,20 @@ async fn main() -> Result<(), Box> { 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", @@ -537,55 +543,39 @@ async fn main() -> Result<(), Box> { ) .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"); + } } }); diff --git a/crates/sandstar-server/src/rest/mod.rs b/crates/sandstar-server/src/rest/mod.rs index 569cd9e..c9ecf27 100644 --- a/crates/sandstar-server/src/rest/mod.rs +++ b/crates/sandstar-server/src/rest/mod.rs @@ -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)) diff --git a/crates/sandstar-server/src/roxwarp/cluster.rs b/crates/sandstar-server/src/roxwarp/cluster.rs index fd028f3..0848dd6 100644 --- a/crates/sandstar-server/src/roxwarp/cluster.rs +++ b/crates/sandstar-server/src/roxwarp/cluster.rs @@ -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 { @@ -99,6 +104,7 @@ impl Default for ClusterConfig { key_path: None, ca_path: None, enable_mdns: false, + allow_plain: false, } } } @@ -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; @@ -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 { @@ -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 { + 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 [ diff --git a/crates/sandstar-server/src/roxwarp/mod.rs b/crates/sandstar-server/src/roxwarp/mod.rs index f639316..44137a0 100644 --- a/crates/sandstar-server/src/roxwarp/mod.rs +++ b/crates/sandstar-server/src/roxwarp/mod.rs @@ -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::{ diff --git a/crates/sandstar-server/src/roxwarp/transport.rs b/crates/sandstar-server/src/roxwarp/transport.rs new file mode 100644 index 0000000..5364e47 --- /dev/null +++ b/crates/sandstar-server/src/roxwarp/transport.rs @@ -0,0 +1,216 @@ +//! Which transport the roxWarp cluster may use (R-54, S-36). +//! +//! Fail-closed: peers talk over mTLS, or over plain WebSocket only when the +//! operator asked for it (`--cluster-insecure`). A broken or incomplete mTLS +//! setup never falls back to plain WebSocket; the cluster network stays off +//! and the reason is logged. + +use std::fmt::Display; +use std::sync::Arc; + +use tracing::{error, warn}; + +use super::cluster::ClusterConfig; +use super::mtls::{build_mtls_client_config, build_mtls_server_config}; + +/// Transport decision for one side (inbound listener or outbound peers). +#[derive(Debug)] +pub enum Transport { + /// mTLS with the built rustls config. + Mtls(T), + /// Plain WebSocket, no peer authentication (`--cluster-insecure`). + Plain, + /// No cluster network on this side. + Off, +} + +impl Transport { + /// Short name for logs and tests. + pub fn kind(&self) -> &'static str { + match self { + Transport::Mtls(_) => "mtls", + Transport::Plain => "plain", + Transport::Off => "off", + } + } +} + +/// True when the cluster runs over plain WebSocket: `--cluster-insecure` +/// and no mTLS path set. Same rule as the `Plain` arm of [`server_transport`], +/// without building TLS or logging. The REST port mounts `/roxwarp` only then; +/// with mTLS, peers must use the cluster port. +pub fn plain_ws_allowed(config: &ClusterConfig) -> bool { + config.allow_plain + && config.cert_path.is_none() + && config.key_path.is_none() + && config.ca_path.is_none() +} + +/// Transport for the inbound listener (cluster port, default 7443). +pub fn server_transport(config: &ClusterConfig) -> Transport> { + decide(config, "listener", build_mtls_server_config) +} + +/// Transport for outbound peer connections. +pub fn client_transport(config: &ClusterConfig) -> Transport> { + decide(config, "outbound", build_mtls_client_config) +} + +fn decide( + config: &ClusterConfig, + side: &str, + build: impl FnOnce(&str, &str, &str) -> Result, +) -> Transport { + match (&config.cert_path, &config.key_path, &config.ca_path) { + (Some(cert), Some(key), Some(ca)) => match build(cert, key, ca) { + Ok(tls) => Transport::Mtls(tls), + Err(e) => { + error!( + side, + error = %e, + "roxWarp: mTLS config failed, cluster {side} disabled (no plain WS fallback)" + ); + Transport::Off + } + }, + (None, None, None) if config.allow_plain => { + warn!( + side, + "roxWarp: cluster {side} uses plain WS without peer auth (--cluster-insecure)" + ); + Transport::Plain + } + (None, None, None) => { + warn!( + side, + "roxWarp: no mTLS configured, cluster {side} disabled; \ + pass --cluster-cert/--cluster-key/--cluster-ca or --cluster-insecure" + ); + Transport::Off + } + _ => { + error!( + side, + "roxWarp: incomplete mTLS config (cert, key and ca are all required), \ + cluster {side} disabled" + ); + Transport::Off + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn config(certs: Option<(&str, &str, &str)>, allow_plain: bool) -> ClusterConfig { + let mut c = ClusterConfig { + allow_plain, + ..ClusterConfig::default() + }; + if let Some((cert, key, ca)) = certs { + c.cert_path = Some(cert.to_string()); + c.key_path = Some(key.to_string()); + c.ca_path = Some(ca.to_string()); + } + c + } + + /// Files that exist but are not PEM certificates or keys. + fn bogus_files() -> (tempfile::TempDir, String, String, String) { + let dir = tempfile::tempdir().unwrap(); + let mut paths = Vec::new(); + for name in ["cert.pem", "key.pem", "ca.pem"] { + let p = dir.path().join(name); + std::fs::write(&p, "not a pem file\n").unwrap(); + paths.push(p.to_string_lossy().into_owned()); + } + let ca = paths.pop().unwrap(); + let key = paths.pop().unwrap(); + let cert = paths.pop().unwrap(); + (dir, cert, key, ca) + } + + #[test] + fn no_certs_and_no_flag_is_off() { + let c = config(None, false); + assert_eq!(server_transport(&c).kind(), "off"); + assert_eq!(client_transport(&c).kind(), "off"); + } + + #[test] + fn no_certs_with_insecure_flag_is_plain() { + let c = config(None, true); + assert_eq!(server_transport(&c).kind(), "plain"); + assert_eq!(client_transport(&c).kind(), "plain"); + } + + #[test] + fn broken_certs_are_off_not_plain() { + let (_dir, cert, key, ca) = bogus_files(); + for allow_plain in [false, true] { + let c = config(Some((&cert, &key, &ca)), allow_plain); + assert_eq!( + server_transport(&c).kind(), + "off", + "allow_plain={allow_plain}" + ); + assert_eq!( + client_transport(&c).kind(), + "off", + "allow_plain={allow_plain}" + ); + } + } + + #[test] + fn missing_cert_files_are_off() { + let c = config( + Some(( + "/nonexistent/c.pem", + "/nonexistent/k.pem", + "/nonexistent/ca.pem", + )), + true, + ); + assert_eq!(server_transport(&c).kind(), "off"); + assert_eq!(client_transport(&c).kind(), "off"); + } + + #[test] + fn incomplete_mtls_config_is_off_even_with_insecure_flag() { + let mut c = config(None, true); + c.cert_path = Some("/some/cert.pem".to_string()); + assert_eq!(server_transport(&c).kind(), "off"); + assert_eq!(client_transport(&c).kind(), "off"); + } + + #[test] + fn plain_ws_allowed_matches_the_plain_transport() { + let (_dir, cert, key, ca) = bogus_files(); + let mut partial = config(None, true); + partial.ca_path = Some(ca.clone()); + for c in [ + config(None, false), + config(None, true), + config(Some((&cert, &key, &ca)), false), + config(Some((&cert, &key, &ca)), true), + partial, + ] { + assert_eq!( + plain_ws_allowed(&c), + server_transport(&c).kind() == "plain", + "allow_plain={} certs={:?}", + c.allow_plain, + c.cert_path + ); + } + } + + #[test] + fn built_mtls_config_is_used() { + let c = config(Some(("c", "k", "ca")), false); + let t = decide(&c, "listener", |_, _, _| Ok::<_, String>(42u8)); + assert!(matches!(t, Transport::Mtls(42))); + } +} diff --git a/crates/sandstar-server/tests/auth_layer.rs b/crates/sandstar-server/tests/auth_layer.rs index d481635..2e838af 100644 --- a/crates/sandstar-server/tests/auth_layer.rs +++ b/crates/sandstar-server/tests/auth_layer.rs @@ -128,6 +128,7 @@ fn build_app(auth: AuthStore) -> (Router, tokio::task::JoinHandle<()>) { key_path: None, ca_path: None, enable_mdns: false, + allow_plain: false, }, sox_tree: None, }; diff --git a/crates/sandstar-server/tests/global_layers.rs b/crates/sandstar-server/tests/global_layers.rs index c69ce1b..66be7f0 100644 --- a/crates/sandstar-server/tests/global_layers.rs +++ b/crates/sandstar-server/tests/global_layers.rs @@ -54,6 +54,7 @@ fn build_app(rate_limit: u64) -> (Router, tokio::task::JoinHandle<()>) { key_path: None, ca_path: None, enable_mdns: false, + allow_plain: false, }, sox_tree: None, }; diff --git a/crates/sandstar-server/tests/roxwarp_integration.rs b/crates/sandstar-server/tests/roxwarp_integration.rs index 7cf118d..0600a82 100644 --- a/crates/sandstar-server/tests/roxwarp_integration.rs +++ b/crates/sandstar-server/tests/roxwarp_integration.rs @@ -49,6 +49,8 @@ fn test_config(node_id: &str, port: u16) -> ClusterConfig { key_path: None, ca_path: None, enable_mdns: false, + // These tests run peers over plain WS (`--cluster-insecure`). + allow_plain: true, } } @@ -285,3 +287,68 @@ async fn mdns_two_nodes_discover_each_other() { found_by_b.lock().unwrap() ); } + +// ── `/roxwarp` on the REST port (R-54, S-36) ─────────────── + +/// Status of a WebSocket upgrade request for `/roxwarp` on the REST-port +/// router built from `config`. 404 means the route is not mounted. +async fn rest_roxwarp_status(config: ClusterConfig) -> axum::http::StatusCode { + use sandstar_server::auth::{AuthState, AuthStore}; + use tower::ServiceExt; + let state = RoxWarpState { + delta_engine: Arc::new(DeltaEngine::new(config.node_id.clone())), + config, + sox_tree: None, + }; + let app = sandstar_server::rest::roxwarp_router(state, AuthState::new(AuthStore::new())); + let req = axum::http::Request::builder() + .uri("/roxwarp") + .header("connection", "upgrade") + .header("upgrade", "websocket") + .header("sec-websocket-version", "13") + .header("sec-websocket-key", "dGhlIHNhbXBsZSBub25jZQ==") + .body(axum::body::Body::empty()) + .unwrap(); + app.oneshot(req).await.unwrap().status() +} + +#[tokio::test] +async fn rest_port_roxwarp_is_mounted_only_in_plain_mode() { + use axum::http::StatusCode; + + // --cluster-insecure, no mTLS: peers may use the REST port. + let plain = test_config("plain", 0); + assert_ne!(rest_roxwarp_status(plain).await, StatusCode::NOT_FOUND); + + // No mTLS and no flag: the cluster network is off. + let mut off = test_config("off", 0); + off.allow_plain = false; + assert_eq!(rest_roxwarp_status(off).await, StatusCode::NOT_FOUND); + + // mTLS configured: peers must use the cluster port, even with the flag. + let mut mtls = test_config("mtls", 0); + mtls.cert_path = Some("/etc/c.pem".into()); + mtls.key_path = Some("/etc/k.pem".into()); + mtls.ca_path = Some("/etc/ca.pem".into()); + assert_eq!(rest_roxwarp_status(mtls).await, StatusCode::NOT_FOUND); +} + +#[tokio::test] +async fn rest_port_cluster_status_stays_mounted() { + use axum::http::StatusCode; + use sandstar_server::auth::{AuthState, AuthStore}; + use tower::ServiceExt; + let mut off = test_config("off", 0); + off.allow_plain = false; + let state = RoxWarpState { + delta_engine: Arc::new(DeltaEngine::new("off".into())), + config: off, + sox_tree: None, + }; + let app = sandstar_server::rest::roxwarp_router(state, AuthState::new(AuthStore::new())); + let req = axum::http::Request::builder() + .uri("/api/cluster/status") + .body(axum::body::Body::empty()) + .unwrap(); + assert_eq!(app.oneshot(req).await.unwrap().status(), StatusCode::OK); +} diff --git a/docs/Progress/DEPLOYMENT_CHECKLIST.md b/docs/Progress/DEPLOYMENT_CHECKLIST.md index 654b9cf..68a6a7a 100644 --- a/docs/Progress/DEPLOYMENT_CHECKLIST.md +++ b/docs/Progress/DEPLOYMENT_CHECKLIST.md @@ -107,7 +107,8 @@ Read the journal soon after the start: it is volatile and holds well under an ho 4. **Engine log** `/var/log/sandstar/sandstar-engine.log.`: - `tables loaded` with the expected count; - a watchdog line saying GPIO60 was opened, or why not (the engine retries for about 5 minutes); - - no repeated `poll cycle exceeded`. + - no repeated `poll cycle exceeded`; + - with `--cluster` and no mTLS certificates (the packaged unit): `roxWarp: no mTLS configured, cluster listener disabled` and `cluster listener not started`, so port 7443 is not listening (S-36). With certificates expect `starting mTLS listener`; `mTLS config failed` means the certificate files need fixing. 5. **Warnings:** count ERROR and WARN lines from the start time and compare them with the known types for this device (for example BACnet `comm fault` when a BACnet drop-in is active). Investigate anything new. 6. **Data:** `curl -s http://localhost:8085/api/status` and spot-read a few channels with `/api/read`. 7. **Next day:** confirm that log pruning kept at most 14 dated files in `/var/log/sandstar/`. diff --git a/docs/Progress/HARDCODED_LIMITS.md b/docs/Progress/HARDCODED_LIMITS.md index 2737e59..ded0e03 100644 --- a/docs/Progress/HARDCODED_LIMITS.md +++ b/docs/Progress/HARDCODED_LIMITS.md @@ -21,6 +21,7 @@ > - Request body limit 1 MB (`rest/mod.rs:1231`, `with_global_layers`); since S-35 it also covers the tags, alerts, roxWarp and simulator routes, which had axum's 2 MB `Json` default before. Driver actor channel capacity 64. > - Log files kept: 14 by default (`--log-max-files`, `logging.rs`). > - roxWarp timer bounds: 1..=86400 s (`roxwarp/cluster.rs`). +> - `--cluster-insecure` default off (`args.rs`, R-54, S-36): without it and without mTLS certificates the cluster listener and peer connections stay off. CLI only; the cluster JSON config cannot set it (`ClusterConfig.allow_plain` is `serde(skip)`). > - roxWarp `PEER_ANOMALY_WARN_INTERVAL_MS` = 60,000 ms (`roxwarp/cluster.rs:225`, R-45/R-27, 2026-11-19): at most one `warn` per minute about bad peer points (NaN/inf value, future timestamp); the rest go to `debug`. Keep hardcoded. > - roxWarp `MAX_PEER_FUTURE_SKEW_MS` = 300,000 ms (5 min) (`roxwarp/cluster.rs:230`, R-27, 2026-11-19): a peer point whose timestamp is further ahead of the local clock is rejected (logged, rate-limited), so a peer cannot pin a channel under last-writer-wins. **Consider** making it configurable if field clocks drift more. > - roxWarp `MAX_FILTER_DEPTH` = 32 (`roxwarp/handler.rs:611`, S-24): deepest `and`/`or` nesting evaluated in a point filter (REST cluster query, roxWarp `query`); terms past it do not match. Without it a long chain overflowed the stack and killed the process. Keep hardcoded. diff --git a/docs/Progress/OVERVIEW.md b/docs/Progress/OVERVIEW.md index 6903609..5ccf31a 100644 --- a/docs/Progress/OVERVIEW.md +++ b/docs/Progress/OVERVIEW.md @@ -45,8 +45,8 @@ This is the single-read status tracker for the Sandstar Rust project. It consoli | BACnet/IP driver (read + write + COV + RPM + BBMD) | ✅ Complete — Project B, 11 phases, live-validated | [IMPLEMENTATION_PLAN_FILTER_AND_BACNET.md](IMPLEMENTATION_PLAN_FILTER_AND_BACNET.md), [BACNET_SETUP.md](BACNET_SETUP.md) | | MQTT driver | ✅ Complete — Project C, 4 phases, live-validated | [IMPLEMENTATION_PLAN_MQTT.md](IMPLEMENTATION_PLAN_MQTT.md), [MQTT_SETUP.md](MQTT_SETUP.md) | | Poll integration (driver → engine channels) | ✅ Complete — shared tick task in rest/mod.rs | [IMPLEMENTATION_PLAN_FILTER_AND_BACNET.md](IMPLEMENTATION_PLAN_FILTER_AND_BACNET.md) Stage 1/2 | -| REST API + WebSocket | ✅ 30+ routes (see §3), bearer + SCRAM auth, rate limit, WS push. Since S-31 every HTTP write route is behind the auth layer and since S-32 the editor endpoints (`/live`, `/api/rows`, `/live/sedonaState`) are too (bearer header or session cookie, plus an Origin check); ⚠ `/roxwarp` is not | [ROADMAP_v2.md](ROADMAP_v2.md) §Phase 1, [DRIVER_REST_API.md](DRIVER_REST_API.md) | -| Security hardening | 🟡 Partial. Open: the field service binds `0.0.0.0` with no auth configured; editor WebSockets and `/roxwarp` outside `check_auth` (§3, S-32); SIGTERM not handled (no graceful shutdown) | [ROADMAP_v2.md](ROADMAP_v2.md) §Phase 5.7, §Phase 6.5 | +| REST API + WebSocket | ✅ 30+ routes (see §3), bearer + SCRAM auth, rate limit, WS push. Since S-31 every HTTP write route is behind the auth layer and since S-32 the editor endpoints (`/live`, `/api/rows`, `/live/sedonaState`) are too (bearer header or session cookie, plus an Origin check). `/roxwarp` on the REST port has no auth and is mounted only with `--cluster-insecure` (S-36) | [ROADMAP_v2.md](ROADMAP_v2.md) §Phase 1, [DRIVER_REST_API.md](DRIVER_REST_API.md) | +| Security hardening | 🟡 Partial. Open: the field service binds `0.0.0.0` with no auth configured; `/roxwarp` outside `check_auth` when `--cluster-insecure` is given (§3, S-36); SIGTERM not handled (no graceful shutdown) | [ROADMAP_v2.md](ROADMAP_v2.md) §Phase 5.7, §Phase 6.5 | | Visual DDC editor | 🟡 14.0A REST complete. 14.0B–F were superseded by 14.0G (native backend for the external Vue editor): about 75%, G-6 open, G-7/G-8 partial | [IMPLEMENTATION_PLAN_NATIVE_EDITOR_BACKEND.md](IMPLEMENTATION_PLAN_NATIVE_EDITOR_BACKEND.md) | | Driver Framework v2 (Phase 12) | ✅ All sub-phases complete (12.0A–G + 12.0D.WS). Caveats: MQTT never reconnects; BACnet COV subscriptions never start in production; REST-created drivers get no poll tick; Modbus is not loadable | [IMPLEMENTATION_PLAN_DRIVER_FRAMEWORK.md](IMPLEMENTATION_PLAN_DRIVER_FRAMEWORK.md) | | Clustering — roxWarp (Phase 9) | 🟡 9.0a + 9.0b + 9.0c shipped; 9.0d SkySpark Fantom pod open. The typed binary-Trio format exists in code but is not what goes over the wire | [ROADMAP_v2.md](ROADMAP_v2.md) §Phase 9, [research/16](../research/16_ROXWARP_PROTOCOL.md) | @@ -228,7 +228,7 @@ Router: `router_with_auth` in `crates/sandstar-server/src/rest/mod.rs`, plus rou | `PUT /api/tags/{comp_id}`, `DELETE /api/tags/{comp_id}/{key}` | **yes** (S-31) | Dynamic tags (write) | | `GET /api/alerts/config` (password masked), `/recipients`, `/active`, `/history` | no | Alert management (read) | | `PUT /api/alerts/config`, `POST/DELETE /api/alerts/recipients*`, `POST /api/alerts/test` | **yes** (S-31) | Alert management (write, test e-mail) | -| `GET /roxwarp` | **no** ⚠ | roxWarp peer WebSocket on the REST port (with `--cluster`). Peers send no bearer token; mTLS applies only on the separate cluster port | +| `GET /roxwarp` | **no** ⚠ | roxWarp peer WebSocket on the REST port, mounted only with `--cluster --cluster-insecure` and no mTLS paths (S-36). Peers send no bearer token. With mTLS, peers use the cluster port only | | `GET /api/cluster/status` | no | Cluster overview | | `POST /api/cluster/query` | **yes** (S-31) | Distributed Haystack query | | `GET /api/sim/state` | no | Only in builds with the `simulator-hal` feature | @@ -239,6 +239,7 @@ Router: `router_with_auth` in `crates/sandstar-server/src/rest/mod.rs`, plus rou - Bearer token (`--auth-token` / `SANDSTAR_AUTH_TOKEN`) and SCRAM-SHA-256 (`--auth-user` / `--auth-pass`, `SANDSTAR_AUTH_USER` / `SANDSTAR_AUTH_PASS`). - REST TLS is behind the `tls` cargo feature; the release alias `arm-build-svm` does not enable it. - Filter depth cap 32, watch cap 64, max channels per watch 256, body limit 1 MB, rate limit on by default (100 req/s, one counter shared by all clients). +- roxWarp cluster is fail-closed (R-54, S-36): the cluster port (default 7443) and outbound peer connections use mTLS (`--cluster-cert/--cluster-key/--cluster-ca`), or plain WS only with `--cluster-insecure`. No certificates and no flag, or a broken or incomplete mTLS setup: no cluster listener and no peer connections, with a WARN/ERROR line saying why; `/api/cluster/status` keeps answering. The field unit runs `--cluster` without either, so 7443 is closed there after S-36. - The request counter, rate limit, body limit and CORS wrap every route on the REST port, including the tags, alerts, roxWarp/cluster and simulator routers merged in `main.rs` (`rest::with_global_layers`, applied last; R-53, S-35). Before S-35 those routers were outside these layers. - CORS: any origin, with an explicit method and header list. - Engine calls from REST, the `/api/ws` WebSocket, SOX, roxWarp and drivers wait at most 10 s (`ENGINE_REPLY_TIMEOUT`). REST then answers `503 {"err":"engine timeout"}`; for writes and other state-changing commands the text adds "may still be applied" (R-28, S-20). @@ -314,7 +315,7 @@ Host addresses, SSH details and site names are deliberately not written in this Rewritten 2026-11-18. Ranked by risk first, then value. ### 🔴 Security and robustness (field device affected) -1. **Auth in the field configuration.** The unit binds `0.0.0.0` with no auth; and even with auth on, `/roxwarp` bypasses auth (§3). HTTP write routes are behind it since S-31, the editor endpoints since S-32; the editor itself cannot log in yet (S-32b). +1. **Auth in the field configuration.** The unit binds `0.0.0.0` with no auth; and with `--cluster-insecure`, `/roxwarp` bypasses auth (§3, S-36). HTTP write routes are behind it since S-31, the editor endpoints since S-32; the editor itself cannot log in yet (S-32b). 2. **Panic paths on network input.** Release builds abort on panic; known cases include a short BACnet BVLL frame and some lock-poison `unwrap`s on REST paths. 3. **Graceful shutdown.** Handle SIGTERM and wire `with_graceful_shutdown`. 4. **Numeric output guards.** Not every value leaving the process is checked with `is_finite` (engine outputs, roxWarp feed). diff --git a/docs/research/16_ROXWARP_PROTOCOL.md b/docs/research/16_ROXWARP_PROTOCOL.md index a8c0807..83c80c5 100644 --- a/docs/research/16_ROXWARP_PROTOCOL.md +++ b/docs/research/16_ROXWARP_PROTOCOL.md @@ -3,7 +3,7 @@ > **Status (2026-11-18)**: audited against `master` `b48484b`. The protocol design below is kept as rationale; this block records what is on the wire today. Doc-by-doc report: [PROGRESS_REPORT_2026_11_18.md](PROGRESS_REPORT_2026_11_18.md). > > **Verdict:** the gossip skeleton runs (hello/welcome, delta, versions, deltaReq, full/fullReq, ack, query, heartbeat), but the designed binary-Trio wire format, string table, join/leave messages and the Fantom pod are not on the wire or in the repo. About 45% implemented. -> - **Implemented:** `/roxwarp` WebSocket with MessagePack binary frames and a `?debug=trio` text mode (`crates/sandstar-server/src/roxwarp/handler.rs`, `peer.rs`); version-vector delta, anti-entropy and deltaReq; last-writer-wins by timestamp; backoff reconnect; distributed query; optional mTLS; cluster timer validation, 1..=86400 s (R-39). +> - **Implemented:** `/roxwarp` WebSocket with MessagePack binary frames and a `?debug=trio` text mode (`crates/sandstar-server/src/roxwarp/handler.rs`, `peer.rs`); version-vector delta, anti-entropy and deltaReq; last-writer-wins by timestamp; backoff reconnect; distributed query; mTLS, fail-closed since S-36 (plain WS only with `--cluster-insecure`, R-54); cluster timer validation, 1..=86400 s (R-39). > - **Done differently:** the wire carries `rmp_serde::to_vec` of a private `handler::WarpMessage`. Points are `{channel: u32, value: f64, unit, status, version, timestamp}` (`crates/sandstar-server/src/roxwarp/cluster.rs`), not typed Haystack values. Debug mode sends JSON text, not Trio. Deltas are pushed on each heartbeat tick (5 s by default), not immediately. > - **Not done / open:** typed ext-code binary Trio and the string table (`binary_trio.rs`, `string_table.rs` and `protocol.rs` exist but are unused on the wire, R-27; the parallel `delta.rs` engine was removed on 2026-11-19, S-15); `warp:join`/`warp:leave`; capabilities and load metrics; `roxwarp.v1` subprotocol; node-id tie-break; the Fantom `bassgRoxWarp` pod; certificate-bound node identity. > - **Superseded by:** [`../Progress/ROADMAP_v2.md`](../Progress/ROADMAP_v2.md) Phase 9.0. Its "9.0a binary Trio COMPLETE" overstates what goes over the wire. @@ -11,7 +11,7 @@ > - **Peer timestamps and versions (R-27, 2026-11-19):** a point timestamp more than 5 min ahead of the local clock is rejected (`MAX_PEER_FUTURE_SKEW_MS`, rate-limited warn), so `i64::MAX` no longer pins a channel; a peer whose clock runs fast is not applied until its clock is fixed. Storing such points with the receive time was rejected: each re-delivery of a stale value would then beat newer ones. What we have seen from each peer (the sender's `toVersion`, advertised in the version vector; point versions are not used because relayed points carry other nodes' counters) and what each peer acknowledged of ours are kept apart; before, a peer's own counter was read as "the peer has our data up to N", so after a reconnect the initial delta could be empty. The server now starts the initial delta from the `hello` version vector, like the client does from `welcome`. Version counters start at 0 on every start and have no epoch: a peer claim above our counter means we restarted, and everything is resent (`resync_from`). Past-dated peer points still always lose, `node_id` is still peer-claimed, and message size is still unbounded. Point filters (`query`, `/api/cluster/query`) are split on `and`/`or` by byte offset (R-7) and evaluated at most 32 levels deep (S-24, 2026-11-20); terms past that do not match. So `/api/cluster/query` can show `Fault` while `/api/read` shows `Ok` for a channel whose value is NaN. Code: `crates/sandstar-server/src/roxwarp/cluster.rs` `feed_decision`, `record_change`, `apply_remote_delta`. > > **Known inaccuracies in the text below** (section: current fact): -> - *Protocol Naming*, *5.1 WebSocket Frame Types*: TLS is optional (fails open) and `/roxwarp` is also served in plain text on :8085. There is no subprotocol and no `warp:leave`; debug frames are JSON. +> - *Protocol Naming*, *5.1 WebSocket Frame Types*: TLS is required unless `--cluster-insecure` is given; a broken mTLS setup turns the cluster network off instead of falling back (S-36). `/roxwarp` is served in plain text on :8085 only with `--cluster-insecure`. There is no subprotocol and no `warp:leave`; debug frames are JSON. > - *2.1 Overview* (type codes, "MessagePack map with a `type` key"): no ext codes on the wire. `rmp_serde::to_vec` encodes structs as positional arrays, which matters for any non-Rust peer (crate behaviour; not verified on the wire). > - *3.2 Versioned Point State*: `channel` is `u32`, `value` is `f64`; fields are `unit`, `status`, `version`, `timestamp`. > - *2.5 String Table Optimization*: not negotiated; the wire `Hello` has only `nodeId` and `versions`.