diff --git a/.claude/rules/routes-auth.md b/.claude/rules/routes-auth.md index c78c81e..cd5e2f7 100644 --- a/.claude/rules/routes-auth.md +++ b/.claude/rules/routes-auth.md @@ -11,7 +11,8 @@ paths: Bugünkü durum: üretim servisi `0.0.0.0` üzerinde ve auth'suz çalışıyor (R-1). Birçok yazma rotası auth katmanından **sonra** merge edildiği için korumasız (R-2). Auth modeli henüz karara bağlanmadı (Q-4, S-3). Bu kurallar durumu daha da kötüleştirmemek içindir. ## Yeni veya değişen rota -- Rotanın auth katmanının **içinde mi dışında mı** olduğu açıkça belirlenir ve commit mesajında yazılır. axum'da `.layer(...)` yalnız kendisinden önce eklenen rotaları sarar. Layer'dan sonra yapılan `.merge(...)` / `.route(...)` korumasız kalır. Örnekler: `crates/sandstar-server/src/rest/mod.rs:855-868`, `crates/sandstar-server/src/main.rs:600-610`. +- Rotanın auth katmanının **içinde mi dışında mı** olduğu açıkça belirlenir ve commit mesajında yazılır. axum'da `.layer(...)` yalnız kendisinden önce eklenen rotaları sarar. Layer'dan sonra yapılan `.merge(...)` / `.route(...)` korumasız kalır. Örnek: `rest/mod.rs` `require_auth` / `require_upgrade_auth`. +- Global katmanlar (sayaç, rate limit, body limit, CORS) `rest::with_global_layers` ile **en son** uygulanır. Yeni bir router `main.rs`'de bu çağrıdan önce birleştirilir; sonra birleştirilen router bu katmanların dışında kalır (R-53, S-35). - Durum değiştiren uçlar (yazma, silme, config, dosya, alarm/SMTP ayarı) varsayılan olarak auth içinde olmalı. Dışarıda kalacaksa gerekçesi kodda yorumla yazılır. - Kimlik bilgisi ve token URL query'sine konmaz (R-14). Token karşılaştırması sabit zamanlı yapılır. - GET yanıtlarında sır alanları maskelenir (örnek: `crates/sandstar-server/src/alerts.rs`). diff --git a/.gitignore b/.gitignore index be244b6..7ffb4f0 100644 --- a/.gitignore +++ b/.gitignore @@ -56,5 +56,6 @@ server_stderr.log /tools/xeto/checkXetoFiles.sh # Local tool output +/tools/editor-dev.env /.playwright-mcp/ /editor_connected.png diff --git a/HowToUses/02_REST_API.md b/HowToUses/02_REST_API.md index 54c5987..853d471 100644 --- a/HowToUses/02_REST_API.md +++ b/HowToUses/02_REST_API.md @@ -58,6 +58,7 @@ curl http://localhost:8085/api/diagnostics ```bash # Full component tree curl http://localhost:8085/api/sox/tree +# With auth on (S-33): add -H "Authorization: Bearer " # Single component with slots and links curl http://localhost:8085/api/sox/comp/200 diff --git a/HowToUses/03_WEB_EDITOR.md b/HowToUses/03_WEB_EDITOR.md index 97809ca..24893f1 100644 --- a/HowToUses/03_WEB_EDITOR.md +++ b/HowToUses/03_WEB_EDITOR.md @@ -5,6 +5,25 @@ http://:8085/editor ``` +## Vue editor against a real device (development) + +The Vue Sedona editor (`sedonaWebEditor`, branch `trkrDevelop`) runs from its +dev server and proxies `/live`, `/api`, `/file` to a device: + +```bash +# Device address: argument, SANDSTAR_DEVICE, or tools/editor-dev.env +# (git-ignored; one line SANDSTAR_DEVICE=) +bash tools/editor-dev.sh [device[:port]] +``` + +The script checks the device (`/api/about`, whether the editor gate asks for +a login) and starts the editor at `http://localhost:8091/`. Add a connection +with the device user; leave `peer` empty (it defaults to the page origin). +With auth on, the device needs `--ws-allowed-origins http://localhost:8091`: +the editor's WebSockets, tree and file reads, and kit uploads (`PUT /file/*`) +use the session cookie from the login and are checked against the page origin. +Edits in the editor go to the running app on the device. + ## Layout - **Left sidebar**: Tree navigator (top) + Component palette (bottom) - **Center canvas**: Visual wire sheet (only user-added components) 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 4b26c9a..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"); + } } }); @@ -597,12 +587,12 @@ async fn main() -> Result<(), Box> { if !args.no_rest { let handle = EngineHandle::new(cmd_tx.clone()); let auth_state = sandstar_server::auth::AuthState::new(config.auth_store.clone()); - #[allow(unused_mut)] - let mut app = rest::router_with_auth( + // Core routes without the global layers; every router below is + // merged first and `with_global_layers` wraps them all (R-53, S-35). + let mut app = rest::api_routes( handle, auth_state.clone(), config.auth_token.clone(), - config.rate_limit, sox_api_state, ); @@ -629,6 +619,10 @@ async fn main() -> Result<(), Box> { app = app.merge(rest::sim::router(sim_state.clone(), auth_state.clone())); } + // Request counter, rate limit, body limit and CORS. Last step: a + // router merged after this line is outside those layers. + let app = rest::with_global_layers(app, config.rate_limit); + let addr: std::net::SocketAddr = format!("{}:{}", args.http_bind, args.http_port) .parse() diff --git a/crates/sandstar-server/src/rest/file_ops.rs b/crates/sandstar-server/src/rest/file_ops.rs index 6c66b1b..198dee1 100644 --- a/crates/sandstar-server/src/rest/file_ops.rs +++ b/crates/sandstar-server/src/rest/file_ops.rs @@ -60,7 +60,12 @@ pub fn resolve_file_root() -> Option { None } -/// `GET` stays public; `PUT` writes files and sits behind the auth layer (R-2). +/// `GET` sits behind the editor gate (bearer or session cookie, plus Origin; +/// R-55, S-33): the browser editor fetches kit files same-origin with its +/// cookie. `PUT` writes files and sits behind the write gate: bearer, or +/// session cookie with a required allowed `Origin` (R-56, S-37); the editor +/// uploads kits with its cookie. With no auth configured both pass every +/// request. pub fn router(state: SoxState, auth_state: crate::auth::AuthState) -> Router { let read = Router::new() .route("/file/{*path}", get(get_file)) @@ -68,7 +73,8 @@ pub fn router(state: SoxState, auth_state: crate::auth::AuthState) -> Router { let write = Router::new() .route("/file/{*path}", put(put_file)) .with_state(state); - read.merge(super::require_auth(write, auth_state)) + super::require_upgrade_auth(read, auth_state.clone()) + .merge(super::require_write_auth(write, auth_state)) } // ── Handlers ─────────────────────────────────────── diff --git a/crates/sandstar-server/src/rest/mod.rs b/crates/sandstar-server/src/rest/mod.rs index bd5f461..dd1fe1e 100644 --- a/crates/sandstar-server/src/rest/mod.rs +++ b/crates/sandstar-server/src/rest/mod.rs @@ -636,7 +636,8 @@ pub(crate) fn has_valid_credential( } /// Gate for the editor endpoints (`/live`, `/live/sedonaState`, -/// `/api/rows`), run before the WebSocket upgrade (R-52, S-32). +/// `/api/rows`), run before the WebSocket upgrade (R-52, S-32). It also +/// gates the SOX tree reads and `GET /file/*` (R-55, S-33). /// /// Browsers cannot send an `Authorization` header on an upgrade, so a /// session cookie from `POST /api/auth` is accepted too. With auth on, a @@ -659,6 +660,52 @@ pub(crate) async fn check_upgrade_auth( Err(StatusCode::UNAUTHORIZED) } +/// Gate for browser writes that cannot carry a bearer header: today only +/// `PUT /file/*`, used by the editor to upload kits (R-56, S-37). +/// +/// - auth not configured: every request passes (field default); +/// - valid bearer header: passes, `Origin` is not checked (same as +/// [`check_auth`]); +/// - valid session cookie: passes only with an `Origin` header that matches +/// the `Host` or the allowlist. A missing or foreign `Origin` gets 403. +/// Browsers always send `Origin` on `PUT`, so a cookie write without one +/// is not the editor. This backs up the cookie's `SameSite=Strict` +/// against cross-site request forgery; +/// - otherwise 401. +pub(crate) async fn check_write_auth( + axum::extract::State(auth_state): axum::extract::State, + request: Request, + next: middleware::Next, +) -> Result { + if !auth_state.store.is_auth_required() { + return Ok(next.run(request).await); + } + let headers = request.headers(); + let bearer = headers + .get(axum::http::header::AUTHORIZATION) + .and_then(|v| v.to_str().ok()) + .and_then(|v| v.strip_prefix("Bearer ")); + if bearer.is_some_and(|t| auth_state.check_token(t)) { + return Ok(next.run(request).await); + } + if session_cookies(headers).any(|t| auth_state.check_token(t)) { + // `origin_allowed` lets a request without `Origin` through (it is + // built for WebSocket clients); a cookie write must have one, so + // this check stays here and must not be dropped. + let has_origin = headers.contains_key(axum::http::header::ORIGIN); + if has_origin && origin_allowed(headers, &auth_state) { + return Ok(next.run(request).await); + } + return Err(StatusCode::FORBIDDEN); + } + Err(StatusCode::UNAUTHORIZED) +} + +/// Wrap every route already in `router` with [`check_write_auth`]. +pub fn require_write_auth(router: Router, auth_state: AuthState) -> Router { + router.route_layer(middleware::from_fn_with_state(auth_state, check_write_auth)) +} + /// Wrap every route already in `router` with [`check_upgrade_auth`]. pub fn require_upgrade_auth(router: Router, auth_state: AuthState) -> Router { router.route_layer(middleware::from_fn_with_state( @@ -989,6 +1036,25 @@ pub fn router_with_auth( auth_token: Option, rate_limit: u64, sox_state: Option, +) -> Router { + with_global_layers( + api_routes(handle, auth_state, auth_token, sox_state), + rate_limit, + ) +} + +/// Build the core routes, each with its auth layer, without the global +/// layers. +/// +/// A caller that merges more routers (`main.rs`: tags, alerts, roxWarp, +/// simulator) merges them into this router and calls [`with_global_layers`] +/// last. A router merged after that call gets no rate limit, body limit or +/// CORS (R-53, S-35). +pub fn api_routes( + handle: EngineHandle, + auth_state: AuthState, + auth_token: Option, + sox_state: Option, ) -> Router { // Public read-only routes (no auth required) let public = Router::new() @@ -1028,26 +1094,6 @@ pub fn router_with_auth( .with_state(handle.clone()); let protected = require_auth(protected, auth_state.clone()); - // CORS policy: allow any origin (embedded device accessed by various IPs) - // but restrict methods and headers to only what we actually use. - // This is safer than CorsLayer::permissive() which allows arbitrary - // headers and methods. - let cors = CorsLayer::new() - .allow_origin(tower_http::cors::Any) - .allow_methods([ - Method::GET, - Method::POST, - Method::PUT, - Method::DELETE, - Method::OPTIONS, - ]) - .allow_headers([ - HeaderName::from_static("content-type"), - HeaderName::from_static("authorization"), - HeaderName::from_static("accept"), - ]) - .max_age(Duration::from_secs(3600)); - // Driver framework REST endpoints — backed by the async DriverHandle actor. // BACnet drivers (and future async drivers) are loaded from environment config // asynchronously in the background so they don't block router construction. @@ -1110,8 +1156,7 @@ pub fn router_with_auth( } let driver_routes = crate::drivers::driver_router(driver_handle, auth_state.clone()); - // Merge and apply global middleware. - // Layer order (axum applies bottom-up): CORS → body limit → rate limit → count. + // Global middleware is applied by `with_global_layers`, not here. let mut app = public .merge(protected) .merge(ws_route) @@ -1158,13 +1203,20 @@ pub fn router_with_auth( auth_state.clone(), ); // Phase 14.0G-5: editor `/library/` + `/tags` compatibility stubs. + // Left outside the gates on purpose: read-only stubs that return + // `[]` or library names, no device data (S-33). let library_route = library::router(live::LiveState { tree: sox.tree.clone(), manifest_db: sox.manifest_db.clone(), dyn_store: sox.dyn_store.clone(), }); app = app - .merge(sox_api::public_router(sox.clone())) + // Tree reads carry the same data as `/live/sedonaState`, so they + // sit behind the same gate (R-55, S-33). + .merge(require_upgrade_auth( + sox_api::public_router(sox.clone()), + auth_state.clone(), + )) .merge(require_auth( sox_api::protected_router(sox), auth_state.clone(), @@ -1180,8 +1232,37 @@ pub fn router_with_auth( // Phase 14.0G-7 skeleton: `/editor` is served by `editor_assets::router()`. // Returns the placeholder HTML when `SANDSTAR_WEB_DIR` is unset, or // mounts the built Vue SPA from that directory when set. - app = app.merge(editor_assets::router()); + app.merge(editor_assets::router()) +} + +/// Apply the global HTTP layers to every route merged so far: request +/// counter, rate limit (`rate_limit` requests per second, 0 = unlimited), +/// 1 MiB body limit and CORS. +/// +/// Call this once, after the last `.merge`; routes merged later are not +/// wrapped (R-53). +pub fn with_global_layers(app: Router, rate_limit: u64) -> Router { + // CORS policy: allow any origin (embedded device accessed by various IPs) + // but restrict methods and headers to only what we actually use. + // This is safer than CorsLayer::permissive() which allows arbitrary + // headers and methods. + let cors = CorsLayer::new() + .allow_origin(tower_http::cors::Any) + .allow_methods([ + Method::GET, + Method::POST, + Method::PUT, + Method::DELETE, + Method::OPTIONS, + ]) + .allow_headers([ + HeaderName::from_static("content-type"), + HeaderName::from_static("authorization"), + HeaderName::from_static("accept"), + ]) + .max_age(Duration::from_secs(3600)); + // Layer order (axum applies bottom-up): CORS → body limit → rate limit → count. let mut app = app.layer(middleware::from_fn(count_requests)); // Apply rate limiting only when configured (rate_limit > 0). @@ -1226,11 +1307,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/rest/sox_api.rs b/crates/sandstar-server/src/rest/sox_api.rs index 4c68bf4..d734be7 100644 --- a/crates/sandstar-server/src/rest/sox_api.rs +++ b/crates/sandstar-server/src/rest/sox_api.rs @@ -835,10 +835,10 @@ pub async fn get_names(State(state): State) -> Response { .into_response() } -/// Build the SOX API sub-router (public read + protected write routes). +/// Build the SOX API read sub-router. /// -/// The caller is responsible for merging these into the main app -/// and applying auth middleware to the write routes. +/// The caller wraps it with `require_upgrade_auth` (bearer or session +/// cookie; R-55, S-33) and the write routes with `require_auth`. pub fn public_router(state: SoxApiState) -> axum::Router { use axum::routing::get; axum::Router::new() 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 6c0a1c5..15c924b 100644 --- a/crates/sandstar-server/tests/auth_layer.rs +++ b/crates/sandstar-server/tests/auth_layer.rs @@ -6,6 +6,8 @@ //! - with the right token the request reaches the handler (not 401); //! - with no auth configured nothing gets 401 (field behavior unchanged). //! +//! The SOX tree and `/file/*` reads sit behind the editor gate (R-55, S-33). +//! //! Limitation: the route list is maintained by hand. A new write route that //! is not added to `WRITE_ROUTES` is not covered by this test. @@ -84,7 +86,6 @@ const READ_ROUTES: &[&str] = &[ "/api/about", "/api/read?filter=point", "/api/drivers", - "/api/sox/tree", "/api/tags", "/api/alerts/config", "/api/cluster/status", @@ -127,15 +128,17 @@ fn build_app(auth: AuthStore) -> (Router, tokio::task::JoinHandle<()>) { key_path: None, ca_path: None, enable_mdns: false, + allow_plain: false, }, sox_tree: None, }; - let app = rest::router_with_auth(handle, auth_state.clone(), None, 0, Some(sox_state)) + // Same order as `main.rs`: every router first, global layers last. + let app = rest::api_routes(handle, auth_state.clone(), None, Some(sox_state)) .merge(rest::tags::router(dyn_store, auth_state.clone())) .merge(alert_router(alerts, auth_state.clone())) .merge(rest::roxwarp_router(rw_state, auth_state)); - (app, cmd_task) + (rest::with_global_layers(app, 0), cmd_task) } async fn status( @@ -238,6 +241,247 @@ async fn an_empty_configured_token_does_not_open_write_routes() { } } +// ── SOX tree and file reads (R-55, S-33) ──────────────────── + +/// Reads that carry the component tree or device files: behind the editor +/// gate (bearer or session cookie, plus Origin). +/// Each entry is (path, status once the gate lets the request through); +/// exact so a route that is not mounted (404) cannot pass. `build_app` +/// unsets the file root, so `/file/*` answers 503 behind the gate. +const GATED_READS: &[(&str, StatusCode)] = &[ + ("/api/sox/tree", StatusCode::OK), + // The test tree is empty: the handler answers 404 for comp 0. + ("/api/sox/comp/0", StatusCode::NOT_FOUND), + ("/api/sox/palette", StatusCode::OK), + ("/api/sox/names", StatusCode::OK), + ( + "/file/sedona/manifests/x/x.xml", + StatusCode::SERVICE_UNAVAILABLE, + ), +]; + +async fn head_with(app: &Router, path: &str, headers: &[(&str, String)]) -> StatusCode { + let mut req = Request::builder().method("HEAD").uri(path); + for (k, v) in headers { + req = req.header(*k, v.as_str()); + } + let req = req.body(Body::empty()).unwrap(); + app.clone().oneshot(req).await.unwrap().status() +} + +async fn get_with(app: &Router, path: &str, headers: &[(&str, String)]) -> StatusCode { + let mut req = Request::builder().method("GET").uri(path); + for (k, v) in headers { + req = req.header(*k, v.as_str()); + } + let req = req.body(Body::empty()).unwrap(); + app.clone().oneshot(req).await.unwrap().status() +} + +#[tokio::test] +async fn tree_and_file_reads_need_a_credential_when_auth_is_configured() { + let (app, _task) = build_app(AuthStore::with_bearer_token(TOKEN.to_string())); + let cookie = || ("cookie", format!("a=b; sandstar_session={TOKEN}")); + for &(p, want) in GATED_READS { + assert_eq!( + head_with(&app, p, &[]).await, + StatusCode::UNAUTHORIZED, + "HEAD {p} none" + ); + assert_eq!( + get_with(&app, p, &[]).await, + StatusCode::UNAUTHORIZED, + "{p} none" + ); + let bad = [("cookie", "sandstar_session=nope".to_string())]; + assert_eq!( + get_with(&app, p, &bad).await, + StatusCode::UNAUTHORIZED, + "{p} bad cookie" + ); + let wrong = [("authorization", "Bearer nope".to_string())]; + assert_eq!( + get_with(&app, p, &wrong).await, + StatusCode::UNAUTHORIZED, + "{p} wrong" + ); + // Same-origin editor fetch: the browser may send an Origin equal to Host. + let same = vec![ + cookie(), + ("host", "dev.local:8091".to_string()), + ("origin", "http://dev.local:8091".to_string()), + ]; + for ok in [vec![cookie()], vec![bearer()], same] { + assert_eq!(get_with(&app, p, &ok).await, want, "{p} {ok:?}"); + } + for cred in [bearer(), cookie()] { + let evil = [cred, ("origin", "http://evil.example".to_string())]; + assert_eq!( + get_with(&app, p, &evil).await, + StatusCode::FORBIDDEN, + "{p} {evil:?}" + ); + } + } +} + +#[tokio::test] +async fn file_upload_accepts_a_cookie_only_with_an_allowed_origin() { + // R-56, S-37: the editor uploads kits with its session cookie. A cookie + // write needs an Origin header that matches the Host or the allowlist. + let mut store = AuthStore::with_bearer_token(TOKEN.to_string()); + store.set_allowed_origins(vec!["http://localhost:8091".to_string()]); + let (app, _task) = build_app(store); + let host = || ("host", "device.local".to_string()); + let cookie = || ("cookie", format!("a=b; sandstar_session={TOKEN}")); + let bad_cookie = || ("cookie", "sandstar_session=forged".to_string()); + let origin = |o: &str| ("origin", o.to_string()); + let bearer = || ("authorization", format!("Bearer {TOKEN}")); + // No file root in tests: a request that passes the gate gets 503. + let passed = StatusCode::SERVICE_UNAVAILABLE; + let cases: Vec<(&str, Vec<(&str, String)>, StatusCode)> = vec![ + ("none", vec![host()], StatusCode::UNAUTHORIZED), + ( + "forged cookie, same-host origin", + vec![host(), bad_cookie(), origin("http://device.local")], + StatusCode::UNAUTHORIZED, + ), + ( + "cookie, same-host origin", + vec![host(), cookie(), origin("http://device.local")], + passed, + ), + ( + "cookie, allowlisted origin", + vec![host(), cookie(), origin("http://localhost:8091")], + passed, + ), + ( + "cookie, no origin", + vec![host(), cookie()], + StatusCode::FORBIDDEN, + ), + ( + "cookie, foreign origin", + vec![host(), cookie(), origin("http://evil.example")], + StatusCode::FORBIDDEN, + ), + ( + "cookie, opaque origin", + vec![host(), cookie(), origin("null")], + StatusCode::FORBIDDEN, + ), + ( + "forged cookie before the valid one", + vec![ + host(), + ( + "cookie", + format!("sandstar_session=forged; sandstar_session={TOKEN}"), + ), + origin("http://device.local"), + ], + passed, + ), + ( + "valid cookie in a second Cookie header", + vec![ + host(), + bad_cookie(), + cookie(), + origin("http://device.local"), + ], + passed, + ), + ( + "cookie, same host other port", + vec![host(), cookie(), origin("http://device.local:8091")], + StatusCode::FORBIDDEN, + ), + ( + "cookie, subdomain origin", + vec![host(), cookie(), origin("http://a.device.local")], + StatusCode::FORBIDDEN, + ), + ( + "cookie, non-http scheme", + vec![host(), cookie(), origin("ftp://device.local")], + StatusCode::FORBIDDEN, + ), + ( + "cookie, origin differs only in case", + vec![host(), cookie(), origin("http://DEVICE.local")], + passed, + ), + ("bearer, no origin", vec![host(), bearer()], passed), + ( + "bearer, foreign origin", + vec![host(), bearer(), origin("http://evil.example")], + passed, + ), + ]; + for (name, headers, want) in cases { + let s = put_with(&app, "/file/s37-probe.txt", &headers).await; + assert_eq!(s, want, "{name}"); + } +} + +#[tokio::test] +async fn other_write_routes_still_reject_the_cookie() { + // Only `PUT /file/*` accepts the cookie; the rest stay bearer-only. + let (app, _task) = build_app(AuthStore::with_bearer_token(TOKEN.to_string())); + for (m, p, b) in WRITE_ROUTES { + if p.starts_with("/file/") { + continue; + } + let req = Request::builder() + .method(*m) + .uri(*p) + .header("host", "device.local") + .header("origin", "http://device.local") + .header("cookie", format!("sandstar_session={TOKEN}")) + .header("content-type", "application/json") + .body(Body::from(b.to_string())) + .unwrap(); + let s = app.clone().oneshot(req).await.unwrap().status(); + assert_eq!(s, StatusCode::UNAUTHORIZED, "{m} {p}"); + } +} + +#[tokio::test] +async fn file_upload_stays_open_when_auth_is_not_configured() { + let (app, _task) = build_app(AuthStore::new()); + let headers = [("origin", "http://evil.example".to_string())]; + let s = put_with(&app, "/file/s37-probe.txt", &headers).await; + assert_eq!(s, StatusCode::SERVICE_UNAVAILABLE); +} + +async fn put_with(app: &Router, path: &str, headers: &[(&str, String)]) -> StatusCode { + let mut req = Request::builder().method("PUT").uri(path); + for (k, v) in headers { + req = req.header(*k, v.as_str()); + } + let req = req.body(Body::from("x")).unwrap(); + app.clone().oneshot(req).await.unwrap().status() +} + +#[tokio::test] +async fn library_stubs_stay_open_when_auth_is_configured() { + let (app, _task) = build_app(AuthStore::with_bearer_token(TOKEN.to_string())); + for p in ["/library/", "/tags"] { + assert_eq!(get_with(&app, p, &[]).await, StatusCode::OK, "{p}"); + } +} + +#[tokio::test] +async fn tree_and_file_reads_stay_open_when_auth_is_not_configured() { + let (app, _task) = build_app(AuthStore::new()); + for &(p, want) in GATED_READS { + let evil = [("origin", "http://evil.example".to_string())]; + assert_eq!(get_with(&app, p, &evil).await, want, "{p}"); + } +} + // ── WebSocket and editor endpoints (R-52, S-32) ───────────── /// Editor endpoints gated before the WebSocket upgrade. diff --git a/crates/sandstar-server/tests/global_layers.rs b/crates/sandstar-server/tests/global_layers.rs new file mode 100644 index 0000000..66be7f0 --- /dev/null +++ b/crates/sandstar-server/tests/global_layers.rs @@ -0,0 +1,176 @@ +//! Global HTTP layers cover the late-merged routers (R-53, S-35). +//! +//! `main.rs` merges the tags, alerts and roxWarp routers into the core app. +//! The request counter, rate limit, 1 MiB body limit and CORS must wrap +//! those routes too, not only the routes built inside `rest`. +//! +//! Not covered here: the simulator router (`simulator-hal` feature only) and +//! `cluster_disabled_router` (merged instead of the roxWarp router when +//! clustering is off); both are merged at the same place in `main.rs`. + +use std::sync::{Arc, Mutex, RwLock}; + +use axum::body::Body; +use axum::http::{Request, StatusCode}; +use axum::Router; +use sandstar_server::alerts::{alert_router, AlertConfig, AlertManager}; +use sandstar_server::auth::{AuthState, AuthStore}; +use sandstar_server::rest::{self, EngineCmd, EngineHandle}; +use sandstar_server::roxwarp::cluster::{ClusterConfig, DeltaEngine}; +use sandstar_server::roxwarp::RoxWarpState; +use sandstar_server::sox::dyn_slots::DynSlotStore; +use tokio::sync::mpsc; +use tower::ServiceExt; + +#[allow(dead_code)] +mod common; + +const TOKEN: &str = "s35-test-token"; + +/// Late-merged GET routes that answer without a token. +const LATE_READS: &[&str] = &["/api/tags", "/api/alerts/active", "/api/cluster/status"]; + +fn build_app(rate_limit: u64) -> (Router, tokio::task::JoinHandle<()>) { + std::env::remove_var("SANDSTAR_WEB_DIR"); + let auth_state = AuthState::new(AuthStore::with_bearer_token(TOKEN.to_string())); + + let engine = common::setup_demo_engine(); + let (cmd_tx, cmd_rx) = mpsc::channel::(64); + let handle = EngineHandle::new(cmd_tx); + let cmd_task = common::spawn_cmd_loop(engine, cmd_rx); + + let dyn_store = Arc::new(RwLock::new(DynSlotStore::with_defaults())); + let alerts = Arc::new(Mutex::new(AlertManager::new(AlertConfig::default()))); + let rw_state = RoxWarpState { + delta_engine: Arc::new(DeltaEngine::new("s35".into())), + config: ClusterConfig { + node_id: "s35".to_string(), + port: 0, + peers: vec![], + heartbeat_interval_secs: 1, + anti_entropy_interval_secs: 10, + feed_interval_secs: 60, + cert_path: None, + key_path: None, + ca_path: None, + enable_mdns: false, + allow_plain: false, + }, + sox_tree: None, + }; + + // Same order as `main.rs`: every router first, global layers last. + let app = rest::api_routes(handle, auth_state.clone(), None, None) + .merge(rest::tags::router(dyn_store, auth_state.clone())) + .merge(alert_router(alerts, auth_state.clone())) + .merge(rest::roxwarp_router(rw_state, auth_state)); + (rest::with_global_layers(app, rate_limit), cmd_task) +} + +async fn get(app: &Router, path: &str) -> axum::response::Response { + let req = Request::builder() + .uri(path) + .header("origin", "http://example.test") + .body(Body::empty()) + .unwrap(); + app.clone().oneshot(req).await.unwrap() +} + +#[tokio::test] +async fn late_routes_are_rate_limited() { + for path in LATE_READS { + let (app, _task) = build_app(1); + let mut limited = 0; + // Five requests span at most two one-second windows, so at most two + // pass with a limit of one per second. + for _ in 0..5 { + if get(&app, path).await.status() == StatusCode::TOO_MANY_REQUESTS { + limited += 1; + } + } + assert!(limited >= 3, "{path}: only {limited} of 5 requests got 429"); + } +} + +#[tokio::test] +async fn late_write_routes_are_rate_limited_before_auth() { + // Token guessing on a late-merged write route hits the rate limit. + let (app, _task) = build_app(1); + let mut limited = 0; + for i in 0..5 { + let req = Request::builder() + .method("PUT") + .uri("/api/tags/1") + .header("authorization", format!("Bearer guess-{i}")) + .header("content-type", "application/json") + .body(Body::from("{}")) + .unwrap(); + let s = app.clone().oneshot(req).await.unwrap().status(); + if s == StatusCode::TOO_MANY_REQUESTS { + limited += 1; + } else { + assert_eq!(s, StatusCode::UNAUTHORIZED, "guess {i}"); + } + } + assert!(limited >= 3, "only {limited} of 5 guesses got 429"); +} + +#[tokio::test] +async fn late_write_routes_enforce_the_body_limit() { + let (app, _task) = build_app(0); + // Valid JSON over 1 MiB and under axum's 2 MiB default. + let big = format!("{{\"note\":\"{}\"}}", "x".repeat(1_536 * 1024)); + let req = Request::builder() + .method("PUT") + .uri("/api/tags/1") + .header("authorization", format!("Bearer {TOKEN}")) + .header("content-type", "application/json") + .body(Body::from(big)) + .unwrap(); + let s = app.oneshot(req).await.unwrap().status(); + assert_eq!(s, StatusCode::PAYLOAD_TOO_LARGE); +} + +#[tokio::test] +async fn late_routes_get_cors_headers() { + let (app, _task) = build_app(0); + for path in LATE_READS { + let res = get(&app, path).await; + assert_eq!(res.status(), StatusCode::OK, "{path}"); + assert_eq!( + res.headers() + .get("access-control-allow-origin") + .map(|v| v.as_bytes()), + Some(&b"*"[..]), + "{path}: no CORS header" + ); + } +} + +#[tokio::test] +async fn late_routes_answer_cors_preflight() { + let (app, _task) = build_app(0); + for (path, method) in [ + ("/api/alerts/config", "PUT"), + ("/api/tags/1", "PUT"), + ("/api/cluster/query", "POST"), + ] { + let req = Request::builder() + .method("OPTIONS") + .uri(path) + .header("origin", "http://example.test") + .header("access-control-request-method", method) + .header( + "access-control-request-headers", + "authorization,content-type", + ) + .body(Body::empty()) + .unwrap(); + let res = app.clone().oneshot(req).await.unwrap(); + assert_eq!(res.status(), StatusCode::OK, "{path}"); + assert!( + res.headers().contains_key("access-control-allow-methods"), + "{path}: preflight without allow-methods" + ); + } +} 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 3c6b082..ded0e03 100644 --- a/docs/Progress/HARDCODED_LIMITS.md +++ b/docs/Progress/HARDCODED_LIMITS.md @@ -3,7 +3,7 @@ > **Status (2026-11-18)**: re-checked against `master` `b48484b`. Most values are unchanged, but many line numbers moved. Search by constant name rather than trusting the `file:line` below. > > **Moved (same value):** -> - `MAX_PARSE_DEPTH` → `rest/filter.rs:115`; CORS max-age → `rest/mod.rs:748`; `ws.rs` constants → lines 29-33 (S-22). +> - `MAX_PARSE_DEPTH` → `rest/filter.rs:115`; CORS max-age → `rest/mod.rs:1217` (`with_global_layers`, S-35); `ws.rs` constants → lines 29-33 (S-22). > - `CONSECUTIVE_FAIL_THRESHOLD` → `engine.rs:42`. The code comment describes it as the count before the fail counter resets. > - `ERR_YIELD` / `ERR_RESTART` / `ERR_HIBERNATE` → `sandstar-svm/src/types.rs:72-74`. > - `args.rs`: rate limit line 75, port 53, bind 57. @@ -18,9 +18,10 @@ > - `CLIENT_TIMEOUT_SECS` also in `rest/live.rs` and `rest/rows.rs`. > - Driver write level 16, duration 30 s and poll interval 5 s (`drivers/loader.rs`). > - MQTT cache max age 600 s; BACnet discovery 2 s, COV renewal 240 s, foreign-device TTL 300 s, COV cache 600 s. -> - Request body limit 1 MB (`rest/mod.rs`); driver actor channel capacity 64. +> - 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. @@ -55,7 +56,7 @@ Audited: 2026-03-10 | Rate limit default | 100 req/s | `sandstar-server/src/args.rs` | 65 | **Configurable** — already via `--rate-limit` / `SANDSTAR_RATE_LIMIT`. | | HTTP port default | 8085 | `sandstar-server/src/args.rs` | 43 | **Configurable** — already via `--http-port` / `SANDSTAR_HTTP_PORT`. | | HTTP bind default | 127.0.0.1 | `sandstar-server/src/args.rs` | 47 | **Configurable** — already via `--http-bind` / `SANDSTAR_HTTP_BIND`. | -| CORS max-age | 3600s (1h) | `sandstar-server/src/rest/mod.rs` | 724 | **Document** — standard value. Keep hardcoded. | +| CORS max-age | 3600s (1h) | `sandstar-server/src/rest/mod.rs` | 1217 | **Document** — standard value. Keep hardcoded. | ## WebSocket diff --git a/docs/Progress/OVERVIEW.md b/docs/Progress/OVERVIEW.md index 0d079dc..ecd4ec2 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) | @@ -218,16 +218,17 @@ Router: `router_with_auth` in `crates/sandstar-server/src/rest/mod.rs`, plus rou | `GET /api/ws` | handshake | Haystack-over-WebSocket (JSON) with SCRAM inside the socket. With auth on (S-32): a foreign browser `Origin` gets 403; a bearer header, session cookie or the deprecated legacy `?token=` pre-authenticates, otherwise the client must send an `auth` message | | `GET /api/drivers`, `/api/drivers/{id}/status`, `/api/drivers/{id}/learn` | no | Driver listing | | `POST /api/drivers`, `DELETE /api/drivers/{id}`, `POST /api/drivers/{id}/open\|close\|ping\|message\|write`, `POST /api/syncCur` | **yes** | Driver lifecycle ([DRIVER_REST_API.md](DRIVER_REST_API.md)) | -| `GET /api/sox/tree`, `/api/sox/comp/{id}`, `/api/sox/palette`, `/api/sox/names` | no | SOX component tree (with `--sox`) | +| `GET /api/sox/tree`, `/api/sox/comp/{id}`, `/api/sox/palette`, `/api/sox/names` | **yes** (S-33, `check_upgrade_auth`) | SOX component tree (with `--sox`). Bearer or `sandstar_session` cookie, plus Origin check | | `POST/DELETE/PUT /api/sox/comp*`, `/api/sox/link` | **yes** (S-31) | SOX component edits (with `--sox`) | | `GET /api/rows`, `GET /live`, `GET /live/sedonaState` | **yes** (S-32, `check_upgrade_auth`) | Editor endpoints (with `--sox`). Accept `Authorization: Bearer` or the `sandstar_session` cookie from `POST /api/auth`; with auth on a browser `Origin` must be the same host or in `--ws-allowed-origins` (else 403). The editor does not log in yet (S-32b), so it cannot connect while auth is on | -| `GET /file/*`, `/library/`, `GET /tags` | no | File download and editor library stubs (with `--sox`) | -| `PUT /file/*` | **yes** (S-31) | File upload (with `--sox`) | +| `GET /file/*` | **yes** (S-33, `check_upgrade_auth`) | File download (with `--sox`); the editor fetches kit files same-origin with the session cookie | +| `/library/`, `GET /tags` | no | Editor library stubs (with `--sox`) | +| `PUT /file/*` | **yes** (S-31; `check_write_auth` since S-37) | File upload (with `--sox`). Bearer, or the session cookie with a required `Origin` that matches the `Host` or `--ws-allowed-origins` (missing or foreign `Origin`: 403); the editor uploads kits with its cookie. The other write routes stay bearer-only | | `GET /api/tags`, `/api/tags/stats`, `/api/tags/{comp_id}` | no | Dynamic tags (read) | | `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 | @@ -237,7 +238,9 @@ Router: `router_with_auth` in `crates/sandstar-server/src/rest/mod.rs`, plus rou - `--http-bind` defaults to `127.0.0.1`. ⚠ The packaged systemd unit passes `--http-bind 0.0.0.0` and configures no auth, so on the field device every route above is reachable on the LAN without credentials. - 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). +- 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). - On an engine timeout (R-28, S-21): @@ -312,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`. diff --git a/tools/editor-dev.sh b/tools/editor-dev.sh new file mode 100644 index 0000000..acde6d3 --- /dev/null +++ b/tools/editor-dev.sh @@ -0,0 +1,84 @@ +#!/usr/bin/env bash +# Start the Vue Sedona editor dev server against a real Sandstar device. +# +# The editor runs at http://localhost:/ and its dev proxy forwards +# /live, /api, /file and /auth to http://:8085 (vue.config.js, +# SOX_PROXY_URL). Same origin for the browser, so the S-32 session cookie +# works when auth is on. +# +# Usage: +# bash tools/editor-dev.sh [device[:port]] +# +# Device address, first match wins (host/IP is never written in the repo): +# 1. first argument; +# 2. SANDSTAR_DEVICE environment variable; +# 3. tools/editor-dev.env (git-ignored), a line: SANDSTAR_DEVICE= +# +# Optional environment: +# SEDONA_EDITOR_DIR editor checkout (default C:/Coding/swe/sedonaWebEditor) +# EDITOR_PORT dev server port (default 8091) +# +# With auth on, the device must allow this page origin: +# --ws-allowed-origins http://localhost: +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +ENV_FILE="${SCRIPT_DIR}/editor-dev.env" + +DEVICE="${1:-${SANDSTAR_DEVICE:-}}" +if [ -z "$DEVICE" ] && [ -f "$ENV_FILE" ]; then + DEVICE="$(sed -n 's/^SANDSTAR_DEVICE=//p' "$ENV_FILE" | tr -d '\r' | head -1)" +fi +if [ -z "$DEVICE" ]; then + echo "error: no device address. Pass it as an argument, set SANDSTAR_DEVICE," >&2 + echo " or write SANDSTAR_DEVICE= to ${ENV_FILE}" >&2 + exit 2 +fi +case "$DEVICE" in + *:*) TARGET="http://${DEVICE}" ;; + *) TARGET="http://${DEVICE}:8085" ;; +esac + +EDITOR_DIR="${SEDONA_EDITOR_DIR:-C:/Coding/swe/sedonaWebEditor}" +PORT="${EDITOR_PORT:-8091}" + +if [ ! -f "${EDITOR_DIR}/vue.config.js" ]; then + echo "error: editor not found at ${EDITOR_DIR} (set SEDONA_EDITOR_DIR)" >&2 + exit 2 +fi +if [ ! -d "${EDITOR_DIR}/node_modules" ]; then + echo "error: ${EDITOR_DIR}/node_modules missing; run 'npm ci' there first" >&2 + exit 2 +fi + +# Refuse to start a second server on the same port. +if curl -s -o /dev/null -m 2 "http://localhost:${PORT}/"; then + echo "error: something already answers on localhost:${PORT}" >&2 + exit 1 +fi + +echo "== device" +if ! about="$(curl -sf -m 5 "${TARGET}/api/about")"; then + echo "error: device not reachable (GET /api/about failed)" >&2 + exit 1 +fi +version="$(printf '%s' "$about" | grep -oE '2\.[0-9]+\.[0-9]+\+[0-9a-f]+' | head -1 || true)" +echo " version: ${version:-unknown}" +gate="$(curl -s -o /dev/null -m 5 -w '%{http_code}' -I "${TARGET}/live/sedonaState" || true)" +case "$gate" in + 200) echo " auth: off (editor gate open)" ;; + 401) echo " auth: on (log in with a Sandstar user)" ;; + *) echo " auth: unknown (HEAD /live/sedonaState -> ${gate})" ;; +esac + +echo "== editor" +branch="$(git -C "$EDITOR_DIR" branch --show-current 2>/dev/null || echo '?')" +commit="$(git -C "$EDITOR_DIR" log -1 --format=%h 2>/dev/null || echo '?')" +echo " ${EDITOR_DIR} (${branch} ${commit})" +echo " open http://localhost:${PORT}/ and add a connection with host localhost:${PORT}" +echo " this is a real device: edits in the editor go to the running app" +echo + +cd "$EDITOR_DIR" +export SOX_PROXY_URL="$TARGET" +exec npx vue-cli-service serve --port "$PORT"