diff --git a/crates/sandstar-server/src/alerts.rs b/crates/sandstar-server/src/alerts.rs index 06bfdc4..c097c04 100644 --- a/crates/sandstar-server/src/alerts.rs +++ b/crates/sandstar-server/src/alerts.rs @@ -539,17 +539,23 @@ use axum::routing::{delete, get, post, put}; use axum::{Json, Router}; /// Build the alert management router. -pub fn alert_router(manager: SharedAlertManager) -> Router { - Router::new() +/// +/// Reads are public (the SMTP password is masked); config changes, recipient +/// changes and the test e-mail sit behind the auth layer (R-2). +pub fn alert_router(manager: SharedAlertManager, auth_state: crate::auth::AuthState) -> Router { + let read = Router::new() .route("/api/alerts/config", get(get_config)) - .route("/api/alerts/config", put(put_config)) .route("/api/alerts/recipients", get(get_recipients)) - .route("/api/alerts/recipients", post(add_recipient)) - .route("/api/alerts/recipients/{email}", delete(remove_recipient)) .route("/api/alerts/active", get(get_active)) .route("/api/alerts/history", get(get_history)) + .with_state(manager.clone()); + let write = Router::new() + .route("/api/alerts/config", put(put_config)) + .route("/api/alerts/recipients", post(add_recipient)) + .route("/api/alerts/recipients/{email}", delete(remove_recipient)) .route("/api/alerts/test", post(send_test)) - .with_state(manager) + .with_state(manager); + read.merge(crate::rest::require_auth(write, auth_state)) } /// GET /api/alerts/config — view current alert config (password masked). diff --git a/crates/sandstar-server/src/args.rs b/crates/sandstar-server/src/args.rs index edf6634..e4735e5 100644 --- a/crates/sandstar-server/src/args.rs +++ b/crates/sandstar-server/src/args.rs @@ -71,6 +71,12 @@ pub struct ServerArgs { #[arg(long, env = "SANDSTAR_AUTH_PASS")] pub auth_pass: Option, + /// Extra browser origins allowed to open the editor WebSockets + /// (`/live`, `/api/rows`, `/api/ws`) when auth is on, comma separated, + /// e.g. `http://editor.local:8080`. Same-host origins are always allowed. + #[arg(long, env = "SANDSTAR_WS_ALLOWED_ORIGINS", value_delimiter = ',')] + pub ws_allowed_origins: Vec, + /// Maximum REST API requests per second (0 = unlimited). #[arg(long, env = "SANDSTAR_RATE_LIMIT", default_value_t = 100)] pub rate_limit: u64, diff --git a/crates/sandstar-server/src/auth.rs b/crates/sandstar-server/src/auth.rs index cc85bfb..ffe23af 100644 --- a/crates/sandstar-server/src/auth.rs +++ b/crates/sandstar-server/src/auth.rs @@ -83,12 +83,26 @@ impl StoredCredential { // ── Auth Store ───────────────────────────────────────────── +/// Compare two byte strings without an early exit on the first mismatch. +/// +/// The length is not hidden (a length mismatch returns at once), only the +/// position of the first differing byte. +pub(crate) fn constant_time_eq(a: &[u8], b: &[u8]) -> bool { + if a.len() != b.len() { + return false; + } + a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0 +} + /// Auth store holding all credentials and the legacy bearer token. #[derive(Debug, Clone, Default)] pub struct AuthStore { credentials: HashMap, /// Legacy bearer token (backward compat with --auth-token). bearer_token: Option, + /// Extra browser origins allowed on WebSocket upgrades (R-52, S-32). + /// Same-host origins are always allowed. + allowed_origins: Vec, } impl AuthStore { @@ -102,9 +116,26 @@ impl AuthStore { Self { credentials: HashMap::new(), bearer_token: Some(token), + allowed_origins: Vec::new(), } } + /// Set the extra origins allowed on WebSocket upgrades (`--ws-allowed-origins`). + /// Entries are compared case-insensitively, without a trailing slash. + pub fn set_allowed_origins(&mut self, origins: Vec) { + self.allowed_origins = origins + .into_iter() + .map(|o| o.trim().trim_end_matches('/').to_ascii_lowercase()) + .filter(|o| !o.is_empty()) + .collect(); + } + + /// Whether `origin` is in the configured allowlist. + pub fn is_origin_allowed(&self, origin: &str) -> bool { + let o = origin.trim().trim_end_matches('/').to_ascii_lowercase(); + self.allowed_origins.contains(&o) + } + /// Add a SCRAM user credential. pub fn add_user(&mut self, username: &str, password: &str) { let cred = StoredCredential::from_password(username, password); @@ -123,7 +154,13 @@ impl AuthStore { /// Check if a bearer token matches. pub fn check_bearer(&self, token: &str) -> bool { - self.bearer_token.as_deref() == Some(token) + match self.bearer_token.as_deref() { + // An empty configured token never matches: auth stays closed + // instead of accepting `Authorization: Bearer `. + Some("") => false, + Some(expected) => constant_time_eq(expected.as_bytes(), token.as_bytes()), + None => false, + } } /// Returns true if any auth mechanism is configured (bearer or SCRAM). diff --git a/crates/sandstar-server/src/config.rs b/crates/sandstar-server/src/config.rs index f04191f..c010263 100644 --- a/crates/sandstar-server/src/config.rs +++ b/crates/sandstar-server/src/config.rs @@ -49,6 +49,7 @@ impl ServerConfig { if let Some(ref token) = args.auth_token { auth_store.set_bearer_token(token.clone()); } + auth_store.set_allowed_origins(args.ws_allowed_origins.clone()); // SCRAM auth: --auth-user + --auth-pass match (&args.auth_user, &args.auth_pass) { diff --git a/crates/sandstar-server/src/drivers/mod.rs b/crates/sandstar-server/src/drivers/mod.rs index 6ec68e4..4d6696e 100644 --- a/crates/sandstar-server/src/drivers/mod.rs +++ b/crates/sandstar-server/src/drivers/mod.rs @@ -509,7 +509,6 @@ pub fn driver_router( handle: crate::drivers::actor::DriverHandle, auth_state: crate::auth::AuthState, ) -> axum::Router { - use axum::middleware; use axum::routing::{delete, get, post}; let public = axum::Router::new() @@ -527,11 +526,8 @@ pub fn driver_router( .route("/api/drivers/{id}/message", post(driver_message_async)) .route("/api/drivers/{id}/write", post(driver_write_async)) .route("/api/syncCur", post(sync_cur_async)) - .route_layer(middleware::from_fn_with_state( - auth_state, - crate::rest::check_auth, - )) .with_state(handle); + let protected = crate::rest::require_auth(protected, auth_state); public.merge(protected) } diff --git a/crates/sandstar-server/src/main.rs b/crates/sandstar-server/src/main.rs index c6ba535..4b26c9a 100644 --- a/crates/sandstar-server/src/main.rs +++ b/crates/sandstar-server/src/main.rs @@ -526,6 +526,10 @@ async fn main() -> Result<(), Box> { use axum::routing::get; use axum::Router; + // 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). let cluster_app = Router::new() .route( "/roxwarp", @@ -596,21 +600,24 @@ async fn main() -> Result<(), Box> { #[allow(unused_mut)] let mut app = rest::router_with_auth( handle, - auth_state, + auth_state.clone(), config.auth_token.clone(), config.rate_limit, sox_api_state, ); // Merge dynamic tags REST endpoints - app = app.merge(rest::tags::router(dyn_store.clone())); + app = app.merge(rest::tags::router(dyn_store.clone(), auth_state.clone())); // Merge alert management REST endpoints - app = app.merge(alerts::alert_router(alert_manager.clone())); + app = app.merge(alerts::alert_router( + alert_manager.clone(), + auth_state.clone(), + )); // Merge roxWarp cluster endpoints (WebSocket + status API) if let Some(ref rw_state) = roxwarp_state { - app = app.merge(rest::roxwarp_router(rw_state.clone())); + app = app.merge(rest::roxwarp_router(rw_state.clone(), auth_state.clone())); } else { // Always provide /api/cluster/status even when clustering is off app = app.merge(rest::cluster_disabled_router()); @@ -619,7 +626,7 @@ async fn main() -> Result<(), Box> { // Merge simulator REST endpoints when built with simulator-hal #[cfg(feature = "simulator-hal")] { - app = app.merge(rest::sim::router(sim_state.clone())); + app = app.merge(rest::sim::router(sim_state.clone(), auth_state.clone())); } let addr: std::net::SocketAddr = diff --git a/crates/sandstar-server/src/rest/file_ops.rs b/crates/sandstar-server/src/rest/file_ops.rs index 7b319d4..6c66b1b 100644 --- a/crates/sandstar-server/src/rest/file_ops.rs +++ b/crates/sandstar-server/src/rest/file_ops.rs @@ -28,7 +28,7 @@ use axum::body::Bytes; use axum::extract::{Path as AxumPath, State}; use axum::http::{header, StatusCode}; use axum::response::{IntoResponse, Response}; -use axum::routing::get; +use axum::routing::{get, put}; use axum::Router; use tokio::fs; use tracing::{debug, warn}; @@ -60,10 +60,15 @@ pub fn resolve_file_root() -> Option { None } -pub fn router(state: SoxState) -> Router { - Router::new() - .route("/file/{*path}", get(get_file).put(put_file)) - .with_state(state) +/// `GET` stays public; `PUT` writes files and sits behind the auth layer (R-2). +pub fn router(state: SoxState, auth_state: crate::auth::AuthState) -> Router { + let read = Router::new() + .route("/file/{*path}", get(get_file)) + .with_state(state.clone()); + let write = Router::new() + .route("/file/{*path}", put(put_file)) + .with_state(state); + read.merge(super::require_auth(write, auth_state)) } // ── Handlers ─────────────────────────────────────── diff --git a/crates/sandstar-server/src/rest/mod.rs b/crates/sandstar-server/src/rest/mod.rs index 8478b93..bd5f461 100644 --- a/crates/sandstar-server/src/rest/mod.rs +++ b/crates/sandstar-server/src/rest/mod.rs @@ -574,6 +574,108 @@ pub(crate) async fn check_auth( Err(StatusCode::UNAUTHORIZED) } +/// Name of the session cookie set after a successful SCRAM login (S-32). +pub const SESSION_COOKIE: &str = "sandstar_session"; + +/// Every `sandstar_session` value in the `Cookie` header(s). +/// +/// All values are returned, not only the first: a stale or planted cookie +/// with the same name must not hide a valid one. +fn session_cookies(headers: &axum::http::HeaderMap) -> impl Iterator { + headers + .get_all(axum::http::header::COOKIE) + .iter() + .filter_map(|v| v.to_str().ok()) + .flat_map(|v| v.split(';')) + .filter_map(|kv| { + let (k, v) = kv.trim().split_once('=')?; + (k == SESSION_COOKIE).then_some(v) + }) +} + +/// Whether the request's `Origin` may open a WebSocket. +/// +/// No `Origin` header means a non-browser client: allowed (it still needs +/// a credential). A browser origin must match the `Host` header or the +/// configured allowlist; this blocks cross-site WebSocket hijacking. +pub(crate) fn origin_allowed(headers: &axum::http::HeaderMap, auth_state: &AuthState) -> bool { + let Some(origin) = headers.get(axum::http::header::ORIGIN) else { + return true; + }; + let Ok(origin) = origin.to_str() else { + return false; + }; + if auth_state.store.is_origin_allowed(origin) { + return true; + } + let host = headers + .get(axum::http::header::HOST) + .and_then(|h| h.to_str().ok()); + let origin_host = origin + .strip_prefix("http://") + .or_else(|| origin.strip_prefix("https://")); + match (origin_host, host) { + (Some(o), Some(h)) => o.trim_end_matches('/').eq_ignore_ascii_case(h), + _ => false, + } +} + +/// Whether the request carries a valid bearer header or session cookie. +pub(crate) fn has_valid_credential( + headers: &axum::http::HeaderMap, + auth_state: &AuthState, +) -> bool { + 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 true; + } + session_cookies(headers).any(|t| auth_state.check_token(t)) +} + +/// Gate for the editor endpoints (`/live`, `/live/sedonaState`, +/// `/api/rows`), run before the WebSocket upgrade (R-52, S-32). +/// +/// Browsers cannot send an `Authorization` header on an upgrade, so a +/// session cookie from `POST /api/auth` is accepted too. With auth on, a +/// foreign `Origin` gets 403 and a missing or bad credential gets 401. +/// With no auth configured every request passes (field default). +pub(crate) async fn check_upgrade_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); + } + if !origin_allowed(request.headers(), &auth_state) { + return Err(StatusCode::FORBIDDEN); + } + if has_valid_credential(request.headers(), &auth_state) { + return Ok(next.run(request).await); + } + Err(StatusCode::UNAUTHORIZED) +} + +/// 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( + auth_state, + check_upgrade_auth, + )) +} + +/// Wrap every route already in `router` with [`check_auth`]. +/// +/// `route_layer` only covers routes added before it, so build the router +/// first and wrap it last. With no auth configured, `check_auth` lets every +/// request through, so behavior is unchanged until auth is turned on (R-2). +pub fn require_auth(router: Router, auth_state: AuthState) -> Router { + router.route_layer(middleware::from_fn_with_state(auth_state, check_auth)) +} + // ── SCRAM Auth Endpoint ───────────────────────────────────── /// JSON request/response types for the /api/auth SCRAM endpoint. @@ -749,14 +851,25 @@ fn handle_scram_final(auth_state: &AuthState, handshake_token: &str, data_b64: & }; match auth_state.complete_scram(handshake_token, &client_final) { - Ok((session_token, server_sig)) => ( - StatusCode::OK, - Json(AuthTokenResponse { - auth_token: session_token, - data: server_sig, - }), - ) - .into_response(), + Ok((session_token, server_sig)) => { + // Browsers cannot send a header on a WebSocket upgrade; the + // cookie carries the session to /live and /api/rows (S-32). + // No `Secure` flag: the device serves plain HTTP (R-14). + let cookie = + format!("{SESSION_COOKIE}={session_token}; HttpOnly; SameSite=Strict; Path=/"); + let mut resp = ( + StatusCode::OK, + Json(AuthTokenResponse { + auth_token: session_token, + data: server_sig, + }), + ) + .into_response(); + if let Ok(v) = axum::http::HeaderValue::from_str(&cookie) { + resp.headers_mut().insert(axum::http::header::SET_COOKIE, v); + } + resp + } Err(e) => ( StatusCode::UNAUTHORIZED, Json(AuthErrorResponse { error: e }), @@ -912,11 +1025,8 @@ pub fn router_with_auth( .route("/api/hisRead", post(handlers::his_read)) .route("/api/nav", post(handlers::nav)) .route("/api/invokeAction", post(handlers::invoke_action)) - .route_layer(middleware::from_fn_with_state( - auth_state.clone(), - check_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. @@ -1018,6 +1128,7 @@ pub fn router_with_auth( manifest_db: sox.manifest_db.clone(), dyn_store: sox.dyn_store.clone(), }); + let rows_route = require_upgrade_auth(rows_route, auth_state.clone()); // Phase 14.0G-2c: Fantom-dialect SOX over WebSocket for the // Vue web editor. Shares state with /api/rows; both endpoints // dispatch through crate::sox::sox_ops. @@ -1031,17 +1142,21 @@ pub fn router_with_auth( manifest_db: sox.manifest_db.clone(), dyn_store: sox.dyn_store.clone(), }); + let live_route = require_upgrade_auth(live_route, auth_state.clone()); // Make the DynSlotStore available as an Extension so that the // Haystack filter evaluator in /api/read can check dynamic tags. if let Some(ref ds) = sox.dyn_store { app = app.layer(axum::Extension(ds.clone())); } // Phase 14.0G-4: file transfer (GET/PUT /file/*path). - let file_route = file_ops::router(live::LiveState { - tree: sox.tree.clone(), - manifest_db: sox.manifest_db.clone(), - dyn_store: sox.dyn_store.clone(), - }); + let file_route = file_ops::router( + live::LiveState { + tree: sox.tree.clone(), + manifest_db: sox.manifest_db.clone(), + dyn_store: sox.dyn_store.clone(), + }, + auth_state.clone(), + ); // Phase 14.0G-5: editor `/library/` + `/tags` compatibility stubs. let library_route = library::router(live::LiveState { tree: sox.tree.clone(), @@ -1050,7 +1165,13 @@ pub fn router_with_auth( }); app = app .merge(sox_api::public_router(sox.clone())) - .merge(sox_api::protected_router(sox)) + .merge(require_auth( + sox_api::protected_router(sox), + auth_state.clone(), + )) + // `/live`, `/live/sedonaState` and `/api/rows` sit behind + // `check_upgrade_auth` (bearer header or session cookie, plus an + // Origin check; S-32). `/library/` and `/tags` are read-only. .merge(rows_route) .merge(live_route) .merge(file_route) @@ -1102,19 +1223,26 @@ async fn cluster_disabled_handler() -> impl IntoResponse { /// - `GET /roxwarp` — WebSocket upgrade for peer gossip /// - `GET /api/cluster/status` — cluster overview (JSON) /// - `POST /api/cluster/query` — distributed Haystack filter query -pub fn roxwarp_router(state: crate::roxwarp::RoxWarpState) -> Router { +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()); - let api_routes = Router::new() + let status_route = Router::new() .route("/api/cluster/status", get(cluster_status_handler)) - .route("/api/cluster/query", post(cluster_query_handler)) - .with_state(state); - - ws_route.merge(api_routes) + .with_state(state.clone()); + let query_route = require_auth( + Router::new() + .route("/api/cluster/query", post(cluster_query_handler)) + .with_state(state), + auth_state, + ); + + ws_route.merge(status_route).merge(query_route) } /// GET /api/cluster/status — return cluster status as JSON. diff --git a/crates/sandstar-server/src/rest/sim.rs b/crates/sandstar-server/src/rest/sim.rs index dd6f92b..d576c58 100644 --- a/crates/sandstar-server/src/rest/sim.rs +++ b/crates/sandstar-server/src/rest/sim.rs @@ -299,18 +299,27 @@ fn apply_inject_point(s: &mut sandstar_hal::simulator::SimState, point: InjectPo /// - `GET /api/sim/outputs` — drain engine writes /// - `GET /api/sim/state` — read state summary /// - `POST /api/sim/scenario` — run timed injection sequence -pub fn router(state: SharedSimState) -> Router { - Router::new() - .route("/api/sim/inject", post(inject_handler)) - .route("/api/sim/outputs", get(outputs_handler)) +/// +/// `inject` and `scenario` change engine inputs, and `outputs` drains the +/// recorded writes; all three sit behind the auth layer (R-2). +pub fn router(state: SharedSimState, auth_state: crate::auth::AuthState) -> Router { + let read = Router::new() .route("/api/sim/state", get(state_handler)) + .with_state(state.clone()); + let write = Router::new() + .route("/api/sim/outputs", get(outputs_handler)) + .route("/api/sim/inject", post(inject_handler)) .route("/api/sim/scenario", post(scenario_handler)) - .with_state(state) + .with_state(state); + read.merge(super::require_auth(write, auth_state)) } #[cfg(test)] mod tests { use super::*; + fn no_auth() -> crate::auth::AuthState { + crate::auth::AuthState::new(crate::auth::AuthStore::new()) + } use axum::body::Body; use axum::http::{Request, StatusCode}; use sandstar_hal::simulator::SimState; @@ -324,7 +333,7 @@ mod tests { #[tokio::test] async fn test_inject_analog() { let state = test_state(); - let app = router(state.clone()); + let app = router(state.clone(), no_auth()); let body = serde_json::json!({ "points": [ @@ -367,7 +376,7 @@ mod tests { #[tokio::test] async fn test_inject_digital() { let state = test_state(); - let app = router(state.clone()); + let app = router(state.clone(), no_auth()); let body = serde_json::json!({ "points": [ @@ -395,7 +404,7 @@ mod tests { #[tokio::test] async fn test_inject_i2c() { let state = test_state(); - let app = router(state.clone()); + let app = router(state.clone(), no_auth()); let body = serde_json::json!({ "points": [ @@ -428,7 +437,7 @@ mod tests { #[tokio::test] async fn test_inject_mixed_types() { let state = test_state(); - let app = router(state.clone()); + let app = router(state.clone(), no_auth()); let body = serde_json::json!({ "points": [ @@ -484,7 +493,7 @@ mod tests { s.digital_reads.insert(45, true); } - let app = router(state.clone()); + let app = router(state.clone(), no_auth()); let resp = app .oneshot( Request::builder() @@ -519,7 +528,7 @@ mod tests { ); } - let app = router(state.clone()); + let app = router(state.clone(), no_auth()); let resp = app .oneshot( Request::builder() @@ -555,7 +564,7 @@ mod tests { ); } - let app = router(state.clone()); + let app = router(state.clone(), no_auth()); let body = serde_json::json!({ "points": [ {"type": "analog", "device": 0, "address": 0, "value": 2000.0} @@ -590,7 +599,7 @@ mod tests { #[tokio::test] async fn test_inject_empty_points() { let state = test_state(); - let app = router(state.clone()); + let app = router(state.clone(), no_auth()); let body = serde_json::json!({ "points": [] }); let resp = app @@ -614,7 +623,7 @@ mod tests { #[tokio::test] async fn test_scenario_returns_started() { let state = test_state(); - let app = router(state.clone()); + let app = router(state.clone(), no_auth()); let body = serde_json::json!({ "steps": [ @@ -651,7 +660,7 @@ mod tests { #[tokio::test] async fn test_scenario_executes_steps() { let state = test_state(); - let app = router(state.clone()); + let app = router(state.clone(), no_auth()); let body = serde_json::json!({ "steps": [ @@ -697,7 +706,7 @@ mod tests { #[tokio::test] async fn test_bad_json_returns_error() { let state = test_state(); - let app = router(state.clone()); + let app = router(state.clone(), no_auth()); let resp = app .oneshot( diff --git a/crates/sandstar-server/src/rest/tags.rs b/crates/sandstar-server/src/rest/tags.rs index c680c09..b2b44b3 100644 --- a/crates/sandstar-server/src/rest/tags.rs +++ b/crates/sandstar-server/src/rest/tags.rs @@ -12,7 +12,7 @@ use axum::extract::{Json, Path, Query, State}; use axum::http::StatusCode; use axum::response::{IntoResponse, Response}; -use axum::routing::{delete, get}; +use axum::routing::{delete, get, put}; use axum::Router; use serde::Deserialize; use std::collections::HashMap; @@ -48,16 +48,18 @@ pub fn json_to_dynvalue(val: &serde_json::Value) -> DynValue { /// Build the tags sub-router. /// -/// All routes are public (read) or protected (write) depending on how they -/// are merged into the main app. The caller is responsible for applying -/// auth middleware. -pub fn router(store: DynSlotStoreHandle) -> Router { - Router::new() +/// Reads are public; `PUT` and `DELETE` sit behind the auth layer (R-2). +pub fn router(store: DynSlotStoreHandle, auth_state: crate::auth::AuthState) -> Router { + let read = Router::new() .route("/api/tags", get(list_tags)) .route("/api/tags/stats", get(get_stats)) - .route("/api/tags/{comp_id}", get(get_tags).put(set_tags)) + .route("/api/tags/{comp_id}", get(get_tags)) + .with_state(store.clone()); + let write = Router::new() + .route("/api/tags/{comp_id}", put(set_tags)) .route("/api/tags/{comp_id}/{key}", delete(delete_tag)) - .with_state(store) + .with_state(store); + read.merge(super::require_auth(write, auth_state)) } /// GET /api/tags — list all components that have dynamic tags. @@ -238,6 +240,10 @@ mod tests { use std::sync::{Arc, RwLock}; use tower::ServiceExt; + fn no_auth() -> crate::auth::AuthState { + crate::auth::AuthState::new(crate::auth::AuthStore::new()) + } + fn test_store() -> DynSlotStoreHandle { Arc::new(RwLock::new( crate::sox::dyn_slots::DynSlotStore::with_defaults(), @@ -246,7 +252,7 @@ mod tests { #[tokio::test] async fn list_tags_empty() { - let app = router(test_store()); + let app = router(test_store(), no_auth()); let resp = app .oneshot(Request::get("/api/tags").body(Body::empty()).unwrap()) .await @@ -265,7 +271,7 @@ mod tests { #[tokio::test] async fn put_and_get_tags() { let store = test_store(); - let app = router(store.clone()); + let app = router(store.clone(), no_auth()); // PUT tags let body = serde_json::json!({ @@ -318,7 +324,7 @@ mod tests { s.set(10, "foo".into(), DynValue::Marker).unwrap(); s.set(10, "bar".into(), DynValue::Int(42)).unwrap(); } - let app = router(store.clone()); + let app = router(store.clone(), no_auth()); let resp = app .clone() @@ -347,7 +353,7 @@ mod tests { #[tokio::test] async fn delete_nonexistent_tag() { - let app = router(test_store()); + let app = router(test_store(), no_auth()); let resp = app .oneshot( Request::delete("/api/tags/10/nope") @@ -373,7 +379,7 @@ mod tests { let mut s = store.write().unwrap(); s.set(10, "old".into(), DynValue::Marker).unwrap(); } - let app = router(store.clone()); + let app = router(store.clone(), no_auth()); let body = serde_json::json!({ "_replace": true, @@ -398,7 +404,7 @@ mod tests { #[tokio::test] async fn put_tags_plain_json_auto_converts() { let store = test_store(); - let app = router(store.clone()); + let app = router(store.clone(), no_auth()); // Plain JSON values auto-convert: string→Str, number→Int/Float, bool→Bool let body = serde_json::json!({ "name": "Wall Temp", @@ -432,7 +438,7 @@ mod tests { s.set(20, "b".into(), DynValue::Marker).unwrap(); s.set(20, "c".into(), DynValue::Int(1)).unwrap(); } - let app = router(store); + let app = router(store, no_auth()); let resp = app .oneshot(Request::get("/api/tags").body(Body::empty()).unwrap()) @@ -452,7 +458,7 @@ mod tests { #[tokio::test] async fn get_tags_nonexistent_comp() { - let app = router(test_store()); + let app = router(test_store(), no_auth()); let resp = app .oneshot(Request::get("/api/tags/999").body(Body::empty()).unwrap()) .await @@ -483,7 +489,7 @@ mod tests { }, ); } - let app = router(store); + let app = router(store, no_auth()); let resp = app .oneshot(Request::get("/api/tags/10").body(Body::empty()).unwrap()) .await @@ -517,7 +523,7 @@ mod tests { }, ); } - let app = router(store); + let app = router(store, no_auth()); let resp = app .oneshot( Request::get("/api/tags/10?computed=false") @@ -549,7 +555,7 @@ mod tests { s.set(20, "unit".into(), DynValue::Str("degF".into())) .unwrap(); } - let app = router(store); + let app = router(store, no_auth()); let resp = app .oneshot(Request::get("/api/tags/stats").body(Body::empty()).unwrap()) .await diff --git a/crates/sandstar-server/src/rest/ws.rs b/crates/sandstar-server/src/rest/ws.rs index 7ad65cd..161a8bf 100644 --- a/crates/sandstar-server/src/rest/ws.rs +++ b/crates/sandstar-server/src/rest/ws.rs @@ -480,6 +480,7 @@ pub async fn ws_upgrade( ws: WebSocketUpgrade, Query(params): Query, State(state): State, + headers: axum::http::HeaderMap, ) -> Response { // Check connection limit let current = crate::metrics::metrics() @@ -493,11 +494,30 @@ pub async fn ws_upgrade( .into_response(); } - // Check query-param auth - let pre_authed = match (&state.auth_token, ¶ms.token) { - (None, _) => true, - (Some(required), Some(provided)) => provided == required, - _ => false, + // Pre-auth before the upgrade (S-32). Without auth every connection is + // authenticated. With auth on, a foreign browser Origin is refused, and + // a bearer header, session cookie or the deprecated `?token=` marks the + // connection authenticated; otherwise it must send an `auth` message. + let pre_authed = match &state.auth_state { + Some(auth) if auth.store.is_auth_required() => { + if !super::origin_allowed(&headers, auth) { + return (StatusCode::FORBIDDEN, "origin not allowed").into_response(); + } + if params.token.is_some() { + warn!("/api/ws ?token= is deprecated (token in URL, R-14); use a header, cookie or auth message"); + } + super::has_valid_credential(&headers, auth) + // Legacy bearer only: session tokens do not go in URLs (R-14). + || params.token.as_deref().is_some_and(|t| auth.store.check_bearer(t)) + } + Some(_) => true, + None => match (&state.auth_token, ¶ms.token) { + (None, _) => true, + (Some(required), Some(provided)) => { + crate::auth::constant_time_eq(required.as_bytes(), provided.as_bytes()) + } + _ => false, + }, }; ws.max_message_size(MAX_CLIENT_MESSAGE_BYTES) @@ -936,7 +956,9 @@ fn handle_auth_msg( .ok() } } - Some(required) if token == *required => { + Some(required) + if crate::auth::constant_time_eq(required.as_bytes(), token.as_bytes()) => + { *authenticated = true; serde_json::to_string(&ServerMsg::AuthOk { id, diff --git a/crates/sandstar-server/tests/auth_layer.rs b/crates/sandstar-server/tests/auth_layer.rs new file mode 100644 index 0000000..6c0a1c5 --- /dev/null +++ b/crates/sandstar-server/tests/auth_layer.rs @@ -0,0 +1,449 @@ +//! Route inventory for the auth layer (R-2, S-31). +//! +//! Builds the REST app the way `main.rs` does (core router + SOX + tags + +//! alerts + roxWarp) and checks every state-changing route: +//! - with auth configured, no token or a wrong token gets 401; +//! - with the right token the request reaches the handler (not 401); +//! - with no auth configured nothing gets 401 (field behavior unchanged). +//! +//! 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. + +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 sandstar_server::sox::sox_handlers::{ComponentTree, ManifestDb}; +use sandstar_server::sox::SharedComponentTree; +use tokio::sync::mpsc; +use tower::ServiceExt; + +#[allow(dead_code)] +mod common; + +const TOKEN: &str = "s31-test-token"; + +/// Every state-changing route on the 8085 app: (method, path, body). +const WRITE_ROUTES: &[(&str, &str, &str)] = &[ + // Haystack core + ( + "POST", + "/api/pointWrite", + r#"{"channel":1113,"value":1.0,"level":16}"#, + ), + ("POST", "/api/pollNow", "{}"), + ("POST", "/api/reload", "{}"), + ("POST", "/api/watchSub", "{}"), + ("POST", "/api/watchUnsub", "{}"), + ("POST", "/api/watchPoll", "{}"), + ("POST", "/api/hisRead", "{}"), + ("POST", "/api/nav", "{}"), + ("POST", "/api/invokeAction", "{}"), + // Drivers + ("POST", "/api/drivers", "{}"), + ("DELETE", "/api/drivers/x", ""), + ("POST", "/api/drivers/x/open", "{}"), + ("POST", "/api/drivers/x/close", "{}"), + ("POST", "/api/drivers/x/ping", "{}"), + ("POST", "/api/drivers/x/message", "{}"), + ("POST", "/api/drivers/x/write", "{}"), + ("POST", "/api/syncCur", "{}"), + // SOX component tree + ("POST", "/api/sox/comp", "{}"), + ("DELETE", "/api/sox/comp/9999", ""), + ("PUT", "/api/sox/comp/9999/name", "{}"), + ("PUT", "/api/sox/comp/9999/slot/0", "{}"), + ("POST", "/api/sox/comp/9999/invoke/0", "{}"), + ("POST", "/api/sox/link", "{}"), + ("DELETE", "/api/sox/link", "{}"), + ("PUT", "/api/sox/comp/9999/pos", "{}"), + ("PUT", "/api/sox/comp/9999/reorder", "{}"), + // File transfer + ("PUT", "/file/s31-probe.txt", "x"), + // Dynamic tags + ("PUT", "/api/tags/9999", "{}"), + ("DELETE", "/api/tags/9999/k", ""), + // Alerts (SMTP config, recipients, test e-mail) + ("PUT", "/api/alerts/config", "{}"), + ("POST", "/api/alerts/recipients", "{}"), + ("DELETE", "/api/alerts/recipients/a%40b.c", ""), + ("POST", "/api/alerts/test", "{}"), + // Cluster + ("POST", "/api/cluster/query", "{}"), +]; + +/// Read routes that must stay public even with auth configured. +const READ_ROUTES: &[&str] = &[ + "/api/about", + "/api/read?filter=point", + "/api/drivers", + "/api/sox/tree", + "/api/tags", + "/api/alerts/config", + "/api/cluster/status", +]; + +fn build_app(auth: AuthStore) -> (Router, tokio::task::JoinHandle<()>) { + // Keep `PUT /file/*` from writing anywhere: with no file root it answers + // 503 before touching the disk. + std::env::remove_var("SANDSTAR_FILE_ROOT"); + std::env::remove_var("SANDSTAR_WEB_DIR"); + let auth_state = AuthState::new(auth); + + let manifest_db = Arc::new(ManifestDb::load("")); + let tree: SharedComponentTree = Arc::new(RwLock::new(ComponentTree::new_with_manifest( + manifest_db.clone(), + ))); + let sox_state = rest::sox_api::SoxApiState { + tree, + manifest_db, + dyn_store: None, + }; + + 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("s31".into())), + config: ClusterConfig { + node_id: "s31".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, + }, + sox_tree: None, + }; + + let app = rest::router_with_auth(handle, auth_state.clone(), None, 0, 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) +} + +async fn status( + app: &Router, + method: &str, + path: &str, + body: &str, + token: Option<&str>, +) -> StatusCode { + let mut req = Request::builder() + .method(method) + .uri(path) + .header("content-type", "application/json"); + if let Some(t) = token { + req = req.header("authorization", format!("Bearer {t}")); + } + let req = req.body(Body::from(body.to_string())).unwrap(); + app.clone().oneshot(req).await.unwrap().status() +} + +#[tokio::test] +async fn write_routes_require_a_token_when_auth_is_configured() { + let (app, _task) = build_app(AuthStore::with_bearer_token(TOKEN.to_string())); + let mut open = Vec::new(); + for (m, p, b) in WRITE_ROUTES { + for token in [None, Some("wrong-token")] { + let s = status(&app, m, p, b, token).await; + if s != StatusCode::UNAUTHORIZED { + open.push(format!("{m} {p} token={token:?} -> {s}")); + } + } + } + assert!( + open.is_empty(), + "write routes reachable without a valid token:\n{}", + open.join("\n") + ); +} + +#[tokio::test] +async fn write_routes_accept_the_configured_token() { + let (app, _task) = build_app(AuthStore::with_bearer_token(TOKEN.to_string())); + for (m, p, b) in WRITE_ROUTES { + let s = status(&app, m, p, b, Some(TOKEN)).await; + assert_ne!( + s, + StatusCode::UNAUTHORIZED, + "{m} {p} rejected a valid token" + ); + // 405 would mean the inventory names a method the router does not serve. + assert_ne!( + s, + StatusCode::METHOD_NOT_ALLOWED, + "{m} {p} is not a served route" + ); + } +} + +#[tokio::test] +async fn no_route_requires_a_token_when_auth_is_not_configured() { + let (app, _task) = build_app(AuthStore::new()); + for (m, p, b) in WRITE_ROUTES { + let s = status(&app, m, p, b, None).await; + assert_ne!( + s, + StatusCode::UNAUTHORIZED, + "{m} {p} needs a token with auth off" + ); + } +} + +#[tokio::test] +async fn read_routes_stay_public_when_auth_is_configured() { + let (app, _task) = build_app(AuthStore::with_bearer_token(TOKEN.to_string())); + for p in READ_ROUTES { + let s = status(&app, "GET", p, "", None).await; + assert_ne!(s, StatusCode::UNAUTHORIZED, "GET {p} needs a token"); + } +} + +#[test] +fn bearer_comparison_rejects_prefixes_and_longer_tokens() { + let store = AuthStore::with_bearer_token(TOKEN.to_string()); + assert!(store.check_bearer(TOKEN)); + assert!(!store.check_bearer("")); + assert!(!store.check_bearer("s31-test-toke")); + assert!(!store.check_bearer("s31-test-tokenX")); + assert!(!store.check_bearer("s31-test-tokeN")); + assert!(!AuthStore::new().check_bearer("")); +} + +#[tokio::test] +async fn an_empty_configured_token_does_not_open_write_routes() { + let (app, _task) = build_app(AuthStore::with_bearer_token(String::new())); + for (m, p, b) in WRITE_ROUTES { + for token in [None, Some("")] { + let s = status(&app, m, p, b, token).await; + assert_eq!(s, StatusCode::UNAUTHORIZED, "{m} {p} token={token:?}"); + } + } +} + +// ── WebSocket and editor endpoints (R-52, S-32) ───────────── + +/// Editor endpoints gated before the WebSocket upgrade. +const UPGRADE_ROUTES: &[&str] = &["/live", "/api/rows", "/api/ws"]; + +async fn serve(auth: AuthStore) -> (String, tokio::task::JoinHandle<()>) { + let (app, task) = build_app(auth); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + (format!("127.0.0.1:{}", addr.port()), task) +} + +/// Try a WebSocket handshake; returns the HTTP status (101 on success). +async fn ws_status(host: &str, path: &str, headers: &[(&str, String)]) -> u16 { + use tokio_tungstenite::tungstenite::client::IntoClientRequest; + let mut req = format!("ws://{host}{path}").into_client_request().unwrap(); + for (k, v) in headers { + req.headers_mut().insert( + axum::http::HeaderName::from_bytes(k.as_bytes()).unwrap(), + v.parse().unwrap(), + ); + } + match tokio_tungstenite::connect_async(req).await { + Ok((_ws, resp)) => resp.status().as_u16(), + Err(tokio_tungstenite::tungstenite::Error::Http(resp)) => resp.status().as_u16(), + Err(e) => panic!("{path}: unexpected handshake error {e}"), + } +} + +fn bearer() -> (&'static str, String) { + ("authorization", format!("Bearer {TOKEN}")) +} + +#[tokio::test] +async fn editor_websockets_need_a_credential_when_auth_is_configured() { + let (host, _t) = serve(AuthStore::with_bearer_token(TOKEN.to_string())).await; + for p in ["/live", "/api/rows"] { + assert_eq!(ws_status(&host, p, &[]).await, 401, "{p} without token"); + let wrong = [("authorization", "Bearer nope".to_string())]; + assert_eq!(ws_status(&host, p, &wrong).await, 401, "{p} wrong token"); + let cookie = [("cookie", "sandstar_session=nope".to_string())]; + assert_eq!(ws_status(&host, p, &cookie).await, 401, "{p} bad cookie"); + } + for p in UPGRADE_ROUTES { + assert_eq!(ws_status(&host, p, &[bearer()]).await, 101, "{p} bearer"); + let cookie = [("cookie", format!("a=b; sandstar_session={TOKEN}"))]; + assert_eq!(ws_status(&host, p, &cookie).await, 101, "{p} cookie"); + } +} + +#[tokio::test] +async fn editor_websockets_refuse_a_foreign_origin() { + let (host, _t) = serve(AuthStore::with_bearer_token(TOKEN.to_string())).await; + for p in UPGRADE_ROUTES { + let evil = [bearer(), ("origin", "http://evil.example".to_string())]; + assert_eq!(ws_status(&host, p, &evil).await, 403, "{p} foreign origin"); + let same = [bearer(), ("origin", format!("http://{host}"))]; + assert_eq!(ws_status(&host, p, &same).await, 101, "{p} same origin"); + } +} + +#[tokio::test] +async fn null_origin_and_a_planted_cookie_are_handled() { + let (host, _t) = serve(AuthStore::with_bearer_token(TOKEN.to_string())).await; + let null = [bearer(), ("origin", "null".to_string())]; + assert_eq!(ws_status(&host, "/live", &null).await, 403); + // A bad cookie with the same name must not hide the valid one. + let two = [( + "cookie", + format!("sandstar_session=planted; sandstar_session={TOKEN}"), + )]; + assert_eq!(ws_status(&host, "/live", &two).await, 101); + let basic = [("authorization", format!("Basic {TOKEN}"))]; + assert_eq!(ws_status(&host, "/live", &basic).await, 401); +} + +#[tokio::test] +async fn allowlisted_origin_is_accepted() { + let mut store = AuthStore::with_bearer_token(TOKEN.to_string()); + store.set_allowed_origins(vec!["http://Editor.local:8080/".to_string()]); + let (host, _t) = serve(store).await; + let h = [bearer(), ("origin", "http://editor.local:8080".to_string())]; + assert_eq!(ws_status(&host, "/live", &h).await, 101); +} + +#[tokio::test] +async fn editor_websockets_stay_open_when_auth_is_not_configured() { + let (host, _t) = serve(AuthStore::new()).await; + for p in UPGRADE_ROUTES { + let evil = [("origin", "http://evil.example".to_string())]; + assert_eq!(ws_status(&host, p, &evil).await, 101, "{p}"); + } +} + +#[tokio::test] +async fn sedona_state_needs_a_credential_when_auth_is_configured() { + let (app, _task) = build_app(AuthStore::with_bearer_token(TOKEN.to_string())); + let p = "/live/sedonaState"; + assert_eq!( + status(&app, "GET", p, "", None).await, + StatusCode::UNAUTHORIZED + ); + assert_ne!( + status(&app, "GET", p, "", Some(TOKEN)).await, + StatusCode::UNAUTHORIZED + ); +} + +async fn post_json( + app: &Router, + path: &str, + body: &serde_json::Value, +) -> (StatusCode, serde_json::Value, Option) { + let req = Request::builder() + .method("POST") + .uri(path) + .header("content-type", "application/json") + .body(Body::from(body.to_string())) + .unwrap(); + let resp = app.clone().oneshot(req).await.unwrap(); + let status = resp.status(); + let cookie = resp + .headers() + .get("set-cookie") + .map(|v| v.to_str().unwrap().to_string()); + let bytes = axum::body::to_bytes(resp.into_body(), 1 << 20) + .await + .unwrap(); + (status, serde_json::from_slice(&bytes).unwrap(), cookie) +} + +#[tokio::test] +async fn scram_login_sets_an_httponly_strict_session_cookie() { + use base64::Engine as _; + let b64 = base64::engine::general_purpose::STANDARD; + let mut store = AuthStore::new(); + store.add_user("s32user", "s32-pass"); + let (app, _task) = build_app(store); + + let (client_first, nonce) = sandstar_server::auth::scram_client_first("s32user"); + let bare = client_first.strip_prefix("n,,").unwrap().to_string(); + let body = serde_json::json!({"action": "scramFirst", "data": b64.encode(&client_first)}); + let (_, v, cookie) = post_json(&app, "/api/auth", &body).await; + assert!(cookie.is_none(), "no cookie before the handshake completes"); + let hs = v["handshakeToken"].as_str().unwrap().to_string(); + let server_first = String::from_utf8(b64.decode(v["data"].as_str().unwrap()).unwrap()).unwrap(); + + let client_final = + sandstar_server::auth::scram_client_final("s32-pass", &nonce, &bare, &server_first) + .unwrap(); + let body = serde_json::json!({ + "action": "scramFinal", "handshakeToken": hs, "data": b64.encode(&client_final) + }); + let (status, v, cookie) = post_json(&app, "/api/auth", &body).await; + assert_eq!(status, StatusCode::OK); + let cookie = cookie.expect("Set-Cookie on SCRAM success"); + let token = v["authToken"].as_str().unwrap(); + assert!( + cookie.starts_with(&format!("sandstar_session={token};")), + "{cookie}" + ); + assert!(cookie.contains("HttpOnly"), "{cookie}"); + assert!(cookie.contains("SameSite=Strict"), "{cookie}"); + + // The cookie opens /live/sedonaState; a SCRAM-only setup is auth-on. + let req = Request::builder() + .uri("/live/sedonaState") + .header("cookie", format!("sandstar_session={token}")) + .body(Body::empty()) + .unwrap(); + let s = app.clone().oneshot(req).await.unwrap().status(); + assert_eq!(s, StatusCode::OK); + assert_eq!( + status_of(&app, "/live/sedonaState").await, + StatusCode::UNAUTHORIZED + ); +} + +async fn status_of(app: &Router, path: &str) -> StatusCode { + status(app, "GET", path, "", None).await +} + +#[tokio::test] +async fn api_ws_is_not_pre_authenticated_with_scram_only() { + // Before S-32 a SCRAM-only setup marked every /api/ws connection as + // authenticated (`ws.rs` `(None, _) => true`). + use futures_util::{SinkExt, StreamExt}; + use tokio_tungstenite::tungstenite::Message; + let mut store = AuthStore::new(); + store.add_user("s32user", "s32-pass"); + let (host, _t) = serve(store).await; + + let evil = [("origin", "http://evil.example".to_string())]; + assert_eq!(ws_status(&host, "/api/ws", &evil).await, 403); + + let (mut ws, _) = tokio_tungstenite::connect_async(format!("ws://{host}/api/ws")) + .await + .unwrap(); + let sub = r#"{"op":"subscribe","id":"s32","ids":[1113]}"#; + ws.send(Message::Text(sub.into())).await.unwrap(); + let reply = tokio::time::timeout(std::time::Duration::from_secs(5), ws.next()) + .await + .expect("reply in time") + .expect("open socket") + .unwrap(); + let text = reply.into_text().unwrap(); + assert!(text.contains("AUTH_REQUIRED"), "{text}"); +} diff --git a/docs/Progress/HARDCODED_LIMITS.md b/docs/Progress/HARDCODED_LIMITS.md index 1c20866..3c6b082 100644 --- a/docs/Progress/HARDCODED_LIMITS.md +++ b/docs/Progress/HARDCODED_LIMITS.md @@ -84,6 +84,8 @@ Audited: 2026-03-10 | `HANDSHAKE_TIMEOUT_SECS` | 30s | `sandstar-server/src/auth.rs` | 33 | **Keep** — prevents hanging auth handshakes. | | `SESSION_LIFETIME_SECS` | 86,400 (24h) | `sandstar-server/src/auth.rs` | 34 | **Consider** — operators may want shorter sessions for security. | | `MAX_SESSIONS` | 256 | `sandstar-server/src/auth.rs` | 35 | **Consider** — may need tuning for high-traffic deployments. | +| `SESSION_COOKIE` | `sandstar_session` | `sandstar-server/src/rest/mod.rs` | — | **Keep** — set by `POST /api/auth` on SCRAM success (`HttpOnly; SameSite=Strict; Path=/`, no `Secure` because the device serves plain HTTP). Accepted on `/live`, `/live/sedonaState`, `/api/rows`, `/api/ws` (S-32). | +| WS allowed origins | empty (same host only) | `sandstar-server/src/args.rs` | — | **Configurable** — `--ws-allowed-origins` / `SANDSTAR_WS_ALLOWED_ORIGINS` (comma separated). Only checked when auth is on (S-32). | ## Engine Core diff --git a/docs/Progress/OVERVIEW.md b/docs/Progress/OVERVIEW.md index 1bb29e4..0d079dc 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. ⚠ Several write routes sit outside the auth layer | [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; write routes outside `check_auth` (§3); 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` 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 | | 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) | @@ -215,16 +215,23 @@ Router: `router_with_auth` in `crates/sandstar-server/src/rest/mod.rs`, plus rou | `GET /api/about`, `/api/ops`, `/api/formats`, `/api/read`, `/api/status`, `/health`, `/api/metrics`, `/metrics`, `/api/diagnostics`, `/api/channels`, `/api/polls`, `/api/tables`, `/api/history/{channel}`, `GET /api/pointWrite` | no | Read-only metadata, data and observability (`/metrics` is Prometheus text) | | `POST /api/auth` | — | SCRAM handshake | | `POST /api/pointWrite`, `/api/pollNow`, `/api/reload`, `/api/watchSub`, `/api/watchUnsub`, `/api/watchPoll`, `/api/hisRead`, `/api/nav`, `/api/invokeAction` | **yes** | Haystack ops and engine writes | -| `GET /api/ws` | handshake | Haystack-over-WebSocket (JSON) with SCRAM inside the socket | +| `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`) | -| `POST/DELETE/PUT /api/sox/comp*`, `/api/sox/link` | **no** ⚠ | SOX component edits (with `--sox`) | -| `GET /api/rows`, `GET /live`, `GET /live/sedonaState`, `GET/PUT /file/*`, `/library/` | **no** ⚠ | Editor WebSockets and file transfer (with `--sox`) | -| `GET/PUT/DELETE /api/tags*` | **no** ⚠ | Dynamic tags | -| `/api/alerts/*` (config, recipients, test e-mail) | **no** ⚠ | Alert management | -| `GET /roxwarp`, `GET /api/cluster/status`, `POST /api/cluster/query` | **no** ⚠ | roxWarp (with `--cluster`; mTLS applies only on the separate cluster port) | -| `/api/sim/*` | no | Only in builds with the `simulator-hal` feature | +| `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 /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 /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 | +| `GET /api/sim/outputs` (drains recorded writes), `POST /api/sim/inject`, `POST /api/sim/scenario` | **yes** (S-31) | Only in builds with the `simulator-hal` feature | **Security posture:** - `--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. @@ -250,7 +257,7 @@ Host addresses, SSH details and site names are deliberately not written in this | Item | State | |---|---| | Field devices | One BeagleBone (Debian 9, kernel 4.9, armv7). Older device labels in this repo's history refer to the same unit. | -| Installed build | `2.9.0+3b8e97c` | +| Installed build | `2.9.0+76888b2` (2026-11-20) | | Service | `sandstar-engine.service`: `--http-bind 0.0.0.0 --sox --cluster`, no auth configured. The C service no longer exists. | | Drivers | A site-local systemd drop-in enables a BACnet driver; it logs a steady stream of `comm fault` warnings that are not yet explained. No MQTT driver is confirmed. | | Logs | `/var/log/sandstar/sandstar-engine.log.YYYY-MM-DD`, newest 14 kept. The systemd journal is volatile and holds well under an hour. | @@ -305,7 +312,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, SOX edits, `/live`, `/file`, tags, alerts and cluster routes bypass `check_auth` (§3). +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). 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).