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
18 changes: 12 additions & 6 deletions crates/sandstar-server/src/alerts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down
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
39 changes: 38 additions & 1 deletion crates/sandstar-server/src/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<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 @@ -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<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 All @@ -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).
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
6 changes: 1 addition & 5 deletions crates/sandstar-server/src/drivers/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand All @@ -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)
}
Expand Down
17 changes: 12 additions & 5 deletions crates/sandstar-server/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -526,6 +526,10 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
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",
Expand Down Expand Up @@ -596,21 +600,24 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
#[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());
Expand All @@ -619,7 +626,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
// 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 =
Expand Down
15 changes: 10 additions & 5 deletions crates/sandstar-server/src/rest/file_ops.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -60,10 +60,15 @@ pub fn resolve_file_root() -> Option<PathBuf> {
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 ───────────────────────────────────────
Expand Down
Loading
Loading