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
3 changes: 2 additions & 1 deletion .claude/rules/routes-auth.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@ paths:
Bugünkü durum: üretim servisi `0.0.0.0` üzerinde ve auth'suz çalışıyor (R-1). Birçok yazma rotası auth katmanından **sonra** merge edildiği için korumasız (R-2). Auth modeli henüz karara bağlanmadı (Q-4, S-3). Bu kurallar durumu daha da kötüleştirmemek içindir.

## Yeni veya değişen rota
- Rotanın auth katmanının **içinde mi dışında mı** olduğu açıkça belirlenir ve commit mesajında yazılır. axum'da `.layer(...)` yalnız kendisinden önce eklenen rotaları sarar. Layer'dan sonra yapılan `.merge(...)` / `.route(...)` korumasız kalır. Örnekler: `crates/sandstar-server/src/rest/mod.rs:855-868`, `crates/sandstar-server/src/main.rs:600-610`.
- Rotanın auth katmanının **içinde mi dışında mı** olduğu açıkça belirlenir ve commit mesajında yazılır. axum'da `.layer(...)` yalnız kendisinden önce eklenen rotaları sarar. Layer'dan sonra yapılan `.merge(...)` / `.route(...)` korumasız kalır. Örnek: `rest/mod.rs` `require_auth` / `require_upgrade_auth`.
- Global katmanlar (sayaç, rate limit, body limit, CORS) `rest::with_global_layers` ile **en son** uygulanır. Yeni bir router `main.rs`'de bu çağrıdan önce birleştirilir; sonra birleştirilen router bu katmanların dışında kalır (R-53, S-35).
- Durum değiştiren uçlar (yazma, silme, config, dosya, alarm/SMTP ayarı) varsayılan olarak auth içinde olmalı. Dışarıda kalacaksa gerekçesi kodda yorumla yazılır.
- Kimlik bilgisi ve token URL query'sine konmaz (R-14). Token karşılaştırması sabit zamanlı yapılır.
- GET yanıtlarında sır alanları maskelenir (örnek: `crates/sandstar-server/src/alerts.rs`).
Expand Down
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -56,5 +56,6 @@ server_stderr.log
/tools/xeto/checkXetoFiles.sh

# Local tool output
/tools/editor-dev.env
/.playwright-mcp/
/editor_connected.png
1 change: 1 addition & 0 deletions HowToUses/02_REST_API.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ curl http://localhost:8085/api/diagnostics
```bash
# Full component tree
curl http://localhost:8085/api/sox/tree
# With auth on (S-33): add -H "Authorization: Bearer <token>"

# Single component with slots and links
curl http://localhost:8085/api/sox/comp/200
Expand Down
19 changes: 19 additions & 0 deletions HowToUses/03_WEB_EDITOR.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,25 @@
http://<host>:8085/editor
```

## Vue editor against a real device (development)

The Vue Sedona editor (`sedonaWebEditor`, branch `trkrDevelop`) runs from its
dev server and proxies `/live`, `/api`, `/file` to a device:

```bash
# Device address: argument, SANDSTAR_DEVICE, or tools/editor-dev.env
# (git-ignored; one line SANDSTAR_DEVICE=<host>)
bash tools/editor-dev.sh [device[:port]]
```

The script checks the device (`/api/about`, whether the editor gate asks for
a login) and starts the editor at `http://localhost:8091/`. Add a connection
with the device user; leave `peer` empty (it defaults to the page origin).
With auth on, the device needs `--ws-allowed-origins http://localhost:8091`:
the editor's WebSockets, tree and file reads, and kit uploads (`PUT /file/*`)
use the session cookie from the login and are checked against the page origin.
Edits in the editor go to the running app on the device.

## Layout
- **Left sidebar**: Tree navigator (top) + Component palette (bottom)
- **Center canvas**: Visual wire sheet (only user-added components)
Expand Down
13 changes: 11 additions & 2 deletions HowToUses/06_ROXWARP_CLUSTER.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,18 @@ roxWarp is a gossip-based state synchronization protocol for multi-device Sandst

## Enable Clustering

### Basic (plain WebSocket, no TLS)
The cluster is fail-closed: without mTLS certificates it starts only with
`--cluster-insecure`. `--cluster` alone, or a broken or incomplete mTLS
setup, leaves the cluster listener and peer connections off (the log says
why); `/api/cluster/status` still answers.

### Basic (plain WebSocket, no TLS, no peer authentication)
```bash
sandstar-engine-server --sox --cluster --node-id sandstar-a-001
sandstar-engine-server --sox --cluster --cluster-insecure --node-id sandstar-a-001
```
Any host that can reach the port can join as a peer. Use it only on an
isolated test network. In this mode `/roxwarp` is also served on the REST
port.

### With Config File
```bash
Expand All @@ -35,6 +43,7 @@ sandstar-engine-server --sox --cluster --node-id sandstar-a-001 \
| `--cluster-cert <path>` | none | Device certificate (PEM) |
| `--cluster-key <path>` | none | Device private key (PEM) |
| `--cluster-ca <path>` | none | CA certificate for peer verification |
| `--cluster-insecure` | off | Allow plain WebSocket with no peer auth when no certificates are given (CLI only, not in the config file) |

## Cluster Config File

Expand Down
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,7 @@ Set via `--config-dir` or `SANDSTAR_CONFIG_DIR`; contains:
| `--no-control` | | false | Disable PID/sequencer engine |
| `--cluster` | | false | Enable roxWarp gossip clustering (see `--cluster-config`) |
| `--cluster-config` | | (none) | Path to `ClusterConfig` JSON (peers, mTLS, mDNS) |
| `--cluster-insecure` | | false | Allow the cluster over plain WebSocket, no peer auth, when no mTLS certificates are given. Without it the cluster network stays off |
| `--tls-cert` | `SANDSTAR_TLS_CERT` | (none) | TLS certificate (PEM) |
| `--tls-key` | `SANDSTAR_TLS_KEY` | (none) | TLS private key (PEM) |
| `--sedona` | | false | Enable Sedona VM |
Expand Down Expand Up @@ -175,7 +176,7 @@ Cluster + SOX WebSocket:
| Endpoint | Method | Description |
|----------|--------|-------------|
| `/api/rows` | GET | RoWS (SOX-over-WebSocket) session — tree, slot, link, readTags/setTags/deleteTag |
| `/roxwarp` | GET | roxWarp cluster peer WebSocket (when `--cluster` is set) |
| `/roxwarp` | GET | roxWarp cluster peer WebSocket (only with `--cluster --cluster-insecure`; with mTLS peers use the cluster port) |

All endpoints support JSON by default; `Accept: text/zinc` returns Haystack Zinc. Per-endpoint details in [`docs/Progress/DRIVER_REST_API.md`](docs/Progress/DRIVER_REST_API.md).

Expand Down
14 changes: 14 additions & 0 deletions crates/sandstar-server/src/args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,12 @@ pub struct ServerArgs {
/// Path to CA certificate (PEM) for verifying roxWarp peer certificates.
#[arg(long, env = "SANDSTAR_CLUSTER_CA")]
pub cluster_ca: Option<String>,

/// Allow the roxWarp cluster over plain WebSocket with no peer auth when
/// no mTLS certificates are given. Without it and without certificates,
/// the cluster listener and outbound peer connections stay off (R-54).
#[arg(long, default_value_t = false)]
pub cluster_insecure: bool,
}

fn default_socket() -> String {
Expand Down Expand Up @@ -378,6 +384,14 @@ mod tests {
assert!(args.cluster_cert.is_none());
assert!(args.cluster_key.is_none());
assert!(args.cluster_ca.is_none());
assert!(!args.cluster_insecure);
}

#[test]
fn test_cluster_insecure_flag() {
let args =
ServerArgs::parse_from(["sandstar-engine-server", "--cluster", "--cluster-insecure"]);
assert!(args.cluster_insecure);
}

#[test]
Expand Down
102 changes: 48 additions & 54 deletions crates/sandstar-server/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -481,6 +481,8 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {

// Override port from CLI
cluster_config.port = args.cluster_port;
// Plain WS without peer auth only on explicit request (R-54, S-36).
cluster_config.allow_plain = args.cluster_insecure;

// Set mTLS paths from CLI args
if args.cluster_cert.is_some() || args.cluster_key.is_some() || args.cluster_ca.is_some() {
Expand All @@ -504,7 +506,8 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
node_id = %cluster_config.node_id,
port = cluster_config.port,
peers = cluster_config.peers.len(),
mtls = cluster_config.cert_path.is_some(),
// Paths only; whether mTLS builds is logged by `roxwarp::transport`.
mtls_paths = cluster_config.cert_path.is_some(),
"roxWarp cluster mode enabled"
);

Expand All @@ -519,73 +522,60 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
sox_tree: sox_api_state.as_ref().map(|s| s.tree.clone()),
};

// Start separate roxWarp listener on cluster port (default 7443)
// Separate roxWarp listener on the cluster port (default 7443).
// Fail-closed (R-54, S-36): mTLS, or plain WS only with
// --cluster-insecure; a broken mTLS setup keeps the port closed.
// `server_transport` logs why the listener is off.
let cluster_port = cluster_config.port;
let transport = sandstar_server::roxwarp::transport::server_transport(&cluster_config);
let rw_state_for_listener = rw_state.clone();
tokio::spawn(async move {
use axum::routing::get;
use axum::Router;
use sandstar_server::roxwarp::transport::Transport;

// Outside the REST auth layer (R-2): peers authenticate with mTLS
// on this port when certificates are configured. Without them, or
// if the mTLS config fails to build, this serves plain WS with no
// peer auth (known gap, see 06).
// on this port; plain WS (no peer auth) only with --cluster-insecure.
let cluster_app = Router::new()
.route(
"/roxwarp",
get(sandstar_server::roxwarp::handler::roxwarp_upgrade),
)
.with_state(rw_state_for_listener);

let bind_addr: std::net::SocketAddr = format!("0.0.0.0:{cluster_port}")
.parse()
.expect("valid cluster bind address");

// Build mTLS server config if certificates are configured
if let (Some(ref cert), Some(ref key), Some(ref ca)) = (
&cluster_config.cert_path,
&cluster_config.key_path,
&cluster_config.ca_path,
) {
match sandstar_server::roxwarp::mtls::build_mtls_server_config(cert, key, ca) {
Ok(server_tls_config) => {
info!(port = cluster_port, "roxWarp: starting mTLS listener");
let rustls_config =
axum_server::tls_rustls::RustlsConfig::from_config(server_tls_config);
if let Err(e) = axum_server::bind_rustls(bind_addr, rustls_config)
.serve(cluster_app.into_make_service())
.await
{
error!(port = cluster_port, error = %e, "roxWarp: mTLS listener failed");
}
}
Err(e) => {
error!(error = %e, "roxWarp: failed to build mTLS server config, falling back to plain WS");
let listener = match tokio::net::TcpListener::bind(&bind_addr).await {
Ok(l) => l,
Err(e) => {
error!(port = cluster_port, error = %e, "roxWarp: failed to bind cluster port");
return;
}
};
info!(
port = cluster_port,
"roxWarp: listening (plain WS, mTLS config failed)"
);
axum::serve(listener, cluster_app).await.ok();
let bind_addr = std::net::SocketAddr::from(([0, 0, 0, 0], cluster_port));

match transport {
Transport::Mtls(server_tls_config) => {
info!(port = cluster_port, "roxWarp: starting mTLS listener");
let rustls_config =
axum_server::tls_rustls::RustlsConfig::from_config(server_tls_config);
if let Err(e) = axum_server::bind_rustls(bind_addr, rustls_config)
.serve(cluster_app.into_make_service())
.await
{
error!(port = cluster_port, error = %e, "roxWarp: mTLS listener failed");
}
}
} else {
// No mTLS configured — plain WebSocket listener
let listener = match tokio::net::TcpListener::bind(&bind_addr).await {
Ok(l) => l,
Err(e) => {
error!(port = cluster_port, error = %e, "roxWarp: failed to bind cluster port");
return;
Transport::Plain => {
let listener = match tokio::net::TcpListener::bind(&bind_addr).await {
Ok(l) => l,
Err(e) => {
error!(port = cluster_port, error = %e, "roxWarp: failed to bind cluster port");
return;
}
};
info!(
port = cluster_port,
"roxWarp: listening (plain WS, --cluster-insecure)"
);
if let Err(e) = axum::serve(listener, cluster_app).await {
error!(port = cluster_port, error = %e, "roxWarp: plain WS listener failed");
}
};
info!(port = cluster_port, "roxWarp: listening (plain WS)");
axum::serve(listener, cluster_app).await.ok();
}
Transport::Off => {
info!(port = cluster_port, "roxWarp: cluster listener not started");
}
}
});

Expand All @@ -597,12 +587,12 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
if !args.no_rest {
let handle = EngineHandle::new(cmd_tx.clone());
let auth_state = sandstar_server::auth::AuthState::new(config.auth_store.clone());
#[allow(unused_mut)]
let mut app = rest::router_with_auth(
// Core routes without the global layers; every router below is
// merged first and `with_global_layers` wraps them all (R-53, S-35).
let mut app = rest::api_routes(
handle,
auth_state.clone(),
config.auth_token.clone(),
config.rate_limit,
sox_api_state,
);

Expand All @@ -629,6 +619,10 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
app = app.merge(rest::sim::router(sim_state.clone(), auth_state.clone()));
}

// Request counter, rate limit, body limit and CORS. Last step: a
// router merged after this line is outside those layers.
let app = rest::with_global_layers(app, config.rate_limit);

let addr: std::net::SocketAddr =
format!("{}:{}", args.http_bind, args.http_port)
.parse()
Expand Down
10 changes: 8 additions & 2 deletions crates/sandstar-server/src/rest/file_ops.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,15 +60,21 @@ pub fn resolve_file_root() -> Option<PathBuf> {
None
}

/// `GET` stays public; `PUT` writes files and sits behind the auth layer (R-2).
/// `GET` sits behind the editor gate (bearer or session cookie, plus Origin;
/// R-55, S-33): the browser editor fetches kit files same-origin with its
/// cookie. `PUT` writes files and sits behind the write gate: bearer, or
/// session cookie with a required allowed `Origin` (R-56, S-37); the editor
/// uploads kits with its cookie. With no auth configured both pass every
/// request.
pub fn router(state: SoxState, auth_state: crate::auth::AuthState) -> Router {
let read = Router::new()
.route("/file/{*path}", get(get_file))
.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))
super::require_upgrade_auth(read, auth_state.clone())
.merge(super::require_write_auth(write, auth_state))
}

// ── Handlers ───────────────────────────────────────
Expand Down
Loading
Loading