diff --git a/crates/tessera-hub/src/api/routes.rs b/crates/tessera-hub/src/api/routes.rs index 4cb190e..1055009 100644 --- a/crates/tessera-hub/src/api/routes.rs +++ b/crates/tessera-hub/src/api/routes.rs @@ -765,12 +765,13 @@ async fn start_reconstitute( headers: HeaderMap, Json(req): Json, ) -> Result, StatusCode> { - let actor = admin_write(&state, peer, &headers)?; - let destination = if actor.browser { - browser_export_path(&state, &req.target_path)? - } else { - req.target_path.clone().into() - }; + admin_write(&state, peer, &headers)?; + // Every caller, browser or API token, may only name a file inside the hub's exports directory, + // and never one that already exists. + let destination = browser_export_path(&state, &req.target_path)?; + if destination.symlink_metadata().is_ok() { + return Err(StatusCode::CONFLICT); + } let vault = state.vault.read().await; if vault .get_snapshot(req.snapshot_id) @@ -1600,6 +1601,36 @@ mod tests { assert_eq!(r.status(), StatusCode::UNAUTHORIZED); } + #[tokio::test] + async fn reconstitute_targets_stay_inside_the_exports_directory_for_every_caller() { + let dir = tempfile::tempdir().unwrap(); + let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault") + .await + .unwrap(); + state.admin.token = Some("synthetic-admin-token-of-32-chars!".into()); + let app = router(state); + let attempt = |path: &str| { + Request::post("/api/v1/reconstitute") + .extension(ConnectInfo("203.0.113.30:9000".parse::().unwrap())) + .header(header::AUTHORIZATION, "Bearer synthetic-admin-token-of-32-chars!") + .header(header::CONTENT_TYPE, "application/json") + .body(Body::from( + serde_json::json!({"snapshot_id": Uuid::new_v4(), "target_path": path}).to_string(), + )) + .unwrap() + }; + for path in ["/etc/passwd", "../escape", "a/b", "..", ""] { + let r = app.clone().oneshot(attempt(path)).await.unwrap(); + assert_eq!(r.status(), StatusCode::BAD_REQUEST, "{path}"); + } + // a plain file name passes confinement (the unknown snapshot is what stops it) + let r = app.clone().oneshot(attempt("dump.sql")).await.unwrap(); + assert_eq!(r.status(), StatusCode::NOT_FOUND); + std::fs::write(dir.path().join("exports").join("taken.sql"), b"keep").unwrap(); + let r = app.oneshot(attempt("taken.sql")).await.unwrap(); + assert_eq!(r.status(), StatusCode::CONFLICT); + } + #[tokio::test] async fn a_failed_denial_audit_write_still_answers_401() { let dir = tempfile::tempdir().unwrap(); diff --git a/crates/tessera-store/src/offsite.rs b/crates/tessera-store/src/offsite.rs index c8afb54..21772ac 100644 --- a/crates/tessera-store/src/offsite.rs +++ b/crates/tessera-store/src/offsite.rs @@ -172,7 +172,7 @@ impl Offsite { )?; let size = file.as_file().metadata()?.len(); file.as_file().sync_all()?; - file.persist(dest)?; + file.persist_noclobber(dest)?; Ok(size) } diff --git a/crates/tessera-store/src/vault.rs b/crates/tessera-store/src/vault.rs index 3dcef97..9845423 100644 --- a/crates/tessera-store/src/vault.rs +++ b/crates/tessera-store/src/vault.rs @@ -655,7 +655,8 @@ impl Vault { } let len = temp.as_file().metadata()?.len(); temp.as_file().sync_all()?; - temp.persist(dest)?; + // never replace a file that is already there + temp.persist_noclobber(dest)?; Ok(len) } diff --git a/tests/fixtures/capture-mysql.py b/tests/fixtures/capture-mysql.py index f940ecf..eacbcb4 100644 --- a/tests/fixtures/capture-mysql.py +++ b/tests/fixtures/capture-mysql.py @@ -89,8 +89,8 @@ def main(): assert result["phase"] == "dump_failed" and result["snapshot_id"] is None, result continue assert result["status"] == "completed", (name, result) - target = root / f"{name}.sql" - session = api("reconstitute", {"snapshot_id": result["snapshot_id"], "target_path": str(target)}) + target = root / "hub" / "exports" / f"{name}.sql" + session = api("reconstitute", {"snapshot_id": result["snapshot_id"], "target_path": target.name}) wait_until(lambda: api(f"reconstitute/{session['session_id']}")["state"] == "completed") sql = target.read_text() assert all(marker in sql for marker in ("sample_view", "sample_routine", "sample_event", "backup 🛰")) diff --git a/tests/fixtures/capture-postgres.py b/tests/fixtures/capture-postgres.py index 8995b1f..fa60c24 100644 --- a/tests/fixtures/capture-postgres.py +++ b/tests/fixtures/capture-postgres.py @@ -125,8 +125,8 @@ def main(): assert failed["snapshot_id"] is None snapshots = api("snapshots") assert {snap["id"] for snap in snapshots} == {successful["snapshot_id"], through_bastion["snapshot_id"]} - dump = root / "backup.dump" - session = api("reconstitute", {"snapshot_id": successful["snapshot_id"], "target_path": str(dump)}) + dump = root / "hub" / "exports" / "backup.dump" + session = api("reconstitute", {"snapshot_id": successful["snapshot_id"], "target_path": dump.name}) wait_until(lambda: api(f"reconstitute/{session['session_id']}")["state"] == "completed") command("pg_restore", *pg, "-d", "target_db", "--exit-on-error", dump) restored = command("psql", *pg, "-d", "target_db", "-Atc",