diff --git a/.claude/rules/routes-auth.md b/.claude/rules/routes-auth.md index c78c81e..cd5e2f7 100644 --- a/.claude/rules/routes-auth.md +++ b/.claude/rules/routes-auth.md @@ -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`). diff --git a/crates/sandstar-server/src/main.rs b/crates/sandstar-server/src/main.rs index 4b26c9a..a45f187 100644 --- a/crates/sandstar-server/src/main.rs +++ b/crates/sandstar-server/src/main.rs @@ -597,12 +597,12 @@ async fn main() -> Result<(), Box> { 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, ); @@ -629,6 +629,10 @@ async fn main() -> Result<(), Box> { 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() diff --git a/crates/sandstar-server/src/rest/mod.rs b/crates/sandstar-server/src/rest/mod.rs index b476e97..569cd9e 100644 --- a/crates/sandstar-server/src/rest/mod.rs +++ b/crates/sandstar-server/src/rest/mod.rs @@ -990,6 +990,25 @@ pub fn router_with_auth( auth_token: Option, rate_limit: u64, sox_state: Option, +) -> Router { + with_global_layers( + api_routes(handle, auth_state, auth_token, sox_state), + rate_limit, + ) +} + +/// Build the core routes, each with its auth layer, without the global +/// layers. +/// +/// A caller that merges more routers (`main.rs`: tags, alerts, roxWarp, +/// simulator) merges them into this router and calls [`with_global_layers`] +/// last. A router merged after that call gets no rate limit, body limit or +/// CORS (R-53, S-35). +pub fn api_routes( + handle: EngineHandle, + auth_state: AuthState, + auth_token: Option, + sox_state: Option, ) -> Router { // Public read-only routes (no auth required) let public = Router::new() @@ -1029,26 +1048,6 @@ pub fn router_with_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. - // This is safer than CorsLayer::permissive() which allows arbitrary - // headers and methods. - let cors = CorsLayer::new() - .allow_origin(tower_http::cors::Any) - .allow_methods([ - Method::GET, - Method::POST, - Method::PUT, - Method::DELETE, - Method::OPTIONS, - ]) - .allow_headers([ - HeaderName::from_static("content-type"), - HeaderName::from_static("authorization"), - HeaderName::from_static("accept"), - ]) - .max_age(Duration::from_secs(3600)); - // Driver framework REST endpoints — backed by the async DriverHandle actor. // BACnet drivers (and future async drivers) are loaded from environment config // asynchronously in the background so they don't block router construction. @@ -1111,8 +1110,7 @@ pub fn router_with_auth( } let driver_routes = crate::drivers::driver_router(driver_handle, auth_state.clone()); - // Merge and apply global middleware. - // Layer order (axum applies bottom-up): CORS → body limit → rate limit → count. + // Global middleware is applied by `with_global_layers`, not here. let mut app = public .merge(protected) .merge(ws_route) @@ -1188,8 +1186,37 @@ pub fn router_with_auth( // Phase 14.0G-7 skeleton: `/editor` is served by `editor_assets::router()`. // Returns the placeholder HTML when `SANDSTAR_WEB_DIR` is unset, or // mounts the built Vue SPA from that directory when set. - app = app.merge(editor_assets::router()); + app.merge(editor_assets::router()) +} + +/// Apply the global HTTP layers to every route merged so far: request +/// counter, rate limit (`rate_limit` requests per second, 0 = unlimited), +/// 1 MiB body limit and CORS. +/// +/// Call this once, after the last `.merge`; routes merged later are not +/// wrapped (R-53). +pub fn with_global_layers(app: Router, rate_limit: u64) -> Router { + // CORS policy: allow any origin (embedded device accessed by various IPs) + // but restrict methods and headers to only what we actually use. + // This is safer than CorsLayer::permissive() which allows arbitrary + // headers and methods. + let cors = CorsLayer::new() + .allow_origin(tower_http::cors::Any) + .allow_methods([ + Method::GET, + Method::POST, + Method::PUT, + Method::DELETE, + Method::OPTIONS, + ]) + .allow_headers([ + HeaderName::from_static("content-type"), + HeaderName::from_static("authorization"), + HeaderName::from_static("accept"), + ]) + .max_age(Duration::from_secs(3600)); + // Layer order (axum applies bottom-up): CORS → body limit → rate limit → count. let mut app = app.layer(middleware::from_fn(count_requests)); // Apply rate limiting only when configured (rate_limit > 0). diff --git a/crates/sandstar-server/tests/auth_layer.rs b/crates/sandstar-server/tests/auth_layer.rs index c4ff344..d481635 100644 --- a/crates/sandstar-server/tests/auth_layer.rs +++ b/crates/sandstar-server/tests/auth_layer.rs @@ -132,11 +132,12 @@ fn build_app(auth: AuthStore) -> (Router, tokio::task::JoinHandle<()>) { sox_tree: None, }; - let app = rest::router_with_auth(handle, auth_state.clone(), None, 0, Some(sox_state)) + // Same order as `main.rs`: every router first, global layers last. + let app = rest::api_routes(handle, auth_state.clone(), None, 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) + (rest::with_global_layers(app, 0), cmd_task) } async fn status( diff --git a/crates/sandstar-server/tests/global_layers.rs b/crates/sandstar-server/tests/global_layers.rs new file mode 100644 index 0000000..c69ce1b --- /dev/null +++ b/crates/sandstar-server/tests/global_layers.rs @@ -0,0 +1,175 @@ +//! Global HTTP layers cover the late-merged routers (R-53, S-35). +//! +//! `main.rs` merges the tags, alerts and roxWarp routers into the core app. +//! The request counter, rate limit, 1 MiB body limit and CORS must wrap +//! those routes too, not only the routes built inside `rest`. +//! +//! Not covered here: the simulator router (`simulator-hal` feature only) and +//! `cluster_disabled_router` (merged instead of the roxWarp router when +//! clustering is off); both are merged at the same place in `main.rs`. + +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 tokio::sync::mpsc; +use tower::ServiceExt; + +#[allow(dead_code)] +mod common; + +const TOKEN: &str = "s35-test-token"; + +/// Late-merged GET routes that answer without a token. +const LATE_READS: &[&str] = &["/api/tags", "/api/alerts/active", "/api/cluster/status"]; + +fn build_app(rate_limit: u64) -> (Router, tokio::task::JoinHandle<()>) { + std::env::remove_var("SANDSTAR_WEB_DIR"); + let auth_state = AuthState::new(AuthStore::with_bearer_token(TOKEN.to_string())); + + 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("s35".into())), + config: ClusterConfig { + node_id: "s35".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, + }; + + // Same order as `main.rs`: every router first, global layers last. + let app = rest::api_routes(handle, auth_state.clone(), None, None) + .merge(rest::tags::router(dyn_store, auth_state.clone())) + .merge(alert_router(alerts, auth_state.clone())) + .merge(rest::roxwarp_router(rw_state, auth_state)); + (rest::with_global_layers(app, rate_limit), cmd_task) +} + +async fn get(app: &Router, path: &str) -> axum::response::Response { + let req = Request::builder() + .uri(path) + .header("origin", "http://example.test") + .body(Body::empty()) + .unwrap(); + app.clone().oneshot(req).await.unwrap() +} + +#[tokio::test] +async fn late_routes_are_rate_limited() { + for path in LATE_READS { + let (app, _task) = build_app(1); + let mut limited = 0; + // Five requests span at most two one-second windows, so at most two + // pass with a limit of one per second. + for _ in 0..5 { + if get(&app, path).await.status() == StatusCode::TOO_MANY_REQUESTS { + limited += 1; + } + } + assert!(limited >= 3, "{path}: only {limited} of 5 requests got 429"); + } +} + +#[tokio::test] +async fn late_write_routes_are_rate_limited_before_auth() { + // Token guessing on a late-merged write route hits the rate limit. + let (app, _task) = build_app(1); + let mut limited = 0; + for i in 0..5 { + let req = Request::builder() + .method("PUT") + .uri("/api/tags/1") + .header("authorization", format!("Bearer guess-{i}")) + .header("content-type", "application/json") + .body(Body::from("{}")) + .unwrap(); + let s = app.clone().oneshot(req).await.unwrap().status(); + if s == StatusCode::TOO_MANY_REQUESTS { + limited += 1; + } else { + assert_eq!(s, StatusCode::UNAUTHORIZED, "guess {i}"); + } + } + assert!(limited >= 3, "only {limited} of 5 guesses got 429"); +} + +#[tokio::test] +async fn late_write_routes_enforce_the_body_limit() { + let (app, _task) = build_app(0); + // Valid JSON over 1 MiB and under axum's 2 MiB default. + let big = format!("{{\"note\":\"{}\"}}", "x".repeat(1_536 * 1024)); + let req = Request::builder() + .method("PUT") + .uri("/api/tags/1") + .header("authorization", format!("Bearer {TOKEN}")) + .header("content-type", "application/json") + .body(Body::from(big)) + .unwrap(); + let s = app.oneshot(req).await.unwrap().status(); + assert_eq!(s, StatusCode::PAYLOAD_TOO_LARGE); +} + +#[tokio::test] +async fn late_routes_get_cors_headers() { + let (app, _task) = build_app(0); + for path in LATE_READS { + let res = get(&app, path).await; + assert_eq!(res.status(), StatusCode::OK, "{path}"); + assert_eq!( + res.headers() + .get("access-control-allow-origin") + .map(|v| v.as_bytes()), + Some(&b"*"[..]), + "{path}: no CORS header" + ); + } +} + +#[tokio::test] +async fn late_routes_answer_cors_preflight() { + let (app, _task) = build_app(0); + for (path, method) in [ + ("/api/alerts/config", "PUT"), + ("/api/tags/1", "PUT"), + ("/api/cluster/query", "POST"), + ] { + let req = Request::builder() + .method("OPTIONS") + .uri(path) + .header("origin", "http://example.test") + .header("access-control-request-method", method) + .header( + "access-control-request-headers", + "authorization,content-type", + ) + .body(Body::empty()) + .unwrap(); + let res = app.clone().oneshot(req).await.unwrap(); + assert_eq!(res.status(), StatusCode::OK, "{path}"); + assert!( + res.headers().contains_key("access-control-allow-methods"), + "{path}: preflight without allow-methods" + ); + } +} diff --git a/docs/Progress/HARDCODED_LIMITS.md b/docs/Progress/HARDCODED_LIMITS.md index 3c6b082..2737e59 100644 --- a/docs/Progress/HARDCODED_LIMITS.md +++ b/docs/Progress/HARDCODED_LIMITS.md @@ -3,7 +3,7 @@ > **Status (2026-11-18)**: re-checked against `master` `b48484b`. Most values are unchanged, but many line numbers moved. Search by constant name rather than trusting the `file:line` below. > > **Moved (same value):** -> - `MAX_PARSE_DEPTH` → `rest/filter.rs:115`; CORS max-age → `rest/mod.rs:748`; `ws.rs` constants → lines 29-33 (S-22). +> - `MAX_PARSE_DEPTH` → `rest/filter.rs:115`; CORS max-age → `rest/mod.rs:1217` (`with_global_layers`, S-35); `ws.rs` constants → lines 29-33 (S-22). > - `CONSECUTIVE_FAIL_THRESHOLD` → `engine.rs:42`. The code comment describes it as the count before the fail counter resets. > - `ERR_YIELD` / `ERR_RESTART` / `ERR_HIBERNATE` → `sandstar-svm/src/types.rs:72-74`. > - `args.rs`: rate limit line 75, port 53, bind 57. @@ -18,7 +18,7 @@ > - `CLIENT_TIMEOUT_SECS` also in `rest/live.rs` and `rest/rows.rs`. > - Driver write level 16, duration 30 s and poll interval 5 s (`drivers/loader.rs`). > - MQTT cache max age 600 s; BACnet discovery 2 s, COV renewal 240 s, foreign-device TTL 300 s, COV cache 600 s. -> - Request body limit 1 MB (`rest/mod.rs`); driver actor channel capacity 64. +> - Request body limit 1 MB (`rest/mod.rs:1231`, `with_global_layers`); since S-35 it also covers the tags, alerts, roxWarp and simulator routes, which had axum's 2 MB `Json` default before. Driver actor channel capacity 64. > - Log files kept: 14 by default (`--log-max-files`, `logging.rs`). > - roxWarp timer bounds: 1..=86400 s (`roxwarp/cluster.rs`). > - roxWarp `PEER_ANOMALY_WARN_INTERVAL_MS` = 60,000 ms (`roxwarp/cluster.rs:225`, R-45/R-27, 2026-11-19): at most one `warn` per minute about bad peer points (NaN/inf value, future timestamp); the rest go to `debug`. Keep hardcoded. @@ -55,7 +55,7 @@ Audited: 2026-03-10 | Rate limit default | 100 req/s | `sandstar-server/src/args.rs` | 65 | **Configurable** — already via `--rate-limit` / `SANDSTAR_RATE_LIMIT`. | | HTTP port default | 8085 | `sandstar-server/src/args.rs` | 43 | **Configurable** — already via `--http-port` / `SANDSTAR_HTTP_PORT`. | | HTTP bind default | 127.0.0.1 | `sandstar-server/src/args.rs` | 47 | **Configurable** — already via `--http-bind` / `SANDSTAR_HTTP_BIND`. | -| CORS max-age | 3600s (1h) | `sandstar-server/src/rest/mod.rs` | 724 | **Document** — standard value. Keep hardcoded. | +| CORS max-age | 3600s (1h) | `sandstar-server/src/rest/mod.rs` | 1217 | **Document** — standard value. Keep hardcoded. | ## WebSocket diff --git a/docs/Progress/OVERVIEW.md b/docs/Progress/OVERVIEW.md index 2c8f938..6903609 100644 --- a/docs/Progress/OVERVIEW.md +++ b/docs/Progress/OVERVIEW.md @@ -238,7 +238,8 @@ Router: `router_with_auth` in `crates/sandstar-server/src/rest/mod.rs`, plus rou - `--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. - Bearer token (`--auth-token` / `SANDSTAR_AUTH_TOKEN`) and SCRAM-SHA-256 (`--auth-user` / `--auth-pass`, `SANDSTAR_AUTH_USER` / `SANDSTAR_AUTH_PASS`). - REST TLS is behind the `tls` cargo feature; the release alias `arm-build-svm` does not enable it. -- Filter depth cap 32, watch cap 64, max channels per watch 256, body limit 1 MB, rate limit on by default (100 req/s). +- Filter depth cap 32, watch cap 64, max channels per watch 256, body limit 1 MB, rate limit on by default (100 req/s, one counter shared by all clients). +- The request counter, rate limit, body limit and CORS wrap every route on the REST port, including the tags, alerts, roxWarp/cluster and simulator routers merged in `main.rs` (`rest::with_global_layers`, applied last; R-53, S-35). Before S-35 those routers were outside these layers. - CORS: any origin, with an explicit method and header list. - Engine calls from REST, the `/api/ws` WebSocket, SOX, roxWarp and drivers wait at most 10 s (`ENGINE_REPLY_TIMEOUT`). REST then answers `503 {"err":"engine timeout"}`; for writes and other state-changing commands the text adds "may still be applied" (R-28, S-20). - On an engine timeout (R-28, S-21):