Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions crates/sandstar-server/src/args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,12 @@ pub struct ServerArgs {
#[arg(long, env = "SANDSTAR_AUTH_PASS")]
pub auth_pass: Option<String>,

/// 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<String>,

/// Maximum REST API requests per second (0 = unlimited).
#[arg(long, env = "SANDSTAR_RATE_LIMIT", default_value_t = 100)]
pub rate_limit: u64,
Expand Down
22 changes: 21 additions & 1 deletion crates/sandstar-server/src/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand All @@ -100,6 +100,9 @@ pub struct AuthStore {
credentials: HashMap<String, StoredCredential>,
/// Legacy bearer token (backward compat with --auth-token).
bearer_token: Option<String>,
/// Extra browser origins allowed on WebSocket upgrades (R-52, S-32).
/// Same-host origins are always allowed.
allowed_origins: Vec<String>,
}

impl AuthStore {
Expand All @@ -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<String>) {
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);
Expand Down
1 change: 1 addition & 0 deletions crates/sandstar-server/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
129 changes: 117 additions & 12 deletions crates/sandstar-server/src/rest/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Item = &str> {
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<AuthState>,
request: Request,
next: middleware::Next,
) -> Result<Response, StatusCode> {
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
Expand Down Expand Up @@ -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 }),
Expand Down Expand Up @@ -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.
Expand All @@ -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 {
Expand All @@ -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)
Expand Down
34 changes: 28 additions & 6 deletions crates/sandstar-server/src/rest/ws.rs
Original file line number Diff line number Diff line change
Expand Up @@ -480,6 +480,7 @@ pub async fn ws_upgrade(
ws: WebSocketUpgrade,
Query(params): Query<WsParams>,
State(state): State<WsState>,
headers: axum::http::HeaderMap,
) -> Response {
// Check connection limit
let current = crate::metrics::metrics()
Expand All @@ -493,11 +494,30 @@ pub async fn ws_upgrade(
.into_response();
}

// Check query-param auth
let pre_authed = match (&state.auth_token, &params.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, &params.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)
Expand Down Expand Up @@ -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,
Expand Down
Loading
Loading