From 71d1e089804aab161a666aee7f3aae3312372e29 Mon Sep 17 00:00:00 2001 From: Turker Mertkan Aytac Date: Sat, 21 Nov 2026 15:09:01 +0300 Subject: [PATCH] fix(rest): gate SOX tree and file reads behind the editor gate (R-55, S-33) GET /api/sox/tree, /api/sox/comp/{id}, /api/sox/palette, /api/sox/names and GET /file/* now sit behind check_upgrade_auth (bearer header or sandstar_session cookie, plus Origin check), the same gate as /live/sedonaState, which carries the same component tree. Routes and auth layer: - inside check_upgrade_auth: the four SOX tree reads and GET /file/*; - PUT /file/* stays behind require_auth (bearer only); - /library/ and GET /tags stay outside on purpose (read-only stubs, no device data; comment in rest/mod.rs). Behavior: with no auth configured (field default) every request passes, unchanged. With auth on, the browser editor keeps working: it fetches /file/* same-origin with the session cookie after SCRAM login (S-32b). Tests: auth_layer.rs covers 401 without/with bad credential (GET and HEAD), exact status with cookie or bearer, same-host Origin accepted, foreign Origin 403 with bearer or cookie, PUT /file with cookie only 401, library stubs open, auth off open. The main test fails on the old code. Gates: 2890 passed, 0 failed. Local E2E with auth on and the trkrDevelop editor: /file and /api/sox/tree 200 after login, 401 without. docs: HARDCODED_LIMITS.md not needed, only tests changed there. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QKRNiek8qYRoRt7dcrDDVC --- HowToUses/02_REST_API.md | 1 + crates/sandstar-server/src/rest/file_ops.rs | 8 +- crates/sandstar-server/src/rest/mod.rs | 12 +- crates/sandstar-server/src/rest/sox_api.rs | 6 +- crates/sandstar-server/tests/auth_layer.rs | 118 +++++++++++++++++++- docs/Progress/OVERVIEW.md | 5 +- 6 files changed, 140 insertions(+), 10 deletions(-) diff --git a/HowToUses/02_REST_API.md b/HowToUses/02_REST_API.md index 54c5987..853d471 100644 --- a/HowToUses/02_REST_API.md +++ b/HowToUses/02_REST_API.md @@ -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 " # Single component with slots and links curl http://localhost:8085/api/sox/comp/200 diff --git a/crates/sandstar-server/src/rest/file_ops.rs b/crates/sandstar-server/src/rest/file_ops.rs index 6c66b1b..1a744d2 100644 --- a/crates/sandstar-server/src/rest/file_ops.rs +++ b/crates/sandstar-server/src/rest/file_ops.rs @@ -60,7 +60,10 @@ pub fn resolve_file_root() -> Option { 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 bearer auth layer (R-2). +/// 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)) @@ -68,7 +71,8 @@ pub fn router(state: SoxState, auth_state: crate::auth::AuthState) -> Router { 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_auth(write, auth_state)) } // ── Handlers ─────────────────────────────────────── diff --git a/crates/sandstar-server/src/rest/mod.rs b/crates/sandstar-server/src/rest/mod.rs index bd5f461..b476e97 100644 --- a/crates/sandstar-server/src/rest/mod.rs +++ b/crates/sandstar-server/src/rest/mod.rs @@ -636,7 +636,8 @@ pub(crate) fn has_valid_credential( } /// Gate for the editor endpoints (`/live`, `/live/sedonaState`, -/// `/api/rows`), run before the WebSocket upgrade (R-52, S-32). +/// `/api/rows`), run before the WebSocket upgrade (R-52, S-32). It also +/// gates the SOX tree reads and `GET /file/*` (R-55, S-33). /// /// Browsers cannot send an `Authorization` header on an upgrade, so a /// session cookie from `POST /api/auth` is accepted too. With auth on, a @@ -1158,13 +1159,20 @@ pub fn router_with_auth( auth_state.clone(), ); // Phase 14.0G-5: editor `/library/` + `/tags` compatibility stubs. + // Left outside the gates on purpose: read-only stubs that return + // `[]` or library names, no device data (S-33). let library_route = library::router(live::LiveState { tree: sox.tree.clone(), manifest_db: sox.manifest_db.clone(), dyn_store: sox.dyn_store.clone(), }); app = app - .merge(sox_api::public_router(sox.clone())) + // Tree reads carry the same data as `/live/sedonaState`, so they + // sit behind the same gate (R-55, S-33). + .merge(require_upgrade_auth( + sox_api::public_router(sox.clone()), + auth_state.clone(), + )) .merge(require_auth( sox_api::protected_router(sox), auth_state.clone(), diff --git a/crates/sandstar-server/src/rest/sox_api.rs b/crates/sandstar-server/src/rest/sox_api.rs index 4c68bf4..d734be7 100644 --- a/crates/sandstar-server/src/rest/sox_api.rs +++ b/crates/sandstar-server/src/rest/sox_api.rs @@ -835,10 +835,10 @@ pub async fn get_names(State(state): State) -> Response { .into_response() } -/// Build the SOX API sub-router (public read + protected write routes). +/// Build the SOX API read sub-router. /// -/// The caller is responsible for merging these into the main app -/// and applying auth middleware to the write routes. +/// The caller wraps it with `require_upgrade_auth` (bearer or session +/// cookie; R-55, S-33) and the write routes with `require_auth`. pub fn public_router(state: SoxApiState) -> axum::Router { use axum::routing::get; axum::Router::new() diff --git a/crates/sandstar-server/tests/auth_layer.rs b/crates/sandstar-server/tests/auth_layer.rs index 6c0a1c5..c4ff344 100644 --- a/crates/sandstar-server/tests/auth_layer.rs +++ b/crates/sandstar-server/tests/auth_layer.rs @@ -6,6 +6,8 @@ //! - with the right token the request reaches the handler (not 401); //! - with no auth configured nothing gets 401 (field behavior unchanged). //! +//! The SOX tree and `/file/*` reads sit behind the editor gate (R-55, S-33). +//! //! Limitation: the route list is maintained by hand. A new write route that //! is not added to `WRITE_ROUTES` is not covered by this test. @@ -84,7 +86,6 @@ const READ_ROUTES: &[&str] = &[ "/api/about", "/api/read?filter=point", "/api/drivers", - "/api/sox/tree", "/api/tags", "/api/alerts/config", "/api/cluster/status", @@ -238,6 +239,121 @@ async fn an_empty_configured_token_does_not_open_write_routes() { } } +// ── SOX tree and file reads (R-55, S-33) ──────────────────── + +/// Reads that carry the component tree or device files: behind the editor +/// gate (bearer or session cookie, plus Origin). +/// Each entry is (path, status once the gate lets the request through); +/// exact so a route that is not mounted (404) cannot pass. `build_app` +/// unsets the file root, so `/file/*` answers 503 behind the gate. +const GATED_READS: &[(&str, StatusCode)] = &[ + ("/api/sox/tree", StatusCode::OK), + // The test tree is empty: the handler answers 404 for comp 0. + ("/api/sox/comp/0", StatusCode::NOT_FOUND), + ("/api/sox/palette", StatusCode::OK), + ("/api/sox/names", StatusCode::OK), + ( + "/file/sedona/manifests/x/x.xml", + StatusCode::SERVICE_UNAVAILABLE, + ), +]; + +async fn head_with(app: &Router, path: &str, headers: &[(&str, String)]) -> StatusCode { + let mut req = Request::builder().method("HEAD").uri(path); + for (k, v) in headers { + req = req.header(*k, v.as_str()); + } + let req = req.body(Body::empty()).unwrap(); + app.clone().oneshot(req).await.unwrap().status() +} + +async fn get_with(app: &Router, path: &str, headers: &[(&str, String)]) -> StatusCode { + let mut req = Request::builder().method("GET").uri(path); + for (k, v) in headers { + req = req.header(*k, v.as_str()); + } + let req = req.body(Body::empty()).unwrap(); + app.clone().oneshot(req).await.unwrap().status() +} + +#[tokio::test] +async fn tree_and_file_reads_need_a_credential_when_auth_is_configured() { + let (app, _task) = build_app(AuthStore::with_bearer_token(TOKEN.to_string())); + let cookie = || ("cookie", format!("a=b; sandstar_session={TOKEN}")); + for &(p, want) in GATED_READS { + assert_eq!( + head_with(&app, p, &[]).await, + StatusCode::UNAUTHORIZED, + "HEAD {p} none" + ); + assert_eq!( + get_with(&app, p, &[]).await, + StatusCode::UNAUTHORIZED, + "{p} none" + ); + let bad = [("cookie", "sandstar_session=nope".to_string())]; + assert_eq!( + get_with(&app, p, &bad).await, + StatusCode::UNAUTHORIZED, + "{p} bad cookie" + ); + let wrong = [("authorization", "Bearer nope".to_string())]; + assert_eq!( + get_with(&app, p, &wrong).await, + StatusCode::UNAUTHORIZED, + "{p} wrong" + ); + // Same-origin editor fetch: the browser may send an Origin equal to Host. + let same = vec![ + cookie(), + ("host", "dev.local:8091".to_string()), + ("origin", "http://dev.local:8091".to_string()), + ]; + for ok in [vec![cookie()], vec![bearer()], same] { + assert_eq!(get_with(&app, p, &ok).await, want, "{p} {ok:?}"); + } + for cred in [bearer(), cookie()] { + let evil = [cred, ("origin", "http://evil.example".to_string())]; + assert_eq!( + get_with(&app, p, &evil).await, + StatusCode::FORBIDDEN, + "{p} {evil:?}" + ); + } + } +} + +#[tokio::test] +async fn file_upload_stays_bearer_only() { + // The read gate accepts the session cookie; the write layer must not. + let (app, _task) = build_app(AuthStore::with_bearer_token(TOKEN.to_string())); + let req = Request::builder() + .method("PUT") + .uri("/file/s33-probe.txt") + .header("cookie", format!("sandstar_session={TOKEN}")) + .body(Body::from("x")) + .unwrap(); + let s = app.clone().oneshot(req).await.unwrap().status(); + assert_eq!(s, StatusCode::UNAUTHORIZED); +} + +#[tokio::test] +async fn library_stubs_stay_open_when_auth_is_configured() { + let (app, _task) = build_app(AuthStore::with_bearer_token(TOKEN.to_string())); + for p in ["/library/", "/tags"] { + assert_eq!(get_with(&app, p, &[]).await, StatusCode::OK, "{p}"); + } +} + +#[tokio::test] +async fn tree_and_file_reads_stay_open_when_auth_is_not_configured() { + let (app, _task) = build_app(AuthStore::new()); + for &(p, want) in GATED_READS { + let evil = [("origin", "http://evil.example".to_string())]; + assert_eq!(get_with(&app, p, &evil).await, want, "{p}"); + } +} + // ── WebSocket and editor endpoints (R-52, S-32) ───────────── /// Editor endpoints gated before the WebSocket upgrade. diff --git a/docs/Progress/OVERVIEW.md b/docs/Progress/OVERVIEW.md index 0d079dc..2c8f938 100644 --- a/docs/Progress/OVERVIEW.md +++ b/docs/Progress/OVERVIEW.md @@ -218,10 +218,11 @@ Router: `router_with_auth` in `crates/sandstar-server/src/rest/mod.rs`, plus rou | `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`) | +| `GET /api/sox/tree`, `/api/sox/comp/{id}`, `/api/sox/palette`, `/api/sox/names` | **yes** (S-33, `check_upgrade_auth`) | SOX component tree (with `--sox`). Bearer or `sandstar_session` cookie, plus Origin check | | `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` | **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`) | +| `GET /file/*` | **yes** (S-33, `check_upgrade_auth`) | File download (with `--sox`); the editor fetches kit files same-origin with the session cookie | +| `/library/`, `GET /tags` | no | 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) | | `PUT /api/tags/{comp_id}`, `DELETE /api/tags/{comp_id}/{key}` | **yes** (S-31) | Dynamic tags (write) |