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 4152891..ffe23af 100644 --- a/crates/sandstar-server/src/auth.rs +++ b/crates/sandstar-server/src/auth.rs @@ -87,7 +87,7 @@ impl StoredCredential { /// /// The length is not hidden (a length mismatch returns at once), only the /// position of the first differing byte. -fn constant_time_eq(a: &[u8], b: &[u8]) -> bool { +pub(crate) fn constant_time_eq(a: &[u8], b: &[u8]) -> bool { if a.len() != b.len() { return false; } @@ -100,6 +100,9 @@ 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 { @@ -113,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); 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/rest/mod.rs b/crates/sandstar-server/src/rest/mod.rs index 2ccdb17..bd5f461 100644 --- a/crates/sandstar-server/src/rest/mod.rs +++ b/crates/sandstar-server/src/rest/mod.rs @@ -574,6 +574,99 @@ 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 @@ -758,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 }), @@ -1024,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. @@ -1037,6 +1142,7 @@ 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 { @@ -1063,10 +1169,9 @@ pub fn router_with_auth( sox_api::protected_router(sox), auth_state.clone(), )) - // Outside the auth layer (R-2, S-32): browsers cannot send an - // Authorization header on a WebSocket upgrade and tokens may not - // go in the query string (R-14). `/live` and `/api/rows` need - // their own auth design. `/library/` and `/tags` are read-only. + // `/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) 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 index 3a27492..6c0a1c5 100644 --- a/crates/sandstar-server/tests/auth_layer.rs +++ b/crates/sandstar-server/tests/auth_layer.rs @@ -237,3 +237,213 @@ async fn an_empty_configured_token_does_not_open_write_routes() { } } } + +// ── 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 f777995..0d079dc 100644 --- a/docs/Progress/OVERVIEW.md +++ b/docs/Progress/OVERVIEW.md @@ -45,7 +45,7 @@ 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; ⚠ the editor WebSockets (`/live`, `/api/rows`) and `/roxwarp` are not | [ROADMAP_v2.md](ROADMAP_v2.md) §Phase 1, [DRIVER_REST_API.md](DRIVER_REST_API.md) | +| 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) | @@ -215,12 +215,12 @@ 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` | **yes** (S-31) | SOX component edits (with `--sox`) | -| `GET /api/rows`, `GET /live`, `GET /live/sedonaState` | **no** ⚠ | Editor WebSockets (with `--sox`). Browsers cannot send a header on the upgrade and tokens may not go in the URL, so these need their own auth design (S-32). They expose the same SOX edits as `/api/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) | @@ -312,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, the editor WebSockets (`/live`, `/api/rows`) and `/roxwarp` bypass `check_auth` (§3). HTTP write routes are behind it since S-31. +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).