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
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
8 changes: 6 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,19 @@ 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 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))
.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_auth(write, auth_state))
}

// ── Handlers ───────────────────────────────────────
Expand Down
12 changes: 10 additions & 2 deletions crates/sandstar-server/src/rest/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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(),
Expand Down
6 changes: 3 additions & 3 deletions crates/sandstar-server/src/rest/sox_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -835,10 +835,10 @@ pub async fn get_names(State(state): State<SoxApiState>) -> 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()
Expand Down
118 changes: 117 additions & 1 deletion crates/sandstar-server/tests/auth_layer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -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.
Expand Down
5 changes: 3 additions & 2 deletions docs/Progress/OVERVIEW.md
Original file line number Diff line number Diff line change
Expand Up @@ -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) |
Expand Down
Loading