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
4 changes: 3 additions & 1 deletion HowToUses/03_WEB_EDITOR.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,9 @@ 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`.
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
Expand Down
8 changes: 5 additions & 3 deletions crates/sandstar-server/src/rest/file_ops.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,8 +62,10 @@ pub fn resolve_file_root() -> Option<PathBuf> {

/// `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.
/// 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))
Expand All @@ -72,7 +74,7 @@ pub fn router(state: SoxState, auth_state: crate::auth::AuthState) -> Router {
.route("/file/{*path}", put(put_file))
.with_state(state);
super::require_upgrade_auth(read, auth_state.clone())
.merge(super::require_auth(write, auth_state))
.merge(super::require_write_auth(write, auth_state))
}

// ── Handlers ───────────────────────────────────────
Expand Down
46 changes: 46 additions & 0 deletions crates/sandstar-server/src/rest/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -660,6 +660,52 @@ pub(crate) async fn check_upgrade_auth(
Err(StatusCode::UNAUTHORIZED)
}

/// Gate for browser writes that cannot carry a bearer header: today only
/// `PUT /file/*`, used by the editor to upload kits (R-56, S-37).
///
/// - auth not configured: every request passes (field default);
/// - valid bearer header: passes, `Origin` is not checked (same as
/// [`check_auth`]);
/// - valid session cookie: passes only with an `Origin` header that matches
/// the `Host` or the allowlist. A missing or foreign `Origin` gets 403.
/// Browsers always send `Origin` on `PUT`, so a cookie write without one
/// is not the editor. This backs up the cookie's `SameSite=Strict`
/// against cross-site request forgery;
/// - otherwise 401.
pub(crate) async fn check_write_auth(
axum::extract::State(auth_state): axum::extract::State<AuthState>,
request: Request,
next: middleware::Next,
) -> Result<Response, StatusCode> {
if !auth_state.store.is_auth_required() {
return Ok(next.run(request).await);
}
let headers = request.headers();
let bearer = headers
.get(axum::http::header::AUTHORIZATION)
.and_then(|v| v.to_str().ok())
.and_then(|v| v.strip_prefix("Bearer "));
if bearer.is_some_and(|t| auth_state.check_token(t)) {
return Ok(next.run(request).await);
}
if session_cookies(headers).any(|t| auth_state.check_token(t)) {
// `origin_allowed` lets a request without `Origin` through (it is
// built for WebSocket clients); a cookie write must have one, so
// this check stays here and must not be dropped.
let has_origin = headers.contains_key(axum::http::header::ORIGIN);
if has_origin && origin_allowed(headers, &auth_state) {
return Ok(next.run(request).await);
}
return Err(StatusCode::FORBIDDEN);
}
Err(StatusCode::UNAUTHORIZED)
}

/// Wrap every route already in `router` with [`check_write_auth`].
pub fn require_write_auth(router: Router, auth_state: AuthState) -> Router {
router.route_layer(middleware::from_fn_with_state(auth_state, check_write_auth))
}

/// Wrap every route already in `router` with [`check_upgrade_auth`].
pub fn require_upgrade_auth(router: Router, auth_state: AuthState) -> Router {
router.route_layer(middleware::from_fn_with_state(
Expand Down
146 changes: 136 additions & 10 deletions crates/sandstar-server/tests/auth_layer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -326,17 +326,143 @@ async fn tree_and_file_reads_need_a_credential_when_auth_is_configured() {
}

#[tokio::test]
async fn file_upload_stays_bearer_only() {
// The read gate accepts the session cookie; the write layer must not.
async fn file_upload_accepts_a_cookie_only_with_an_allowed_origin() {
// R-56, S-37: the editor uploads kits with its session cookie. A cookie
// write needs an Origin header that matches the Host or the allowlist.
let mut store = AuthStore::with_bearer_token(TOKEN.to_string());
store.set_allowed_origins(vec!["http://localhost:8091".to_string()]);
let (app, _task) = build_app(store);
let host = || ("host", "device.local".to_string());
let cookie = || ("cookie", format!("a=b; sandstar_session={TOKEN}"));
let bad_cookie = || ("cookie", "sandstar_session=forged".to_string());
let origin = |o: &str| ("origin", o.to_string());
let bearer = || ("authorization", format!("Bearer {TOKEN}"));
// No file root in tests: a request that passes the gate gets 503.
let passed = StatusCode::SERVICE_UNAVAILABLE;
let cases: Vec<(&str, Vec<(&str, String)>, StatusCode)> = vec![
("none", vec![host()], StatusCode::UNAUTHORIZED),
(
"forged cookie, same-host origin",
vec![host(), bad_cookie(), origin("http://device.local")],
StatusCode::UNAUTHORIZED,
),
(
"cookie, same-host origin",
vec![host(), cookie(), origin("http://device.local")],
passed,
),
(
"cookie, allowlisted origin",
vec![host(), cookie(), origin("http://localhost:8091")],
passed,
),
(
"cookie, no origin",
vec![host(), cookie()],
StatusCode::FORBIDDEN,
),
(
"cookie, foreign origin",
vec![host(), cookie(), origin("http://evil.example")],
StatusCode::FORBIDDEN,
),
(
"cookie, opaque origin",
vec![host(), cookie(), origin("null")],
StatusCode::FORBIDDEN,
),
(
"forged cookie before the valid one",
vec![
host(),
(
"cookie",
format!("sandstar_session=forged; sandstar_session={TOKEN}"),
),
origin("http://device.local"),
],
passed,
),
(
"valid cookie in a second Cookie header",
vec![
host(),
bad_cookie(),
cookie(),
origin("http://device.local"),
],
passed,
),
(
"cookie, same host other port",
vec![host(), cookie(), origin("http://device.local:8091")],
StatusCode::FORBIDDEN,
),
(
"cookie, subdomain origin",
vec![host(), cookie(), origin("http://a.device.local")],
StatusCode::FORBIDDEN,
),
(
"cookie, non-http scheme",
vec![host(), cookie(), origin("ftp://device.local")],
StatusCode::FORBIDDEN,
),
(
"cookie, origin differs only in case",
vec![host(), cookie(), origin("http://DEVICE.local")],
passed,
),
("bearer, no origin", vec![host(), bearer()], passed),
(
"bearer, foreign origin",
vec![host(), bearer(), origin("http://evil.example")],
passed,
),
];
for (name, headers, want) in cases {
let s = put_with(&app, "/file/s37-probe.txt", &headers).await;
assert_eq!(s, want, "{name}");
}
}

#[tokio::test]
async fn other_write_routes_still_reject_the_cookie() {
// Only `PUT /file/*` accepts the cookie; the rest stay bearer-only.
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);
for (m, p, b) in WRITE_ROUTES {
if p.starts_with("/file/") {
continue;
}
let req = Request::builder()
.method(*m)
.uri(*p)
.header("host", "device.local")
.header("origin", "http://device.local")
.header("cookie", format!("sandstar_session={TOKEN}"))
.header("content-type", "application/json")
.body(Body::from(b.to_string()))
.unwrap();
let s = app.clone().oneshot(req).await.unwrap().status();
assert_eq!(s, StatusCode::UNAUTHORIZED, "{m} {p}");
}
}

#[tokio::test]
async fn file_upload_stays_open_when_auth_is_not_configured() {
let (app, _task) = build_app(AuthStore::new());
let headers = [("origin", "http://evil.example".to_string())];
let s = put_with(&app, "/file/s37-probe.txt", &headers).await;
assert_eq!(s, StatusCode::SERVICE_UNAVAILABLE);
}

async fn put_with(app: &Router, path: &str, headers: &[(&str, String)]) -> StatusCode {
let mut req = Request::builder().method("PUT").uri(path);
for (k, v) in headers {
req = req.header(*k, v.as_str());
}
let req = req.body(Body::from("x")).unwrap();
app.clone().oneshot(req).await.unwrap().status()
}

#[tokio::test]
Expand Down
2 changes: 1 addition & 1 deletion docs/Progress/OVERVIEW.md
Original file line number Diff line number Diff line change
Expand Up @@ -223,7 +223,7 @@ Router: `router_with_auth` in `crates/sandstar-server/src/rest/mod.rs`, plus rou
| `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/*` | **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`) |
| `PUT /file/*` | **yes** (S-31; `check_write_auth` since S-37) | File upload (with `--sox`). Bearer, or the session cookie with a required `Origin` that matches the `Host` or `--ws-allowed-origins` (missing or foreign `Origin`: 403); the editor uploads kits with its cookie. The other write routes stay bearer-only |
| `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) |
| `GET /api/alerts/config` (password masked), `/recipients`, `/active`, `/history` | no | Alert management (read) |
Expand Down
Loading