From c14e0af8f911d88cfee90b397672ed1a144c63ee Mon Sep 17 00:00:00 2001 From: RealDoc06 <73218979+RealDoc06@users.noreply.github.com> Date: Thu, 19 Nov 2026 04:46:01 +0100 Subject: [PATCH 01/33] docs: add security policy --- SECURITY.md | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 SECURITY.md diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..d534c94 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,33 @@ +# Security policy + +## Supported versions + +BeaconSync is in alpha. Only the latest `0.1.0-alpha` release gets security fixes; update to it +before reporting. + +## Reporting a vulnerability + +Please report privately, not in a public issue: open the repo's **Security** tab and choose +**Report a vulnerability** (GitHub private vulnerability reporting). + +Include what is affected, the version, and how to reproduce it. + +## What to expect + +- An acknowledgement within 7 days. +- An assessment and, if confirmed, a fix plan shortly after. Serious issues are fixed in a new + release first and disclosed in a GitHub security advisory once it is out. +- Credit in the advisory, unless you'd rather stay anonymous. + +## Scope + +- The `beacon` CLI and server agent (`crates/cli`, `crates/core`) +- The desktop app (`apps/desktop`) +- The companion mods (`mods/`) +- The hub server (`crates/hub`) and the public hub at `beaconsync.realdoc06.it` + +Out of scope: denial of service by flooding the public hub, issues in Minecraft, mod loaders, +Prism Launcher, Modrinth or CurseForge themselves, and mods a pack owner chose to ship (a pack +runs its mods' code by design). + +Please test against your own hub (`beacon-hub`), not the public one. From 2d39e078ee5a1ffd836d46c0b787f87888b78477 Mon Sep 17 00:00:00 2001 From: RealDoc06 <73218979+RealDoc06@users.noreply.github.com> Date: Thu, 19 Nov 2026 04:46:31 +0100 Subject: [PATCH 02/33] fix(core): only fetch BeaconSync releases for real version strings The server agent's update action passes a hub supplied version into the GitHub release URL. Dot segments in it were resolved by the URL parser, so the agent could be pointed at a release outside BeaconSync's repo. Versions are now limited to version characters before any request. --- crates/core/src/release.rs | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/crates/core/src/release.rs b/crates/core/src/release.rs index c83f495..3d04377 100644 --- a/crates/core/src/release.rs +++ b/crates/core/src/release.rs @@ -104,8 +104,10 @@ pub async fn latest() -> Result { } } -/// A release by version ("0.1.0-alpha.2") or tag ("v0.1.0-alpha.2"). +/// A release by version ("0.1.0-alpha.2") or tag ("v0.1.0-alpha.2"). The version can come from +/// the hub, so it must look like one: anything else could steer the URL to another repo. pub async fn by_version(version: &str) -> Result { + ensure!(is_version(version), "{version:?} is not a BeaconSync version"); let tag = format!("v{}", version.trim_start_matches('v')); match manifest(&format!("download/{tag}")).await { Some(r) => Ok(r), @@ -143,6 +145,11 @@ pub async fn download(asset: &Asset, dest: &Path, on: impl Fn(u64)) -> Result<() Ok(()) } +/// Version characters only (`0-9a-zA-Z.-+`), so it is safe inside a URL path. +fn is_version(v: &str) -> bool { + (1..=64).contains(&v.len()) && v.bytes().all(|b| b.is_ascii_alphanumeric() || b"-.+".contains(&b)) +} + /// Semver order for `MAJOR.MINOR.PATCH[-PRE]`: a prerelease sorts before its release and /// numeric prerelease parts compare as numbers ("alpha.10" > "alpha.9"). pub fn newer(a: &str, b: &str) -> bool { @@ -177,7 +184,15 @@ pub fn cli_asset() -> String { #[cfg(test)] mod tests { - use super::newer; + use super::{is_version, newer}; + + #[test] + fn only_version_strings_reach_release_urls() { + assert!(is_version("0.1.0-alpha.14") && is_version("v1.2.3+build.5")); + for bad in ["", "9.9.9/../../../other/repo", "1.0%2f..", "1.0?x", "1.0#x", "1.0\\.."] { + assert!(!is_version(bad), "{bad}"); + } + } #[test] fn orders_versions_like_semver() { From 775306d9aa927e1a533800e04f0c3fafa7ad84c7 Mon Sep 17 00:00:00 2001 From: RealDoc06 <73218979+RealDoc06@users.noreply.github.com> Date: Thu, 19 Nov 2026 04:47:26 +0100 Subject: [PATCH 03/33] fix(hub): check passwords without holding the database lock Login, register and the /device page ran Argon2 on an async worker while holding the hub's single database lock, so a burst of unauthenticated login attempts stalled every other request. The hash is now read under the lock and verified on the blocking pool. --- crates/hub/src/pages.rs | 3 ++- crates/hub/src/routes.rs | 24 ++++++++++++++++-------- 2 files changed, 18 insertions(+), 9 deletions(-) diff --git a/crates/hub/src/pages.rs b/crates/hub/src/pages.rs index 4ef6f73..4e0c910 100644 --- a/crates/hub/src/pages.rs +++ b/crates/hub/src/pages.rs @@ -80,7 +80,8 @@ pub struct DeviceForm { } pub async fn device_submit(State(s): State, Form(f): Form) -> Html { - let result = check_credentials(&s, &Credentials { username: f.username, password: f.password }) + let result = check_credentials(&s, Credentials { username: f.username, password: f.password }) + .await .and_then(|u| approve_device(&s, &u.id, &f.user_code)); match result { Ok(()) => page("Approved", "

Approved

You can close this page and go back to the terminal.

"), diff --git a/crates/hub/src/routes.rs b/crates/hub/src/routes.rs index ffcd341..e284b46 100644 --- a/crates/hub/src/routes.rs +++ b/crates/hub/src/routes.rs @@ -152,7 +152,7 @@ async fn register(State(s): State, Json(c): Json) -> Resu if c.password.len() < 8 { return Err(Error::bad("password must be at least 8 characters")); } - let pw = hash_password(&c.password)?; + let pw = argon(move || hash_password(&c.password)).await??; let db = s.db(); let id = new_id(); let taken = db.query_row("select 1 from users where username = ?1", params![username], |_| Ok(())).optional()?.is_some(); @@ -164,22 +164,30 @@ async fn register(State(s): State, Json(c): Json) -> Resu Ok(Json(AuthResponse { token, user: User { id, username: username.into() } })) } +/// Runs Argon2 on the blocking pool: it takes tens of milliseconds of CPU, which would otherwise +/// stall an async worker (and, under the DB lock, every request). +async fn argon(f: impl FnOnce() -> T + Send + 'static) -> Result { + tokio::task::spawn_blocking(f).await.map_err(|e| anyhow::Error::from(e).into()) +} + /// Checks a username/password pair (also used by the /device web page). -pub fn check_credentials(s: &AppState, c: &Credentials) -> Result { - let db = s.db(); - let row: Option<(String, String, String)> = db +pub async fn check_credentials(s: &AppState, c: Credentials) -> Result { + let row: Option<(String, String, String)> = s + .db() .query_row("select id, username, pw_hash from users where username = ?1", params![c.username.trim()], |r| { Ok((r.get(0)?, r.get(1)?, r.get(2)?)) }) .optional()?; - match row { - Some((id, username, hash)) if verify_password(&c.password, &hash) => Ok(User { id, username }), - _ => Err(Error(StatusCode::UNAUTHORIZED, "wrong username or password".into())), + let wrong = || Error(StatusCode::UNAUTHORIZED, "wrong username or password".into()); + let (id, username, hash) = row.ok_or_else(wrong)?; + if !argon(move || verify_password(&c.password, &hash)).await? { + return Err(wrong()); } + Ok(User { id, username }) } async fn login(State(s): State, Json(c): Json) -> Result> { - let user = check_credentials(&s, &c)?; + let user = check_credentials(&s, c).await?; let token = issue_token(&s.db(), &user.id, "login")?; Ok(Json(AuthResponse { token, user })) } From 77369390e10bfc92fd44415996df7b44053706ed Mon Sep 17 00:00:00 2001 From: RealDoc06 <73218979+RealDoc06@users.noreply.github.com> Date: Thu, 19 Nov 2026 04:48:55 +0100 Subject: [PATCH 04/33] fix(hub): limit wrong password attempts per account Password sign in (API and /device page) had no limit on guesses. After 10 wrong passwords for an account within 15 minutes the hub answers 429 for the rest of that window. Attempts are counted before the check, so parallel guesses can't exceed the limit, and existing tokens keep working. --- crates/hub/src/routes.rs | 33 ++++++++++++++++++++++++++++++++- crates/hub/src/tests.rs | 24 ++++++++++++++++++++++++ docs/ARCHITECTURE.md | 2 +- 3 files changed, 57 insertions(+), 2 deletions(-) diff --git a/crates/hub/src/routes.rs b/crates/hub/src/routes.rs index e284b46..b008f97 100644 --- a/crates/hub/src/routes.rs +++ b/crates/hub/src/routes.rs @@ -37,8 +37,15 @@ pub struct Inner { waiters: Mutex>>, /// Live console and backups per server, kept in memory only. consoles: Mutex>, + /// Failed sign ins per user id: (count, start of the window). + failures: Mutex>, } +/// Wrong passwords allowed per account within [`FAILURE_WINDOW`] seconds before sign ins with a +/// password are refused for the rest of it. Existing tokens keep working. +const MAX_FAILURES: u32 = 10; +const FAILURE_WINDOW: i64 = 15 * 60; + /// Lines kept per server for viewers that open the console later. const CONSOLE_LINES: usize = 2000; @@ -70,13 +77,28 @@ impl AppState { std::fs::create_dir_all(&config.data)?; let db = db::open(&config.data.join("hub.db"))?; let store = ObjectStore::new(config.data.join("objects")); - Ok(Self(Arc::new(Inner { db: Mutex::new(db), store, config, waiters: Mutex::default(), consoles: Mutex::default() }))) + Ok(Self(Arc::new(Inner { + db: Mutex::new(db), + store, + config, + waiters: Mutex::default(), + consoles: Mutex::default(), + failures: Mutex::default(), + }))) } pub fn db(&self) -> MutexGuard<'_, Connection> { self.0.db.lock().unwrap_or_else(|e| e.into_inner()) } + /// Runs `f` on a user's failed sign in count, restarting it once its window is over. + fn failures(&self, user: &str, f: impl FnOnce(&mut (u32, i64)) -> T) -> T { + let mut all = self.failures.lock().unwrap_or_else(|e| e.into_inner()); + let now = now(); + all.retain(|_, (_, since)| now - *since < FAILURE_WINDOW); + f(all.entry(user.to_string()).or_insert((0, now))) + } + fn waiter(&self, server: &str) -> Arc { self.waiters.lock().unwrap_or_else(|e| e.into_inner()).entry(server.to_string()).or_default().clone() } @@ -180,9 +202,18 @@ pub async fn check_credentials(s: &AppState, c: Credentials) -> Result { .optional()?; let wrong = || Error(StatusCode::UNAUTHORIZED, "wrong username or password".into()); let (id, username, hash) = row.ok_or_else(wrong)?; + // Counted before checking, so parallel guesses can't all slip in under the limit. + let allowed = s.failures(&id, |(count, _)| { + *count += 1; + *count <= MAX_FAILURES + }); + if !allowed { + return Err(Error(StatusCode::TOO_MANY_REQUESTS, "too many wrong passwords, try again in 15 minutes".into())); + } if !argon(move || verify_password(&c.password, &hash)).await? { return Err(wrong()); } + s.failures.lock().unwrap_or_else(|e| e.into_inner()).remove(&id); Ok(User { id, username }) } diff --git a/crates/hub/src/tests.rs b/crates/hub/src/tests.rs index dbc3b4d..e9f523a 100644 --- a/crates/hub/src/tests.rs +++ b/crates/hub/src/tests.rs @@ -98,6 +98,30 @@ async fn publish_and_deploy_flow() { assert!(servers[0].online); } +#[tokio::test] +async fn wrong_passwords_lock_password_sign_in_for_a_while() { + let (_tmp, base) = start().await; + let anon = Hub::new(&base, None); + let good = Credentials { username: "doc".into(), password: "longpassword".into() }; + let auth = anon.register(&good).await.unwrap(); + let wrong = Credentials { password: "wrongpassword".into(), ..good.clone() }; + // Fired at once: the limit holds for parallel guesses too. + let guesses: Vec<_> = (0..20) + .map(|_| { + let (a, w) = (Hub::new(&base, None), wrong.clone()); + tokio::spawn(async move { a.login(&w).await.unwrap_err().to_string() }) + }) + .collect(); + let mut errors = vec![]; + for g in guesses { + errors.push(g.await.unwrap()); + } + assert_eq!(errors.iter().filter(|e| e.contains("too many")).count(), 10, "{errors:?}"); + assert!(anon.login(&good).await.unwrap_err().to_string().contains("too many")); + // Signed in clients are unaffected. + assert!(Hub::new(&base, Some(auth.token)).library().await.is_ok()); +} + #[tokio::test] async fn device_login() { let (_tmp, base) = start().await; diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 555f8f4..53af1f0 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -134,7 +134,7 @@ GET /api/objects/:hash -> raw object bytes (blobs, trees, commits) Authenticated: ``` -POST /api/auth/register|login { username, password } -> { token, user } +POST /api/auth/register|login { username, password } -> { token, user } (429 after 10 wrong passwords for an account within 15 minutes) POST /api/auth/device/start -> { device_code, user_code, expires_in } POST /api/auth/device/poll { device_code } -> { token, user } | 428 pending POST /api/auth/device/approve { user_code } From 218f048227fcd3d7c0bbb9ba440e34612187687d Mon Sep 17 00:00:00 2001 From: RealDoc06 <73218979+RealDoc06@users.noreply.github.com> Date: Thu, 19 Nov 2026 04:49:22 +0100 Subject: [PATCH 05/33] fix(core): write token files owner-only from the start settings.json (user token) and a server's .beacon/server.json (server token) were written with the default umask and only then chmodded to 0600, leaving a window where other local users could read the token. Servers rewrite server.json on every deploy. Both now use write_private, which creates the file 0600. --- crates/core/src/server/mod.rs | 10 ++-------- crates/core/src/settings.rs | 9 +-------- 2 files changed, 3 insertions(+), 16 deletions(-) diff --git a/crates/core/src/server/mod.rs b/crates/core/src/server/mod.rs index fe7df26..c37f6fe 100644 --- a/crates/core/src/server/mod.rs +++ b/crates/core/src/server/mod.rs @@ -56,15 +56,9 @@ impl ServerConfig { Ok(serde_json::from_slice(&bytes)?) } + /// Owner-only from the start: it holds the server's hub token. pub fn save(&self, dir: &Path) -> Result<()> { - let p = Self::path(dir); - write_atomic(&p, &serde_json::to_vec_pretty(self)?)?; - #[cfg(unix)] - { - use std::os::unix::fs::PermissionsExt; - fs::set_permissions(&p, fs::Permissions::from_mode(0o600))?; - } - Ok(()) + crate::store::write_private(&Self::path(dir), &serde_json::to_vec_pretty(self)?) } /// Full command line used to start Minecraft. diff --git a/crates/core/src/settings.rs b/crates/core/src/settings.rs index 95fbe6b..c43f67c 100644 --- a/crates/core/src/settings.rs +++ b/crates/core/src/settings.rs @@ -38,14 +38,7 @@ impl Settings { /// Saves with owner-only permissions since it holds the auth token. pub fn save(&self) -> Result<()> { - let path = Self::path(); - crate::store::write_atomic(&path, &serde_json::to_vec_pretty(self)?)?; - #[cfg(unix)] - { - use std::os::unix::fs::PermissionsExt; - std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600))?; - } - Ok(()) + crate::store::write_private(&Self::path(), &serde_json::to_vec_pretty(self)?) } pub fn hub_url(&self) -> String { From 30ddb47d7124b627627f4c66f8a22ca8f1a557c8 Mon Sep 17 00:00:00 2001 From: RealDoc06 <73218979+RealDoc06@users.noreply.github.com> Date: Thu, 19 Nov 2026 04:51:25 +0100 Subject: [PATCH 06/33] fix(deps): update zip to 9 zip 2.6 is affected by RUSTSEC-2026-0367, -0368, -0369, -0429 and -0545. The extract issues (symlinks pointing outside the destination, permissions applied through symlinks) reach BeaconSync through restoring a mod made world backup zip on a server and unpacking the built-in Prism and Java archives. Adapts to entry names now being fallible. --- Cargo.lock | 62 ++++++++++++++++++++++++--------------- crates/cli/Cargo.toml | 2 +- crates/cli/src/backups.rs | 5 +++- crates/core/Cargo.toml | 2 +- crates/core/src/import.rs | 14 +++++---- 5 files changed, 53 insertions(+), 32 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 9a18387..4adda8e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -133,15 +133,6 @@ dependencies = [ "object", ] -[[package]] -name = "arbitrary" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3bc62ac97cc33321f50863d514c3bc38a453947a8f9e781137e47c7401020aed" -dependencies = [ - "derive_arbitrary", -] - [[package]] name = "argon2" version = "0.5.3" @@ -924,6 +915,15 @@ dependencies = [ "windows-sys 0.59.0", ] +[[package]] +name = "constant_time_eq" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9eb6feb175df65d0a3ccd3e73484e940d0ac664e8034f0519fd49a93db3071d9" +dependencies = [ + "rustversion", +] + [[package]] name = "convert_case" version = "0.10.0" @@ -1217,17 +1217,6 @@ dependencies = [ "serde_core", ] -[[package]] -name = "derive_arbitrary" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b034bd7d5f032402a2479444dcc6f74e36a03f31854d41680fb240ef682a1ac" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.9", -] - [[package]] name = "derive_more" version = "2.1.1" @@ -5791,6 +5780,12 @@ version = "0.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" +[[package]] +name = "typed-path" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ce898823d8cd0f028662d2f349694b1af0a5cc9be83f1d213a00d3147445e1e" + [[package]] name = "typeid" version = "1.0.3" @@ -6849,6 +6844,20 @@ name = "zeroize" version = "1.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" +dependencies = [ + "zeroize_derive", +] + +[[package]] +name = "zeroize_derive" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] [[package]] name = "zerotrie" @@ -6885,16 +6894,21 @@ dependencies = [ [[package]] name = "zip" -version = "2.6.1" +version = "9.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1dcb24d0152526ae49b9b96c1dcf71850ca1e0b882e4e28ed898a93c41334744" +checksum = "2522d7da11cd3f2fe692a06a3bf9cecdbaa3720ede120d5ae9cffe42c56c6029" dependencies = [ - "arbitrary", + "constant_time_eq", "crc32fast", - "crossbeam-utils", "flate2", + "getrandom 0.4.3", "indexmap 2.14.2", + "libc", "memchr", + "nix 0.31.3", + "typed-path", + "windows-sys 0.61.2", + "zeroize", "zopfli", ] diff --git a/crates/cli/Cargo.toml b/crates/cli/Cargo.toml index 822de17..a24c06d 100644 --- a/crates/cli/Cargo.toml +++ b/crates/cli/Cargo.toml @@ -23,7 +23,7 @@ indicatif = "0.17" console = "0.15" tar = "0.4" flate2 = "1" -zip = { version = "2", default-features = false, features = ["deflate"] } +zip = { version = "9", default-features = false, features = ["deflate"] } walkdir = "2" libc = "0.2" ratatui = "0.30.2" diff --git a/crates/cli/src/backups.rs b/crates/cli/src/backups.rs index e6099d1..88aa414 100644 --- a/crates/cli/src/backups.rs +++ b/crates/cli/src/backups.rs @@ -277,7 +277,10 @@ pub fn restore(server: &Path, id: &str) -> Result<()> { fn archive_entries(file: &Path) -> Result> { if file.to_string_lossy().to_ascii_lowercase().ends_with(".zip") { let z = zip::ZipArchive::new(fs::File::open(file)?)?; - return Ok(z.file_names().map(|n| n.trim_start_matches("./").to_string()).collect()); + return Ok(z + .file_names() + .map(|n| n.map(|n| n.trim_start_matches("./").to_string())) + .collect::>()?); } let mut tar = tar::Archive::new(flate2::read::GzDecoder::new(fs::File::open(file)?)); let mut out = vec![]; diff --git a/crates/core/Cargo.toml b/crates/core/Cargo.toml index 4d6df6f..24b579b 100644 --- a/crates/core/Cargo.toml +++ b/crates/core/Cargo.toml @@ -18,7 +18,7 @@ futures.workspace = true ignore = "0.4" walkdir = "2" rayon = "1" -zip = { version = "2", default-features = false, features = ["deflate"] } +zip = { version = "9", default-features = false, features = ["deflate"] } dirs = "6" tar = "0.4" flate2 = "1" diff --git a/crates/core/src/import.rs b/crates/core/src/import.rs index 680d9b4..1ed9323 100644 --- a/crates/core/src/import.rs +++ b/crates/core/src/import.rs @@ -65,7 +65,7 @@ pub enum ImportKind { pub fn detect(path: &Path) -> Result { let mut zip = zip::ZipArchive::new(fs::File::open(path)?).context("not a zip file")?; - let names: Vec = zip.file_names().map(str::to_string).collect(); + let names: Vec = zip.file_names().map(|n| n.map(|n| n.into_owned())).collect::>()?; if names.iter().any(|n| n == "modrinth.index.json") { return Ok(ImportKind::Mrpack); } @@ -151,7 +151,7 @@ pub async fn mrpack_tree(path: &Path, store: &ObjectStore) -> Result<(MrIndex, T if !file.is_file() { continue; } - let Some(rel) = file.name().strip_prefix(prefix).and_then(safe_rel) else { continue }; + let Some(rel) = file.name()?.strip_prefix(prefix).and_then(safe_rel) else { continue }; let mut bytes = Vec::with_capacity(file.size() as usize); file.read_to_end(&mut bytes)?; let id = store.put(&bytes)?; @@ -335,7 +335,7 @@ pub async fn import_curseforge(file: &Path, root: &Path, cf: &CurseForge, author let overrides = format!("{}/", manifest.overrides.as_deref().unwrap_or("overrides")); for i in 0..zip.len() { let mut f = zip.by_index(i)?; - let Some(rel) = f.name().strip_prefix(&overrides).and_then(safe_rel) else { continue }; + let Some(rel) = f.name()?.strip_prefix(&overrides).and_then(safe_rel) else { continue }; if f.is_file() { let mut bytes = vec![]; f.read_to_end(&mut bytes)?; @@ -381,13 +381,17 @@ pub async fn import_curseforge(file: &Path, root: &Path, cf: &CurseForge, author /// Extracts a Prism/MultiMC instance export (.zip) and starts tracking it. pub async fn import_prism_zip(file: &Path, root: &Path, author: &str) -> Result { let mut zip = zip::ZipArchive::new(fs::File::open(file)?)?; - let cfg_name = zip.file_names().find(|n| n.ends_with("instance.cfg")).context("no instance.cfg")?.to_string(); + let cfg_name = zip + .file_names() + .find(|n| n.as_ref().is_ok_and(|n| n.ends_with("instance.cfg"))) + .context("no instance.cfg")?? + .into_owned(); let prefix = cfg_name.trim_end_matches("instance.cfg").to_string(); let stem = file.file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_else(|| "pack".into()); let dir = instance::unique_dir(root, &stem); for i in 0..zip.len() { let mut f = zip.by_index(i)?; - let Some(rel) = f.name().strip_prefix(&prefix).and_then(safe_rel) else { continue }; + let Some(rel) = f.name()?.strip_prefix(&prefix).and_then(safe_rel) else { continue }; if f.is_file() { let mut bytes = vec![]; f.read_to_end(&mut bytes)?; From c8ccb65d892f63a20f267b231080f708a877a0d2 Mon Sep 17 00:00:00 2001 From: RealDoc06 <73218979+RealDoc06@users.noreply.github.com> Date: Thu, 19 Nov 2026 04:52:36 +0100 Subject: [PATCH 07/33] fix(deps): update rusqlite to 0.43 The bundled SQLite in libsqlite3-sys 0.30 is affected by RUSTSEC-2026-0459 (CVE-2026-119375). The hub only opens its own database, so it isn't reachable today, but this clears the advisory. --- Cargo.lock | 55 +++++++++++++++++++++---------------------- crates/hub/Cargo.toml | 2 +- 2 files changed, 28 insertions(+), 29 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 4adda8e..a268962 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8,18 +8,6 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" -[[package]] -name = "ahash" -version = "0.8.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75" -dependencies = [ - "cfg-if", - "once_cell", - "version_check", - "zerocopy", -] - [[package]] name = "aho-corasick" version = "1.1.5" @@ -2074,15 +2062,6 @@ version = "0.12.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" -[[package]] -name = "hashbrown" -version = "0.14.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" -dependencies = [ - "ahash", -] - [[package]] name = "hashbrown" version = "0.17.1" @@ -2096,11 +2075,11 @@ dependencies = [ [[package]] name = "hashlink" -version = "0.9.1" +version = "0.12.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ba4ff7128dee98c7dc9794b6a411377e1404dba1c97deb8d1a55297bd25d8af" +checksum = "a596f1b20ed2cc5ecac41a164aaebc7258057060f06c0cf7a2ba3991ee7990fb" dependencies = [ - "hashbrown 0.14.5", + "hashbrown 0.17.1", ] [[package]] @@ -2768,9 +2747,9 @@ dependencies = [ [[package]] name = "libsqlite3-sys" -version = "0.30.1" +version = "0.40.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2e99fb7a497b1e3339bc746195567ed8d3e24945ecd636e3619d20b9de9e9149" +checksum = "b06e69070b7e12262b0cd90832f0a7396f142a2b330181255562decf9f0c6215" dependencies = [ "cc", "pkg-config", @@ -4247,11 +4226,20 @@ dependencies = [ "windows-sys 0.52.0", ] +[[package]] +name = "rsqlite-vfs" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "353b74f9810d5b085b6c42c9d86a5f0fdb795553235cdd48753b32e3809d18a7" +dependencies = [ + "thiserror 2.0.21", +] + [[package]] name = "rusqlite" -version = "0.32.1" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7753b721174eb8ff87a9a0e799e2d7bc3749323e773db92e0984debb00019d6e" +checksum = "f172c4812a19b26d1c23cdb0070e69db335503dfa378b910eb857386e5b8beba" dependencies = [ "bitflags 2.13.2", "fallible-iterator", @@ -4259,6 +4247,7 @@ dependencies = [ "hashlink", "libsqlite3-sys", "smallvec", + "sqlite-wasm-rs", ] [[package]] @@ -4769,6 +4758,16 @@ dependencies = [ "system-deps", ] +[[package]] +name = "sqlite-wasm-rs" +version = "0.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cd504cecbfe7eef649988840f9a6cb768d11085efec138f8e99f160632d867" +dependencies = [ + "cc", + "rsqlite-vfs", +] + [[package]] name = "stable_deref_trait" version = "1.2.1" diff --git a/crates/hub/Cargo.toml b/crates/hub/Cargo.toml index 9c47572..5531303 100644 --- a/crates/hub/Cargo.toml +++ b/crates/hub/Cargo.toml @@ -17,7 +17,7 @@ rand.workspace = true tracing.workspace = true tracing-subscriber.workspace = true axum = "0.8" -rusqlite = { version = "0.32", features = ["bundled"] } +rusqlite = { version = "0.43", features = ["bundled"] } argon2 = "0.5" clap = { version = "4", features = ["derive", "env"] } tower-http = { version = "0.6", features = ["trace"] } From 6f60c96648f46eed377fe3353ad0ec3f1312e97c Mon Sep 17 00:00:00 2001 From: RealDoc06 <73218979+RealDoc06@users.noreply.github.com> Date: Thu, 19 Nov 2026 04:59:52 +0100 Subject: [PATCH 08/33] fix(cli): Windows backups leave out other backups and the retention rule skip() matched '/' prefixes against Windows '\' paths, so backups on Windows included .beacon/backups and the retention file, and a restore brought back an older retention rule. --- crates/cli/src/backups.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/cli/src/backups.rs b/crates/cli/src/backups.rs index 88aa414..a9860b3 100644 --- a/crates/cli/src/backups.rs +++ b/crates/cli/src/backups.rs @@ -149,7 +149,8 @@ fn find(server: &Path, id: &str) -> Result { /// files being written. /// `world` is the world folder, always kept even if its name contains "backup". fn skip(server: &Path, world: &str, rel: &Path) -> bool { - let s = rel.to_string_lossy(); + // Forward slashes on every OS, so the prefixes below also match Windows paths. + let s = rel.to_string_lossy().replace('\\', "/"); let top = rel.components().next().map(|c| c.as_os_str().to_string_lossy().into_owned()).unwrap_or_default(); s.starts_with(".beacon/backup") || s.starts_with(".beacon/objects") From a781ba777478c4ac1ccc177a12ae46fae738899b Mon Sep 17 00:00:00 2001 From: RealDoc06 <73218979+RealDoc06@users.noreply.github.com> Date: Thu, 19 Nov 2026 05:08:11 +0100 Subject: [PATCH 09/33] fix(hub): bound Argon2 work and throttle unknown usernames too At most one hash per CPU runs at once, registration rejects taken names before hashing, unknown usernames are counted and checked against a dummy hash, and the /device page returns the real error status. --- crates/hub/src/pages.rs | 11 ++++++-- crates/hub/src/routes.rs | 61 ++++++++++++++++++++++++++++------------ crates/hub/src/tests.rs | 6 ++++ docs/ARCHITECTURE.md | 2 +- 4 files changed, 58 insertions(+), 22 deletions(-) diff --git a/crates/hub/src/pages.rs b/crates/hub/src/pages.rs index 4e0c910..f09b322 100644 --- a/crates/hub/src/pages.rs +++ b/crates/hub/src/pages.rs @@ -5,6 +5,7 @@ use crate::routes::{AppState, approve_device, check_credentials, public_info}; use axum::{ Form, extract::{Path, State}, + http::StatusCode, response::Html, }; use beacon_core::api::Credentials; @@ -79,12 +80,16 @@ pub struct DeviceForm { password: String, } -pub async fn device_submit(State(s): State, Form(f): Form) -> Html { +/// Errors keep their API status (401, 429...) so scripts and proxies see the failure. +pub async fn device_submit(State(s): State, Form(f): Form) -> (StatusCode, Html) { let result = check_credentials(&s, Credentials { username: f.username, password: f.password }) .await .and_then(|u| approve_device(&s, &u.id, &f.user_code)); match result { - Ok(()) => page("Approved", "

Approved

You can close this page and go back to the terminal.

"), - Err(e) => device_html(&format!("

{}

", esc(&e.1))), + Ok(()) => ( + StatusCode::OK, + page("Approved", "

Approved

You can close this page and go back to the terminal.

"), + ), + Err(e) => (e.0, device_html(&format!("

{}

", esc(&e.1)))), } } diff --git a/crates/hub/src/routes.rs b/crates/hub/src/routes.rs index b008f97..6d976b4 100644 --- a/crates/hub/src/routes.rs +++ b/crates/hub/src/routes.rs @@ -21,10 +21,10 @@ use serde::Deserialize; use serde_json::{Value, json}; use std::{ collections::HashMap, - sync::{Arc, Mutex, MutexGuard}, + sync::{Arc, LazyLock, Mutex, MutexGuard}, time::Duration, }; -use tokio::sync::Notify; +use tokio::sync::{Notify, Semaphore}; #[derive(Clone)] pub struct AppState(Arc); @@ -37,12 +37,14 @@ pub struct Inner { waiters: Mutex>>, /// Live console and backups per server, kept in memory only. consoles: Mutex>, - /// Failed sign ins per user id: (count, start of the window). + /// Failed sign ins per username, existing or not: (count, start of the window). failures: Mutex>, } -/// Wrong passwords allowed per account within [`FAILURE_WINDOW`] seconds before sign ins with a -/// password are refused for the rest of it. Existing tokens keep working. +/// Wrong passwords allowed per username within [`FAILURE_WINDOW`] seconds before sign ins with a +/// password are refused for the rest of it. Existing tokens keep working. The limit is per +/// account, not per client, so someone who knows a username can keep its password sign in locked; +/// the hub sits behind a proxy and has no client address it can trust. const MAX_FAILURES: u32 = 10; const FAILURE_WINDOW: i64 = 15 * 60; @@ -174,11 +176,17 @@ async fn register(State(s): State, Json(c): Json) -> Resu if c.password.len() < 8 { return Err(Error::bad("password must be at least 8 characters")); } + let taken = |db: &Connection| -> Result { + Ok(db.query_row("select 1 from users where username = ?1", params![username], |_| Ok(())).optional()?.is_some()) + }; + // Checked before hashing too, so repeat requests for a taken name cost no Argon2 work. + if taken(&s.db())? { + return Err(Error::conflict("that username is taken")); + } let pw = argon(move || hash_password(&c.password)).await??; let db = s.db(); let id = new_id(); - let taken = db.query_row("select 1 from users where username = ?1", params![username], |_| Ok(())).optional()?.is_some(); - if taken { + if taken(&db)? { return Err(Error::conflict("that username is taken")); } db.execute("insert into users (id, username, pw_hash, created) values (?1, ?2, ?3, ?4)", params![id, username, pw, now()])?; @@ -186,34 +194,51 @@ async fn register(State(s): State, Json(c): Json) -> Resu Ok(Json(AuthResponse { token, user: User { id, username: username.into() } })) } -/// Runs Argon2 on the blocking pool: it takes tens of milliseconds of CPU, which would otherwise -/// stall an async worker (and, under the DB lock, every request). +/// One Argon2 run per CPU at a time: each takes tens of milliseconds and ~19 MiB, so a flood of +/// sign ins or registrations queues here instead of exhausting the host. +static ARGON: LazyLock> = + LazyLock::new(|| Arc::new(Semaphore::new(std::thread::available_parallelism().map_or(2, |n| n.get())))); + +/// Runs Argon2 on the blocking pool, so it never stalls an async worker (and, under the DB lock, +/// every request). The permit lives as long as the work, even if the request is dropped. async fn argon(f: impl FnOnce() -> T + Send + 'static) -> Result { - tokio::task::spawn_blocking(f).await.map_err(|e| anyhow::Error::from(e).into()) + let permit = ARGON.clone().acquire_owned().await.map_err(anyhow::Error::from)?; + tokio::task::spawn_blocking(move || { + let out = f(); + drop(permit); + out + }) + .await + .map_err(|e| anyhow::Error::from(e).into()) } +/// Checked against when the username doesn't exist, so unknown names cost the same time as real +/// ones and don't reveal which accounts exist. +static DUMMY_HASH: LazyLock = LazyLock::new(|| hash_password("not a real password").unwrap_or_default()); + /// Checks a username/password pair (also used by the /device web page). pub async fn check_credentials(s: &AppState, c: Credentials) -> Result { + let name = c.username.trim().to_string(); let row: Option<(String, String, String)> = s .db() - .query_row("select id, username, pw_hash from users where username = ?1", params![c.username.trim()], |r| { + .query_row("select id, username, pw_hash from users where username = ?1", params![name], |r| { Ok((r.get(0)?, r.get(1)?, r.get(2)?)) }) .optional()?; - let wrong = || Error(StatusCode::UNAUTHORIZED, "wrong username or password".into()); - let (id, username, hash) = row.ok_or_else(wrong)?; // Counted before checking, so parallel guesses can't all slip in under the limit. - let allowed = s.failures(&id, |(count, _)| { + let allowed = s.failures(&name, |(count, _)| { *count += 1; *count <= MAX_FAILURES }); if !allowed { return Err(Error(StatusCode::TOO_MANY_REQUESTS, "too many wrong passwords, try again in 15 minutes".into())); } - if !argon(move || verify_password(&c.password, &hash)).await? { - return Err(wrong()); - } - s.failures.lock().unwrap_or_else(|e| e.into_inner()).remove(&id); + let hash = row.as_ref().map(|(_, _, h)| h.clone()); + let ok = argon(move || verify_password(&c.password, hash.as_deref().unwrap_or(&DUMMY_HASH))).await?; + let Some((id, username, _)) = row.filter(|_| ok) else { + return Err(Error(StatusCode::UNAUTHORIZED, "wrong username or password".into())); + }; + s.failures.lock().unwrap_or_else(|e| e.into_inner()).remove(&name); Ok(User { id, username }) } diff --git a/crates/hub/src/tests.rs b/crates/hub/src/tests.rs index e9f523a..d7d3869 100644 --- a/crates/hub/src/tests.rs +++ b/crates/hub/src/tests.rs @@ -120,6 +120,12 @@ async fn wrong_passwords_lock_password_sign_in_for_a_while() { assert!(anon.login(&good).await.unwrap_err().to_string().contains("too many")); // Signed in clients are unaffected. assert!(Hub::new(&base, Some(auth.token)).library().await.is_ok()); + // Unknown usernames are limited the same way, so guessing names gets no free attempts. + let ghost = Credentials { username: "ghost".into(), password: "whatever1".into() }; + for _ in 0..10 { + assert!(!anon.login(&ghost).await.unwrap_err().to_string().contains("too many")); + } + assert!(anon.login(&ghost).await.unwrap_err().to_string().contains("too many")); } #[tokio::test] diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 53af1f0..74e5349 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -134,7 +134,7 @@ GET /api/objects/:hash -> raw object bytes (blobs, trees, commits) Authenticated: ``` -POST /api/auth/register|login { username, password } -> { token, user } (429 after 10 wrong passwords for an account within 15 minutes) +POST /api/auth/register|login { username, password } -> { token, user } (429 after 10 wrong passwords for a username, existing or not, within 15 minutes; per account, so it can keep a known username's password sign in locked, but tokens keep working) POST /api/auth/device/start -> { device_code, user_code, expires_in } POST /api/auth/device/poll { device_code } -> { token, user } | 428 pending POST /api/auth/device/approve { user_code } From 2c941c07ba95ec946f931866d03f8824d079aa3b Mon Sep 17 00:00:00 2001 From: RealDoc06 <73218979+RealDoc06@users.noreply.github.com> Date: Thu, 19 Nov 2026 05:08:11 +0100 Subject: [PATCH 10/33] fix(cli): restores only clear a folder directly inside the server A mod archive or level-name pointing at .. or a nested path is refused before anything is deleted. Backup archives, which hold the server token, are created owner-only on Unix. --- crates/cli/src/backups.rs | 46 ++++++++++++++++++++++++++++++++++----- 1 file changed, 40 insertions(+), 6 deletions(-) diff --git a/crates/cli/src/backups.rs b/crates/cli/src/backups.rs index a9860b3..7044cc0 100644 --- a/crates/cli/src/backups.rs +++ b/crates/cli/src/backups.rs @@ -10,7 +10,7 @@ use beacon_core::{ }; use std::{ fs, - path::{Path, PathBuf}, + path::{Component, Path, PathBuf}, time::UNIX_EPOCH, }; @@ -173,7 +173,15 @@ pub fn create(server: &Path, note: &str) -> Result { let name = format!("{}-{}.tar.gz", beacon_core::now(), slug.trim_matches('-')); let tmp = dir.join(format!("{name}.part")); { - let enc = flate2::write::GzEncoder::new(fs::File::create(&tmp)?, flate2::Compression::fast()); + // Owner-only on Unix: the archive holds `.beacon/server.json` and its hub token. + let mut options = fs::OpenOptions::new(); + options.write(true).create(true).truncate(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.mode(0o600); + } + let enc = flate2::write::GzEncoder::new(options.open(&tmp)?, flate2::Compression::fast()); let mut tar = tar::Builder::new(enc); tar.follow_symlinks(false); let world = level_name(server); @@ -235,6 +243,22 @@ fn level_name(server: &Path) -> String { .unwrap_or_else(|| "world".into()) } +/// Whether `name` is one plain folder name, so a restore only ever clears a folder directly +/// inside the server (not `..`, `.`, an absolute path or a nested one). +fn one_folder(name: &str) -> bool { + let mut parts = Path::new(name).components(); + matches!((parts.next(), parts.next()), (Some(Component::Normal(_)), None)) +} + +/// The world folder a restore clears, refused unless it sits directly inside the server. +fn world_dir(server: &Path) -> Result { + let name = level_name(server); + if !one_folder(&name) { + bail!("level-name {name:?} in server.properties isn't a plain folder name"); + } + Ok(server.join(name)) +} + /// Restores a backup. Minecraft must be stopped. Whole server backups replace the pack files /// and worlds; mod backups replace only the world they contain. pub fn restore(server: &Path, id: &str) -> Result<()> { @@ -247,7 +271,7 @@ pub fn restore(server: &Path, id: &str) -> Result<()> { } } // Chunks generated after the backup would otherwise survive the restore. - fs::remove_dir_all(server.join(level_name(server))).ok(); + fs::remove_dir_all(world_dir(server)?).ok(); tar::Archive::new(flate2::read::GzDecoder::new(fs::File::open(file)?)).unpack(server)?; return Ok(()); } @@ -258,9 +282,9 @@ pub fn restore(server: &Path, id: &str) -> Result<()> { let entries = archive_entries(&file)?; // Either the world's files at the root, or one folder holding them. let (dest, clear) = if entries.iter().any(|e| e == "level.dat") { - let world = server.join(level_name(server)); + let world = world_dir(server)?; (world.clone(), world) - } else if let Some(top) = entries.iter().find_map(|e| e.strip_suffix("/level.dat").filter(|t| !t.contains('/'))) { + } else if let Some(top) = entries.iter().find_map(|e| e.strip_suffix("/level.dat").filter(|t| one_folder(t))) { (server.to_path_buf(), server.join(top)) } else { bail!("{} doesn't look like a world backup (no level.dat)", b.note); @@ -340,10 +364,20 @@ mod tests { ); // Our own backups leave mod backups out. let own = create(&d, "manual").unwrap(); - assert!(!archive_entries(&d.join(own.id)).unwrap().iter().any(|e| e.starts_with("backups/"))); + assert!(!archive_entries(&d.join(&own.id)).unwrap().iter().any(|e| e.starts_with("backups/"))); restore(&d, &b.id).unwrap(); assert_eq!(fs::read_to_string(d.join("world/level.dat")).unwrap(), "from mod"); assert!(restore(&d, "../etc/passwd").is_err()); + // An archive naming `..` as its world is refused before anything is cleared. + let mut z = zip::ZipWriter::new(fs::File::create(d.join("backups/escape.zip")).unwrap()); + z.start_file("../level.dat", zip::write::SimpleFileOptions::default()).unwrap(); + z.finish().unwrap(); + assert!(restore(&d, "backups/escape.zip").is_err()); + assert!(d.join("world/level.dat").exists()); + // So is a server.properties pointing the world outside the server. + fs::write(d.join("server.properties"), "level-name=../elsewhere\n").unwrap(); + assert!(restore(&d, &own.id).is_err()); + fs::write(d.join("server.properties"), "level-name=world\n").unwrap(); // Partial archives from incremental backups are refused rather than half restored. fs::copy(d.join("backups/2026-11-05.zip"), d.join("backups/incremental.zip")).unwrap(); assert!(restore(&d, "backups/incremental.zip").is_err()); From d1e5b34189d410091ef441523656b9c17c921843 Mon Sep 17 00:00:00 2001 From: RealDoc06 <73218979+RealDoc06@users.noreply.github.com> Date: Thu, 19 Nov 2026 05:08:11 +0100 Subject: [PATCH 11/33] fix(core): atomic writes use a unique, exclusively created temp file --- crates/core/src/store.rs | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/crates/core/src/store.rs b/crates/core/src/store.rs index 36f0876..f58f36e 100644 --- a/crates/core/src/store.rs +++ b/crates/core/src/store.rs @@ -76,20 +76,28 @@ pub fn write_atomic(path: &Path, bytes: &[u8]) -> Result<()> { write_through_temp(path, bytes, false) } -/// [`write_atomic`] for files holding secrets: owner-only permissions from the start. +/// [`write_atomic`] for files holding secrets: owner-only permissions from the start on Unix. +/// On Windows the file gets its folder's permissions. pub fn write_private(path: &Path, bytes: &[u8]) -> Result<()> { write_through_temp(path, bytes, true) } fn write_through_temp(path: &Path, bytes: &[u8], private: bool) -> Result<()> { + static SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); let dir = path.parent().context("path has no parent")?; fs::create_dir_all(dir)?; - let tmp = dir.join(format!(".{}.tmp{}", path.file_name().and_then(|n| n.to_str()).unwrap_or("obj"), std::process::id())); + let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.subsec_nanos()); + let tmp = dir.join(format!( + ".{}.{}-{}-{nanos}.tmp", + path.file_name().and_then(|n| n.to_str()).unwrap_or("obj"), + std::process::id(), + SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed), + )); { - // The mode only applies to new files, so a leftover temp file must go first. - fs::remove_file(&tmp).ok(); + // A fresh name created exclusively: concurrent saves never share a temp file, and nothing + // planted at that path (a symlink, a file with looser permissions) is ever written through. let mut options = fs::OpenOptions::new(); - options.write(true).create(true).truncate(true); + options.write(true).create_new(true); #[cfg(unix)] if private { use std::os::unix::fs::OpenOptionsExt; From e7c0843d9198281e8b32be8a6f71cd9af2931342 Mon Sep 17 00:00:00 2001 From: RealDoc06 <73218979+RealDoc06@users.noreply.github.com> Date: Thu, 19 Nov 2026 05:08:11 +0100 Subject: [PATCH 12/33] fix(core): release versions must start with a digit and have no empty parts --- crates/core/src/release.rs | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/crates/core/src/release.rs b/crates/core/src/release.rs index 3d04377..447e7d2 100644 --- a/crates/core/src/release.rs +++ b/crates/core/src/release.rs @@ -145,9 +145,14 @@ pub async fn download(asset: &Asset, dest: &Path, on: impl Fn(u64)) -> Result<() Ok(()) } -/// Version characters only (`0-9a-zA-Z.-+`), so it is safe inside a URL path. +/// Version characters only (`0-9a-zA-Z.-+`), starting with a digit and with no empty dot parts, so +/// it is safe inside a URL path (`..` and `.` can't appear as segments). fn is_version(v: &str) -> bool { - (1..=64).contains(&v.len()) && v.bytes().all(|b| b.is_ascii_alphanumeric() || b"-.+".contains(&b)) + let core = v.strip_prefix('v').unwrap_or(v); + (1..=64).contains(&v.len()) + && core.starts_with(|c: char| c.is_ascii_digit()) + && !core.contains("..") + && core.bytes().all(|b| b.is_ascii_alphanumeric() || b"-.+".contains(&b)) } /// Semver order for `MAJOR.MINOR.PATCH[-PRE]`: a prerelease sorts before its release and @@ -189,7 +194,9 @@ mod tests { #[test] fn only_version_strings_reach_release_urls() { assert!(is_version("0.1.0-alpha.14") && is_version("v1.2.3+build.5")); - for bad in ["", "9.9.9/../../../other/repo", "1.0%2f..", "1.0?x", "1.0#x", "1.0\\.."] { + for bad in + ["", "v", ".", "..", "v..", "1..2", "x1.0", "9.9.9/../../../other/repo", "1.0%2f..", "1.0?x", "1.0#x", "1.0\\.."] + { assert!(!is_version(bad), "{bad}"); } } From f66fde0b97b7b9f4e2308ad96145d74f30ce32b0 Mon Sep 17 00:00:00 2001 From: RealDoc06 <73218979+RealDoc06@users.noreply.github.com> Date: Thu, 19 Nov 2026 05:15:24 +0100 Subject: [PATCH 13/33] fix(hub): throttle case-insensitively and bound waiting sign ins Usernames match with collate nocase, so the failure key is lowercased. Invalid names are rejected before touching the throttle, expired entries are swept at most once a minute, and at most 256 requests wait for Argon2 before the hub answers 503. --- crates/hub/src/routes.rs | 54 ++++++++++++++++++++++++++++++++++------ crates/hub/src/tests.rs | 3 +++ 2 files changed, 49 insertions(+), 8 deletions(-) diff --git a/crates/hub/src/routes.rs b/crates/hub/src/routes.rs index 6d976b4..3c4b944 100644 --- a/crates/hub/src/routes.rs +++ b/crates/hub/src/routes.rs @@ -21,7 +21,10 @@ use serde::Deserialize; use serde_json::{Value, json}; use std::{ collections::HashMap, - sync::{Arc, LazyLock, Mutex, MutexGuard}, + sync::{ + Arc, LazyLock, Mutex, MutexGuard, + atomic::{AtomicI64, AtomicUsize, Ordering}, + }, time::Duration, }; use tokio::sync::{Notify, Semaphore}; @@ -37,8 +40,10 @@ pub struct Inner { waiters: Mutex>>, /// Live console and backups per server, kept in memory only. consoles: Mutex>, - /// Failed sign ins per username, existing or not: (count, start of the window). + /// Failed sign ins per lowercased username, existing or not: (count, start of the window). failures: Mutex>, + /// When `failures` last dropped expired entries. + failures_swept: AtomicI64, } /// Wrong passwords allowed per username within [`FAILURE_WINDOW`] seconds before sign ins with a @@ -86,6 +91,7 @@ impl AppState { waiters: Mutex::default(), consoles: Mutex::default(), failures: Mutex::default(), + failures_swept: AtomicI64::default(), }))) } @@ -93,12 +99,21 @@ impl AppState { self.0.db.lock().unwrap_or_else(|e| e.into_inner()) } - /// Runs `f` on a user's failed sign in count, restarting it once its window is over. + /// Runs `f` on a username's failed sign in count, restarting it once its window is over. + /// Expired entries are swept at most once a minute, not on every sign in. fn failures(&self, user: &str, f: impl FnOnce(&mut (u32, i64)) -> T) -> T { let mut all = self.failures.lock().unwrap_or_else(|e| e.into_inner()); let now = now(); - all.retain(|_, (_, since)| now - *since < FAILURE_WINDOW); - f(all.entry(user.to_string()).or_insert((0, now))) + // Read and written only under the `failures` lock. + if now - self.failures_swept.load(Ordering::Relaxed) >= 60 { + all.retain(|_, (_, since)| now - *since < FAILURE_WINDOW); + self.failures_swept.store(now, Ordering::Relaxed); + } + let entry = all.entry(user.to_string()).or_insert((0, now)); + if now - entry.1 >= FAILURE_WINDOW { + *entry = (0, now); + } + f(entry) } fn waiter(&self, server: &str) -> Arc { @@ -199,10 +214,26 @@ async fn register(State(s): State, Json(c): Json) -> Resu static ARGON: LazyLock> = LazyLock::new(|| Arc::new(Semaphore::new(std::thread::available_parallelism().map_or(2, |n| n.get())))); +/// Sign ins and registrations allowed to wait for [`ARGON`] at once; past that the hub answers +/// 503 right away instead of holding more requests (and their bodies) in memory. +const MAX_ARGON_WAITING: usize = 256; +static ARGON_WAITING: AtomicUsize = AtomicUsize::new(0); + /// Runs Argon2 on the blocking pool, so it never stalls an async worker (and, under the DB lock, /// every request). The permit lives as long as the work, even if the request is dropped. async fn argon(f: impl FnOnce() -> T + Send + 'static) -> Result { + struct Waiting; + impl Drop for Waiting { + fn drop(&mut self) { + ARGON_WAITING.fetch_sub(1, Ordering::Relaxed); + } + } + let waiting = Waiting; + if ARGON_WAITING.fetch_add(1, Ordering::Relaxed) >= MAX_ARGON_WAITING { + return Err(Error(StatusCode::SERVICE_UNAVAILABLE, "the hub is busy, try again shortly".into())); + } let permit = ARGON.clone().acquire_owned().await.map_err(anyhow::Error::from)?; + drop(waiting); tokio::task::spawn_blocking(move || { let out = f(); drop(permit); @@ -218,7 +249,14 @@ static DUMMY_HASH: LazyLock = LazyLock::new(|| hash_password("not a real /// Checks a username/password pair (also used by the /device web page). pub async fn check_credentials(s: &AppState, c: Credentials) -> Result { + let wrong = || Error(StatusCode::UNAUTHORIZED, "wrong username or password".into()); let name = c.username.trim().to_string(); + // No account can have an invalid name, so this reveals nothing and keeps junk out of `failures`. + if !valid_username(&name) { + return Err(wrong()); + } + // Usernames match case-insensitively (`collate nocase`), so the limit must too. + let key = name.to_ascii_lowercase(); let row: Option<(String, String, String)> = s .db() .query_row("select id, username, pw_hash from users where username = ?1", params![name], |r| { @@ -226,7 +264,7 @@ pub async fn check_credentials(s: &AppState, c: Credentials) -> Result { }) .optional()?; // Counted before checking, so parallel guesses can't all slip in under the limit. - let allowed = s.failures(&name, |(count, _)| { + let allowed = s.failures(&key, |(count, _)| { *count += 1; *count <= MAX_FAILURES }); @@ -236,9 +274,9 @@ pub async fn check_credentials(s: &AppState, c: Credentials) -> Result { let hash = row.as_ref().map(|(_, _, h)| h.clone()); let ok = argon(move || verify_password(&c.password, hash.as_deref().unwrap_or(&DUMMY_HASH))).await?; let Some((id, username, _)) = row.filter(|_| ok) else { - return Err(Error(StatusCode::UNAUTHORIZED, "wrong username or password".into())); + return Err(wrong()); }; - s.failures.lock().unwrap_or_else(|e| e.into_inner()).remove(&name); + s.failures.lock().unwrap_or_else(|e| e.into_inner()).remove(&key); Ok(User { id, username }) } diff --git a/crates/hub/src/tests.rs b/crates/hub/src/tests.rs index d7d3869..aeb0e82 100644 --- a/crates/hub/src/tests.rs +++ b/crates/hub/src/tests.rs @@ -120,6 +120,9 @@ async fn wrong_passwords_lock_password_sign_in_for_a_while() { assert!(anon.login(&good).await.unwrap_err().to_string().contains("too many")); // Signed in clients are unaffected. assert!(Hub::new(&base, Some(auth.token)).library().await.is_ok()); + // Other casings of the name are the same account and share the limit. + let shouted = Credentials { username: "DOC".into(), ..wrong.clone() }; + assert!(anon.login(&shouted).await.unwrap_err().to_string().contains("too many")); // Unknown usernames are limited the same way, so guessing names gets no free attempts. let ghost = Credentials { username: "ghost".into(), password: "whatever1".into() }; for _ in 0..10 { From 03fbbc63b1aa7ed6d654fff1116af924e7b1c8b3 Mon Sep 17 00:00:00 2001 From: RealDoc06 <73218979+RealDoc06@users.noreply.github.com> Date: Thu, 19 Nov 2026 05:15:25 +0100 Subject: [PATCH 14/33] fix(cli): validate the world before a full restore deletes anything Also joins the validated folder name (a trailing / can't follow a symlinked world) and creates the backup .part exclusively so its 0600 mode always applies. --- crates/cli/src/backups.rs | 39 ++++++++++++++++++++++++++------------- 1 file changed, 26 insertions(+), 13 deletions(-) diff --git a/crates/cli/src/backups.rs b/crates/cli/src/backups.rs index 7044cc0..d73074b 100644 --- a/crates/cli/src/backups.rs +++ b/crates/cli/src/backups.rs @@ -173,9 +173,11 @@ pub fn create(server: &Path, note: &str) -> Result { let name = format!("{}-{}.tar.gz", beacon_core::now(), slug.trim_matches('-')); let tmp = dir.join(format!("{name}.part")); { - // Owner-only on Unix: the archive holds `.beacon/server.json` and its hub token. + // Owner-only on Unix: the archive holds `.beacon/server.json` and its hub token. Created + // exclusively, so a leftover `.part` with looser permissions is never reused. + fs::remove_file(&tmp).ok(); let mut options = fs::OpenOptions::new(); - options.write(true).create(true).truncate(true); + options.write(true).create_new(true); #[cfg(unix)] { use std::os::unix::fs::OpenOptionsExt; @@ -243,20 +245,23 @@ fn level_name(server: &Path) -> String { .unwrap_or_else(|| "world".into()) } -/// Whether `name` is one plain folder name, so a restore only ever clears a folder directly -/// inside the server (not `..`, `.`, an absolute path or a nested one). -fn one_folder(name: &str) -> bool { +/// `name` as one plain folder name, so a restore only ever clears a folder directly inside the +/// server (not `..`, `.`, an absolute path or a nested one). Callers join the returned part, not +/// `name`, so a trailing `/` can't make deletion follow a symlinked folder. +fn one_folder(name: &str) -> Option<&std::ffi::OsStr> { let mut parts = Path::new(name).components(); - matches!((parts.next(), parts.next()), (Some(Component::Normal(_)), None)) + match (parts.next(), parts.next()) { + (Some(Component::Normal(part)), None) => Some(part), + _ => None, + } } /// The world folder a restore clears, refused unless it sits directly inside the server. fn world_dir(server: &Path) -> Result { let name = level_name(server); - if !one_folder(&name) { - bail!("level-name {name:?} in server.properties isn't a plain folder name"); - } - Ok(server.join(name)) + let part = + one_folder(&name).with_context(|| format!("level-name {name:?} in server.properties isn't a plain folder name"))?; + Ok(server.join(part)) } /// Restores a backup. Minecraft must be stopped. Whole server backups replace the pack files @@ -265,13 +270,15 @@ pub fn restore(server: &Path, id: &str) -> Result<()> { let b = find(server, id)?; let file = server.join(&b.id); if b.full { + // Checked first: a refused restore must leave the server as it was. + let world = world_dir(server)?; if let Some(tree) = srv::applied_tree(server) { for p in tree.files.keys() { fs::remove_file(server.join(p)).ok(); } } // Chunks generated after the backup would otherwise survive the restore. - fs::remove_dir_all(world_dir(server)?).ok(); + fs::remove_dir_all(world).ok(); tar::Archive::new(flate2::read::GzDecoder::new(fs::File::open(file)?)).unpack(server)?; return Ok(()); } @@ -284,7 +291,7 @@ pub fn restore(server: &Path, id: &str) -> Result<()> { let (dest, clear) = if entries.iter().any(|e| e == "level.dat") { let world = world_dir(server)?; (world.clone(), world) - } else if let Some(top) = entries.iter().find_map(|e| e.strip_suffix("/level.dat").filter(|t| one_folder(t))) { + } else if let Some(top) = entries.iter().find_map(|e| e.strip_suffix("/level.dat").and_then(one_folder)) { (server.to_path_buf(), server.join(top)) } else { bail!("{} doesn't look like a world backup (no level.dat)", b.note); @@ -374,9 +381,15 @@ mod tests { z.finish().unwrap(); assert!(restore(&d, "backups/escape.zip").is_err()); assert!(d.join("world/level.dat").exists()); - // So is a server.properties pointing the world outside the server. + // So is a server.properties pointing the world outside the server, and pack files survive. + let mut tree = beacon_core::model::Tree::default(); + tree.files.insert("mods/pack.jar".into(), serde_json::from_value(serde_json::json!({ "hash": "x", "size": 0 })).unwrap()); + fs::write(d.join(".beacon/server-tree.json"), serde_json::to_vec(&tree).unwrap()).unwrap(); + fs::write(d.join("mods/pack.jar"), "").unwrap(); fs::write(d.join("server.properties"), "level-name=../elsewhere\n").unwrap(); assert!(restore(&d, &own.id).is_err()); + assert!(d.join("world/level.dat").exists() && d.join("mods/pack.jar").exists(), "a refused restore deletes nothing"); + assert_eq!(one_folder("world/"), Some(std::ffi::OsStr::new("world"))); fs::write(d.join("server.properties"), "level-name=world\n").unwrap(); // Partial archives from incremental backups are refused rather than half restored. fs::copy(d.join("backups/2026-11-05.zip"), d.join("backups/incremental.zip")).unwrap(); From d0d6fc4d266a08d546b5a5ff122494fa667da8e1 Mon Sep 17 00:00:00 2001 From: RealDoc06 <73218979+RealDoc06@users.noreply.github.com> Date: Thu, 19 Nov 2026 05:15:25 +0100 Subject: [PATCH 15/33] fix(core): remove temp files after failed writes and reject trailing dots in versions --- crates/core/src/release.rs | 19 ++++++++++++++++--- crates/core/src/store.rs | 14 ++++++++++---- 2 files changed, 26 insertions(+), 7 deletions(-) diff --git a/crates/core/src/release.rs b/crates/core/src/release.rs index 447e7d2..8b6a753 100644 --- a/crates/core/src/release.rs +++ b/crates/core/src/release.rs @@ -152,6 +152,7 @@ fn is_version(v: &str) -> bool { (1..=64).contains(&v.len()) && core.starts_with(|c: char| c.is_ascii_digit()) && !core.contains("..") + && !core.ends_with('.') && core.bytes().all(|b| b.is_ascii_alphanumeric() || b"-.+".contains(&b)) } @@ -194,9 +195,21 @@ mod tests { #[test] fn only_version_strings_reach_release_urls() { assert!(is_version("0.1.0-alpha.14") && is_version("v1.2.3+build.5")); - for bad in - ["", "v", ".", "..", "v..", "1..2", "x1.0", "9.9.9/../../../other/repo", "1.0%2f..", "1.0?x", "1.0#x", "1.0\\.."] - { + for bad in [ + "", + "v", + ".", + "..", + "v..", + "1..2", + "1.", + "x1.0", + "9.9.9/../../../other/repo", + "1.0%2f..", + "1.0?x", + "1.0#x", + "1.0\\..", + ] { assert!(!is_version(bad), "{bad}"); } } diff --git a/crates/core/src/store.rs b/crates/core/src/store.rs index f58f36e..75280a1 100644 --- a/crates/core/src/store.rs +++ b/crates/core/src/store.rs @@ -105,10 +105,16 @@ fn write_through_temp(path: &Path, bytes: &[u8], private: bool) -> Result<()> { } #[cfg(not(unix))] let _ = private; - let mut f = options.open(&tmp)?; - f.write_all(bytes)?; - f.sync_all().ok(); + let written = options.open(&tmp).and_then(|mut f| { + f.write_all(bytes)?; + f.sync_all().ok(); + Ok(()) + }); + // Unique names would otherwise pile up (secrets included) after failed writes. + if let Err(e) = written.and_then(|()| fs::rename(&tmp, path)) { + fs::remove_file(&tmp).ok(); + return Err(e.into()); + } } - fs::rename(&tmp, path)?; Ok(()) } From d281601f866a43fb99e5f079cbeb026a8a58f3fa Mon Sep 17 00:00:00 2001 From: RealDoc06 <73218979+RealDoc06@users.noreply.github.com> Date: Thu, 19 Nov 2026 05:21:45 +0100 Subject: [PATCH 16/33] fix(hub): take the Argon2 queue slot before counting a sign in A 503 from a busy hub no longer costs an attempt, and turned-away requests leave nothing in the failure map. --- crates/hub/src/routes.rs | 35 +++++++++++++++++++++++------------ docs/ARCHITECTURE.md | 2 +- 2 files changed, 24 insertions(+), 13 deletions(-) diff --git a/crates/hub/src/routes.rs b/crates/hub/src/routes.rs index 3c4b944..1df682c 100644 --- a/crates/hub/src/routes.rs +++ b/crates/hub/src/routes.rs @@ -198,7 +198,7 @@ async fn register(State(s): State, Json(c): Json) -> Resu if taken(&s.db())? { return Err(Error::conflict("that username is taken")); } - let pw = argon(move || hash_password(&c.password)).await??; + let pw = argon(ArgonSlot::take()?, move || hash_password(&c.password)).await??; let db = s.db(); let id = new_id(); if taken(&db)? { @@ -219,21 +219,31 @@ static ARGON: LazyLock> = const MAX_ARGON_WAITING: usize = 256; static ARGON_WAITING: AtomicUsize = AtomicUsize::new(0); -/// Runs Argon2 on the blocking pool, so it never stalls an async worker (and, under the DB lock, -/// every request). The permit lives as long as the work, even if the request is dropped. -async fn argon(f: impl FnOnce() -> T + Send + 'static) -> Result { - struct Waiting; - impl Drop for Waiting { - fn drop(&mut self) { +/// A place in the queue for [`ARGON`], taken before anything else is recorded so a busy hub +/// turns requests away without counting them (or remembering their usernames). +struct ArgonSlot; + +impl ArgonSlot { + fn take() -> Result { + if ARGON_WAITING.fetch_add(1, Ordering::Relaxed) >= MAX_ARGON_WAITING { ARGON_WAITING.fetch_sub(1, Ordering::Relaxed); + return Err(Error(StatusCode::SERVICE_UNAVAILABLE, "the hub is busy, try again shortly".into())); } + Ok(Self) } - let waiting = Waiting; - if ARGON_WAITING.fetch_add(1, Ordering::Relaxed) >= MAX_ARGON_WAITING { - return Err(Error(StatusCode::SERVICE_UNAVAILABLE, "the hub is busy, try again shortly".into())); +} + +impl Drop for ArgonSlot { + fn drop(&mut self) { + ARGON_WAITING.fetch_sub(1, Ordering::Relaxed); } +} + +/// Runs Argon2 on the blocking pool, so it never stalls an async worker (and, under the DB lock, +/// every request). The permit lives as long as the work, even if the request is dropped. +async fn argon(slot: ArgonSlot, f: impl FnOnce() -> T + Send + 'static) -> Result { let permit = ARGON.clone().acquire_owned().await.map_err(anyhow::Error::from)?; - drop(waiting); + drop(slot); tokio::task::spawn_blocking(move || { let out = f(); drop(permit); @@ -263,6 +273,7 @@ pub async fn check_credentials(s: &AppState, c: Credentials) -> Result { Ok((r.get(0)?, r.get(1)?, r.get(2)?)) }) .optional()?; + let slot = ArgonSlot::take()?; // Counted before checking, so parallel guesses can't all slip in under the limit. let allowed = s.failures(&key, |(count, _)| { *count += 1; @@ -272,7 +283,7 @@ pub async fn check_credentials(s: &AppState, c: Credentials) -> Result { return Err(Error(StatusCode::TOO_MANY_REQUESTS, "too many wrong passwords, try again in 15 minutes".into())); } let hash = row.as_ref().map(|(_, _, h)| h.clone()); - let ok = argon(move || verify_password(&c.password, hash.as_deref().unwrap_or(&DUMMY_HASH))).await?; + let ok = argon(slot, move || verify_password(&c.password, hash.as_deref().unwrap_or(&DUMMY_HASH))).await?; let Some((id, username, _)) = row.filter(|_| ok) else { return Err(wrong()); }; diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 74e5349..3a7964a 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -134,7 +134,7 @@ GET /api/objects/:hash -> raw object bytes (blobs, trees, commits) Authenticated: ``` -POST /api/auth/register|login { username, password } -> { token, user } (429 after 10 wrong passwords for a username, existing or not, within 15 minutes; per account, so it can keep a known username's password sign in locked, but tokens keep working) +POST /api/auth/register|login { username, password } -> { token, user } (429 after 10 wrong passwords for a username, existing or not, within 15 minutes; per account, so it can keep a known username's password sign in locked, but tokens keep working; 503 when too many sign ins are already waiting) POST /api/auth/device/start -> { device_code, user_code, expires_in } POST /api/auth/device/poll { device_code } -> { token, user } | 428 pending POST /api/auth/device/approve { user_code } From b64f73aac085e92b2ef96edf65d361f9af041f15 Mon Sep 17 00:00:00 2001 From: RealDoc06 <73218979+RealDoc06@users.noreply.github.com> Date: Thu, 19 Nov 2026 05:21:46 +0100 Subject: [PATCH 17/33] fix(cli): restores stop if the world can't be cleared and put the token back owner-only Backup temp files are unique per call, so concurrent backups can't remove each other's in-progress archive. --- crates/cli/src/backups.rs | 55 ++++++++++++++++++++++++++++++++------- 1 file changed, 45 insertions(+), 10 deletions(-) diff --git a/crates/cli/src/backups.rs b/crates/cli/src/backups.rs index d73074b..9356c62 100644 --- a/crates/cli/src/backups.rs +++ b/crates/cli/src/backups.rs @@ -10,6 +10,7 @@ use beacon_core::{ }; use std::{ fs, + io::Read, path::{Component, Path, PathBuf}, time::UNIX_EPOCH, }; @@ -171,11 +172,13 @@ pub fn create(server: &Path, note: &str) -> Result { fs::create_dir_all(&dir)?; let slug: String = note.chars().map(|c| if c.is_ascii_alphanumeric() || c == '.' { c } else { '-' }).collect(); let name = format!("{}-{}.tar.gz", beacon_core::now(), slug.trim_matches('-')); - let tmp = dir.join(format!("{name}.part")); + // Unique per call, so concurrent backups never share (or delete) each other's temp file. + static SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let seq = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let tmp = dir.join(format!("{name}.{}-{seq}.part", std::process::id())); { // Owner-only on Unix: the archive holds `.beacon/server.json` and its hub token. Created - // exclusively, so a leftover `.part` with looser permissions is never reused. - fs::remove_file(&tmp).ok(); + // exclusively, so nothing already at that path is ever reused. let mut options = fs::OpenOptions::new(); options.write(true).create_new(true); #[cfg(unix)] @@ -264,22 +267,43 @@ fn world_dir(server: &Path) -> Result { Ok(server.join(part)) } +/// Where the server's config, hub token included, lives inside a whole server backup. +const SERVER_CONFIG: &str = ".beacon/server.json"; + +/// Removes a world folder before a restore. Missing is fine; anything else stops the restore. +fn clear(dir: &Path) -> Result<()> { + match fs::remove_dir_all(dir) { + Err(e) if e.kind() != std::io::ErrorKind::NotFound => Err(e).with_context(|| format!("clearing {}", dir.display())), + _ => Ok(()), + } +} + /// Restores a backup. Minecraft must be stopped. Whole server backups replace the pack files /// and worlds; mod backups replace only the world they contain. pub fn restore(server: &Path, id: &str) -> Result<()> { let b = find(server, id)?; let file = server.join(&b.id); if b.full { - // Checked first: a refused restore must leave the server as it was. - let world = world_dir(server)?; + // Checked first: a refused restore must leave the server as it was. Chunks generated + // after the backup would otherwise survive, so a world that can't be cleared stops it. + clear(&world_dir(server)?)?; if let Some(tree) = srv::applied_tree(server) { for p in tree.files.keys() { fs::remove_file(server.join(p)).ok(); } } - // Chunks generated after the backup would otherwise survive the restore. - fs::remove_dir_all(world).ok(); - tar::Archive::new(flate2::read::GzDecoder::new(fs::File::open(file)?)).unpack(server)?; + let mut archive = tar::Archive::new(flate2::read::GzDecoder::new(fs::File::open(file)?)); + for entry in archive.entries()? { + let mut entry = entry?; + // The server token goes back owner-only from the start, never through a default mode. + if entry.path()? == Path::new(SERVER_CONFIG) { + let mut bytes = vec![]; + entry.read_to_end(&mut bytes)?; + beacon_core::store::write_private(&server.join(SERVER_CONFIG), &bytes)?; + } else { + entry.unpack_in(server)?; + } + } return Ok(()); } let name = b.id.to_ascii_lowercase(); @@ -288,7 +312,7 @@ pub fn restore(server: &Path, id: &str) -> Result<()> { } let entries = archive_entries(&file)?; // Either the world's files at the root, or one folder holding them. - let (dest, clear) = if entries.iter().any(|e| e == "level.dat") { + let (dest, old) = if entries.iter().any(|e| e == "level.dat") { let world = world_dir(server)?; (world.clone(), world) } else if let Some(top) = entries.iter().find_map(|e| e.strip_suffix("/level.dat").and_then(one_folder)) { @@ -296,7 +320,7 @@ pub fn restore(server: &Path, id: &str) -> Result<()> { } else { bail!("{} doesn't look like a world backup (no level.dat)", b.note); }; - fs::remove_dir_all(&clear).ok(); + clear(&old)?; fs::create_dir_all(&dest)?; if b.id.to_ascii_lowercase().ends_with(".zip") { zip::ZipArchive::new(fs::File::open(&file)?)?.extract(&dest)?; @@ -344,6 +368,8 @@ mod tests { #[test] fn full_backup_round_trips_and_leaves_newer_chunks_out() { let d = server(); + fs::create_dir_all(d.join(".beacon")).unwrap(); + fs::write(d.join(SERVER_CONFIG), "{\"token\":\"secret\"}").unwrap(); let b = create(&d, "before 1.4").unwrap(); assert_eq!((b.source.as_str(), b.note.as_str(), b.full), ("BeaconSync", "before 1.4", true)); fs::write(d.join("world/level.dat"), "new").unwrap(); @@ -351,6 +377,15 @@ mod tests { restore(&d, &b.id).unwrap(); assert_eq!(fs::read_to_string(d.join("world/level.dat")).unwrap(), "old"); assert!(!d.join("world/region/r.0.0.mca").exists()); + // The archive and the restored token are owner-only. + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let mode = |p: &Path| fs::metadata(p).unwrap().permissions().mode() & 0o777; + assert_eq!(mode(&d.join(&b.id)), 0o600); + assert_eq!(mode(&d.join(SERVER_CONFIG)), 0o600); + } + assert_eq!(fs::read_to_string(d.join(SERVER_CONFIG)).unwrap(), "{\"token\":\"secret\"}"); fs::remove_dir_all(d).ok(); } From cf2c5382c8bdf40233e74c642af820d243ea6621 Mon Sep 17 00:00:00 2001 From: RealDoc06 <73218979+RealDoc06@users.noreply.github.com> Date: Thu, 19 Nov 2026 05:21:46 +0100 Subject: [PATCH 18/33] fix(core): only clean up a temp file this write created --- crates/core/src/store.rs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/crates/core/src/store.rs b/crates/core/src/store.rs index 75280a1..cc8302d 100644 --- a/crates/core/src/store.rs +++ b/crates/core/src/store.rs @@ -105,11 +105,12 @@ fn write_through_temp(path: &Path, bytes: &[u8], private: bool) -> Result<()> { } #[cfg(not(unix))] let _ = private; - let written = options.open(&tmp).and_then(|mut f| { - f.write_all(bytes)?; + // Only cleaned up once this call created it: a failed exclusive open names someone else's file. + let mut f = options.open(&tmp)?; + let written = f.write_all(bytes).map(|()| { f.sync_all().ok(); - Ok(()) }); + drop(f); // Unique names would otherwise pile up (secrets included) after failed writes. if let Err(e) = written.and_then(|()| fs::rename(&tmp, path)) { fs::remove_file(&tmp).ok(); From 00e980d10d83b102094d896761c3a6d9a9a61a51 Mon Sep 17 00:00:00 2001 From: RealDoc06 <73218979+RealDoc06@users.noreply.github.com> Date: Thu, 19 Nov 2026 05:28:19 +0100 Subject: [PATCH 19/33] fix(hub): count a sign in attempt inside the Argon2 job A request dropped while queued (client timeout during a backlog) no longer costs an attempt, and a correct password clears the count in the same job. --- crates/hub/src/routes.rs | 37 +++++++++++++++++++++++-------------- 1 file changed, 23 insertions(+), 14 deletions(-) diff --git a/crates/hub/src/routes.rs b/crates/hub/src/routes.rs index 1df682c..24f3c1f 100644 --- a/crates/hub/src/routes.rs +++ b/crates/hub/src/routes.rs @@ -274,21 +274,30 @@ pub async fn check_credentials(s: &AppState, c: Credentials) -> Result { }) .optional()?; let slot = ArgonSlot::take()?; - // Counted before checking, so parallel guesses can't all slip in under the limit. - let allowed = s.failures(&key, |(count, _)| { - *count += 1; - *count <= MAX_FAILURES - }); - if !allowed { - return Err(Error(StatusCode::TOO_MANY_REQUESTS, "too many wrong passwords, try again in 15 minutes".into())); - } let hash = row.as_ref().map(|(_, _, h)| h.clone()); - let ok = argon(slot, move || verify_password(&c.password, hash.as_deref().unwrap_or(&DUMMY_HASH))).await?; - let Some((id, username, _)) = row.filter(|_| ok) else { - return Err(wrong()); - }; - s.failures.lock().unwrap_or_else(|e| e.into_inner()).remove(&key); - Ok(User { id, username }) + let state = s.clone(); + // Counted inside the job, right before the check: parallel guesses can't all slip in under + // the limit, and a request turned away or dropped while queued never costs an attempt. + let verdict = argon(slot, move || { + let allowed = state.failures(&key, |(count, _)| { + *count += 1; + *count <= MAX_FAILURES + }); + if !allowed { + return None; + } + let ok = verify_password(&c.password, hash.as_deref().unwrap_or(&DUMMY_HASH)) && hash.is_some(); + if ok { + state.failures.lock().unwrap_or_else(|e| e.into_inner()).remove(&key); + } + Some(ok) + }) + .await?; + match (verdict, row) { + (None, _) => Err(Error(StatusCode::TOO_MANY_REQUESTS, "too many wrong passwords, try again in 15 minutes".into())), + (Some(true), Some((id, username, _))) => Ok(User { id, username }), + _ => Err(wrong()), + } } async fn login(State(s): State, Json(c): Json) -> Result> { From e42c0e28ead189708561ad18ff0368d7e5027a25 Mon Sep 17 00:00:00 2001 From: RealDoc06 <73218979+RealDoc06@users.noreply.github.com> Date: Thu, 19 Nov 2026 05:28:19 +0100 Subject: [PATCH 20/33] fix(cli): harden the full restore token write and clean up failed backups The token entry matches however it is spelled, is never written through a symlinked .beacon, and restores unpack into the canonical server path like Archive::unpack did. A failed backup removes its partial archive. --- crates/cli/src/backups.rs | 51 ++++++++++++++++++++++++++++----------- 1 file changed, 37 insertions(+), 14 deletions(-) diff --git a/crates/cli/src/backups.rs b/crates/cli/src/backups.rs index 9356c62..d427ee9 100644 --- a/crates/cli/src/backups.rs +++ b/crates/cli/src/backups.rs @@ -187,19 +187,27 @@ pub fn create(server: &Path, note: &str) -> Result { options.mode(0o600); } let enc = flate2::write::GzEncoder::new(options.open(&tmp)?, flate2::Compression::fast()); - let mut tar = tar::Builder::new(enc); - tar.follow_symlinks(false); - let world = level_name(server); - let walk = walkdir::WalkDir::new(server).min_depth(1).into_iter(); - for e in walk.filter_entry(|e| !skip(server, &world, e.path().strip_prefix(server).unwrap_or(e.path()))) { - let e = e?; - if e.file_type().is_file() { - tar.append_path_with_name(e.path(), e.path().strip_prefix(server)?)?; + let written = (|| -> Result<()> { + let mut tar = tar::Builder::new(enc); + tar.follow_symlinks(false); + let world = level_name(server); + let walk = walkdir::WalkDir::new(server).min_depth(1).into_iter(); + for e in walk.filter_entry(|e| !skip(server, &world, e.path().strip_prefix(server).unwrap_or(e.path()))) { + let e = e?; + if e.file_type().is_file() { + tar.append_path_with_name(e.path(), e.path().strip_prefix(server)?)?; + } } + tar.into_inner()?.finish()?; + fs::rename(&tmp, dir.join(&name))?; + Ok(()) + })(); + // A failed backup (disk full, say) must not leave a partial archive outside retention. + if written.is_err() { + fs::remove_file(&tmp).ok(); } - tar.into_inner()?.finish()?; + written?; } - fs::rename(&tmp, dir.join(&name))?; find(server, &rel(server, &dir.join(name))) } @@ -270,6 +278,14 @@ fn world_dir(server: &Path) -> Result { /// Where the server's config, hub token included, lives inside a whole server backup. const SERVER_CONFIG: &str = ".beacon/server.json"; +/// Whether an archive path names [`SERVER_CONFIG`], however it is spelled (`./`, or another case +/// on a case-insensitive disk). +fn is_server_config(path: &Path) -> bool { + let parts: Vec<_> = path.components().filter(|c| !matches!(c, Component::CurDir)).collect(); + matches!(parts.as_slice(), [Component::Normal(dir), Component::Normal(file)] + if dir.eq_ignore_ascii_case(".beacon") && file.eq_ignore_ascii_case("server.json")) +} + /// Removes a world folder before a restore. Missing is fine; anything else stops the restore. fn clear(dir: &Path) -> Result<()> { match fs::remove_dir_all(dir) { @@ -292,16 +308,22 @@ pub fn restore(server: &Path, id: &str) -> Result<()> { fs::remove_file(server.join(p)).ok(); } } + // Canonical like `Archive::unpack`, which also gives Windows its long path prefix. + let dest = server.canonicalize()?; let mut archive = tar::Archive::new(flate2::read::GzDecoder::new(fs::File::open(file)?)); for entry in archive.entries()? { let mut entry = entry?; - // The server token goes back owner-only from the start, never through a default mode. - if entry.path()? == Path::new(SERVER_CONFIG) { + // The server token goes back owner-only from the start, never through a default mode, + // and only into the server's own `.beacon` folder. + if is_server_config(&entry.path()?) { + if fs::symlink_metadata(dest.join(".beacon")).is_ok_and(|m| m.file_type().is_symlink()) { + bail!("{} is a link; not writing the server token through it", dest.join(".beacon").display()); + } let mut bytes = vec![]; entry.read_to_end(&mut bytes)?; - beacon_core::store::write_private(&server.join(SERVER_CONFIG), &bytes)?; + beacon_core::store::write_private(&dest.join(SERVER_CONFIG), &bytes)?; } else { - entry.unpack_in(server)?; + entry.unpack_in(&dest)?; } } return Ok(()); @@ -425,6 +447,7 @@ mod tests { assert!(restore(&d, &own.id).is_err()); assert!(d.join("world/level.dat").exists() && d.join("mods/pack.jar").exists(), "a refused restore deletes nothing"); assert_eq!(one_folder("world/"), Some(std::ffi::OsStr::new("world"))); + assert!(is_server_config(Path::new("./.Beacon/Server.json")) && !is_server_config(Path::new("x/.beacon/server.json"))); fs::write(d.join("server.properties"), "level-name=world\n").unwrap(); // Partial archives from incremental backups are refused rather than half restored. fs::copy(d.join("backups/2026-11-05.zip"), d.join("backups/incremental.zip")).unwrap(); From bcb1bc827e649309249aaf1602ec61b0dc5b34f3 Mon Sep 17 00:00:00 2001 From: RealDoc06 <73218979+RealDoc06@users.noreply.github.com> Date: Thu, 19 Nov 2026 05:33:15 +0100 Subject: [PATCH 21/33] fix: run every restore check before deleting, and cancel dropped Argon2 jobs Full restores resolve the server path and refuse a symlinked .beacon before the world or pack files are touched. Token entries keep their own spelling so case-distinct files stay separate. A sign in dropped before its Argon2 job starts cancels the job, so it never counts an attempt. --- crates/cli/src/backups.rs | 52 +++++++++++++++++++++++++-------------- crates/hub/src/routes.rs | 16 ++++++++---- 2 files changed, 45 insertions(+), 23 deletions(-) diff --git a/crates/cli/src/backups.rs b/crates/cli/src/backups.rs index d427ee9..dcc653b 100644 --- a/crates/cli/src/backups.rs +++ b/crates/cli/src/backups.rs @@ -275,15 +275,20 @@ fn world_dir(server: &Path) -> Result { Ok(server.join(part)) } -/// Where the server's config, hub token included, lives inside a whole server backup. -const SERVER_CONFIG: &str = ".beacon/server.json"; - -/// Whether an archive path names [`SERVER_CONFIG`], however it is spelled (`./`, or another case -/// on a case-insensitive disk). -fn is_server_config(path: &Path) -> bool { +/// The archive path, without `./` parts, when it names `.beacon/server.json` (the server's config, +/// hub token included) in any letter case (on a +/// case-insensitive disk every spelling is the live token). Callers write it under this spelling, +/// so case-distinct files on other disks stay separate files, each owner-only. +fn server_config_entry(path: &Path) -> Option { let parts: Vec<_> = path.components().filter(|c| !matches!(c, Component::CurDir)).collect(); - matches!(parts.as_slice(), [Component::Normal(dir), Component::Normal(file)] - if dir.eq_ignore_ascii_case(".beacon") && file.eq_ignore_ascii_case("server.json")) + match parts.as_slice() { + [Component::Normal(dir), Component::Normal(file)] + if dir.eq_ignore_ascii_case(".beacon") && file.eq_ignore_ascii_case("server.json") => + { + Some(Path::new(dir).join(file)) + } + _ => None, + } } /// Removes a world folder before a restore. Missing is fine; anything else stops the restore. @@ -300,28 +305,36 @@ pub fn restore(server: &Path, id: &str) -> Result<()> { let b = find(server, id)?; let file = server.join(&b.id); if b.full { - // Checked first: a refused restore must leave the server as it was. Chunks generated - // after the backup would otherwise survive, so a world that can't be cleared stops it. - clear(&world_dir(server)?)?; + // Everything that can refuse runs first: a refused restore must leave the server as it was. + // Canonical like `Archive::unpack`, which also gives Windows its long path prefix. + let dest = server.canonicalize()?; + let world = world_dir(server)?; + let beacon = dest.join(".beacon"); + let linked = || fs::symlink_metadata(&beacon).is_ok_and(|m| m.file_type().is_symlink()); + if linked() { + bail!("{} is a link; not restoring the server token through it", beacon.display()); + } + // Chunks generated after the backup would otherwise survive, so a world that can't be + // cleared stops the restore. + clear(&world)?; if let Some(tree) = srv::applied_tree(server) { for p in tree.files.keys() { fs::remove_file(server.join(p)).ok(); } } - // Canonical like `Archive::unpack`, which also gives Windows its long path prefix. - let dest = server.canonicalize()?; let mut archive = tar::Archive::new(flate2::read::GzDecoder::new(fs::File::open(file)?)); for entry in archive.entries()? { let mut entry = entry?; // The server token goes back owner-only from the start, never through a default mode, // and only into the server's own `.beacon` folder. - if is_server_config(&entry.path()?) { - if fs::symlink_metadata(dest.join(".beacon")).is_ok_and(|m| m.file_type().is_symlink()) { - bail!("{} is a link; not writing the server token through it", dest.join(".beacon").display()); + if let Some(rel) = server_config_entry(&entry.path()?) { + // Checked again right before writing, in case the archive itself created the link. + if linked() { + bail!("{} is a link; not restoring the server token through it", beacon.display()); } let mut bytes = vec![]; entry.read_to_end(&mut bytes)?; - beacon_core::store::write_private(&dest.join(SERVER_CONFIG), &bytes)?; + beacon_core::store::write_private(&dest.join(rel), &bytes)?; } else { entry.unpack_in(&dest)?; } @@ -371,6 +384,8 @@ fn archive_entries(file: &Path) -> Result> { #[cfg(test)] mod tests { use super::*; + + const SERVER_CONFIG: &str = ".beacon/server.json"; use std::io::Write; fn server() -> PathBuf { @@ -447,7 +462,8 @@ mod tests { assert!(restore(&d, &own.id).is_err()); assert!(d.join("world/level.dat").exists() && d.join("mods/pack.jar").exists(), "a refused restore deletes nothing"); assert_eq!(one_folder("world/"), Some(std::ffi::OsStr::new("world"))); - assert!(is_server_config(Path::new("./.Beacon/Server.json")) && !is_server_config(Path::new("x/.beacon/server.json"))); + assert_eq!(server_config_entry(Path::new("./.Beacon/Server.json")), Some(PathBuf::from(".Beacon/Server.json"))); + assert_eq!(server_config_entry(Path::new("x/.beacon/server.json")), None); fs::write(d.join("server.properties"), "level-name=world\n").unwrap(); // Partial archives from incremental backups are refused rather than half restored. fs::copy(d.join("backups/2026-11-05.zip"), d.join("backups/incremental.zip")).unwrap(); diff --git a/crates/hub/src/routes.rs b/crates/hub/src/routes.rs index 24f3c1f..cfe31c5 100644 --- a/crates/hub/src/routes.rs +++ b/crates/hub/src/routes.rs @@ -240,17 +240,23 @@ impl Drop for ArgonSlot { } /// Runs Argon2 on the blocking pool, so it never stalls an async worker (and, under the DB lock, -/// every request). The permit lives as long as the work, even if the request is dropped. +/// every request). The permit lives as long as the work. If the request is dropped before the job +/// starts, the job is cancelled, so it never runs (or counts an attempt) for nobody. async fn argon(slot: ArgonSlot, f: impl FnOnce() -> T + Send + 'static) -> Result { + struct AbortOnDrop(tokio::task::JoinHandle); + impl Drop for AbortOnDrop { + fn drop(&mut self) { + self.0.abort(); + } + } let permit = ARGON.clone().acquire_owned().await.map_err(anyhow::Error::from)?; drop(slot); - tokio::task::spawn_blocking(move || { + let mut job = AbortOnDrop(tokio::task::spawn_blocking(move || { let out = f(); drop(permit); out - }) - .await - .map_err(|e| anyhow::Error::from(e).into()) + })); + (&mut job.0).await.map_err(|e| anyhow::Error::from(e).into()) } /// Checked against when the username doesn't exist, so unknown names cost the same time as real From d26cc3a3c74922d11199da6bcf5739a8ded2a1a6 Mon Sep 17 00:00:00 2001 From: RealDoc06 <73218979+RealDoc06@users.noreply.github.com> Date: Thu, 19 Nov 2026 05:37:27 +0100 Subject: [PATCH 22/33] fix: check the token's real parent folder, refuse broken backups up front The link check now looks at the folder each token entry is written to, so a .Beacon link on a case-sensitive disk is refused. A full restore reads the whole archive before deleting anything, so a truncated backup leaves the server as it was. Atomic write temp names no longer embed the target name (255 byte limit). --- crates/cli/src/backups.rs | 66 +++++++++++++++++++++++++++++++++------ crates/core/src/store.rs | 4 +-- 2 files changed, 58 insertions(+), 12 deletions(-) diff --git a/crates/cli/src/backups.rs b/crates/cli/src/backups.rs index dcc653b..7c808cc 100644 --- a/crates/cli/src/backups.rs +++ b/crates/cli/src/backups.rs @@ -276,9 +276,9 @@ fn world_dir(server: &Path) -> Result { } /// The archive path, without `./` parts, when it names `.beacon/server.json` (the server's config, -/// hub token included) in any letter case (on a -/// case-insensitive disk every spelling is the live token). Callers write it under this spelling, -/// so case-distinct files on other disks stay separate files, each owner-only. +/// hub token included) in any letter case: on a case-insensitive disk every spelling is the live +/// token. Callers write it under this spelling, so case-distinct files on other disks stay separate +/// files, each owner-only. fn server_config_entry(path: &Path) -> Option { let parts: Vec<_> = path.components().filter(|c| !matches!(c, Component::CurDir)).collect(); match parts.as_slice() { @@ -309,10 +309,19 @@ pub fn restore(server: &Path, id: &str) -> Result<()> { // Canonical like `Archive::unpack`, which also gives Windows its long path prefix. let dest = server.canonicalize()?; let world = world_dir(server)?; - let beacon = dest.join(".beacon"); - let linked = || fs::symlink_metadata(&beacon).is_ok_and(|m| m.file_type().is_symlink()); - if linked() { - bail!("{} is a link; not restoring the server token through it", beacon.display()); + // Reading the whole archive first also refuses a truncated or corrupt backup up front. + let tokens: Vec = archive_entries(&file)?.iter().filter_map(|e| server_config_entry(Path::new(e))).collect(); + // The token is only ever written into a real folder inside the server, never through a link. + let refuse_link = |rel: &Path| -> Result<()> { + let dir = dest.join(rel.parent().unwrap_or(rel)); + if fs::symlink_metadata(&dir).is_ok_and(|m| m.file_type().is_symlink()) { + bail!("{} is a link; not restoring the server token through it", dir.display()); + } + Ok(()) + }; + refuse_link(Path::new(".beacon/server.json"))?; + for rel in &tokens { + refuse_link(rel)?; } // Chunks generated after the backup would otherwise survive, so a world that can't be // cleared stops the restore. @@ -329,9 +338,7 @@ pub fn restore(server: &Path, id: &str) -> Result<()> { // and only into the server's own `.beacon` folder. if let Some(rel) = server_config_entry(&entry.path()?) { // Checked again right before writing, in case the archive itself created the link. - if linked() { - bail!("{} is a link; not restoring the server token through it", beacon.display()); - } + refuse_link(&rel)?; let mut bytes = vec![]; entry.read_to_end(&mut bytes)?; beacon_core::store::write_private(&dest.join(rel), &bytes)?; @@ -426,6 +433,45 @@ mod tests { fs::remove_dir_all(d).ok(); } + #[test] + fn broken_or_linking_full_backups_are_refused() { + let d = server(); + let good = create(&d, "good").unwrap(); + let own = own_dir(&d); + // Truncated: refused before the world is touched. + let bytes = fs::read(d.join(&good.id)).unwrap(); + fs::write(own.join("1-truncated.tar.gz"), &bytes[..bytes.len() / 2]).unwrap(); + assert!(find(&d, ".beacon/backups/1-truncated.tar.gz").unwrap().full); + assert!(restore(&d, ".beacon/backups/1-truncated.tar.gz").is_err()); + assert_eq!(fs::read_to_string(d.join("world/level.dat")).unwrap(), "old"); + // A `.Beacon` link made by the archive itself is never written through. + #[cfg(unix)] + { + let outside = std::env::temp_dir().join(format!("beacon-outside-{}", rand_suffix())); + fs::create_dir_all(&outside).unwrap(); + let mut tar = tar::Builder::new(flate2::write::GzEncoder::new( + fs::File::create(own.join("2-linking.tar.gz")).unwrap(), + flate2::Compression::fast(), + )); + let mut link = tar::Header::new_gnu(); + link.set_entry_type(tar::EntryType::Symlink); + link.set_size(0); + tar.append_link(&mut link, ".Beacon", &outside).unwrap(); + let mut file = tar::Header::new_gnu(); + file.set_size(2); + tar.append_data(&mut file, ".Beacon/server.json", &b"{}"[..]).unwrap(); + tar.into_inner().unwrap().finish().unwrap(); + assert!(find(&d, ".beacon/backups/2-linking.tar.gz").unwrap().full); + let err = restore(&d, ".beacon/backups/2-linking.tar.gz").unwrap_err().to_string(); + // Case-sensitive disks reach the link check; case-insensitive ones can't create `.Beacon` + // next to the real `.beacon` at all. + assert!(err.contains("is a link") || cfg!(target_os = "macos"), "{err}"); + assert!(!outside.join("server.json").exists()); + fs::remove_dir_all(outside).ok(); + } + fs::remove_dir_all(d).ok(); + } + #[test] fn mod_zip_backups_are_listed_and_restore_the_world() { let d = server(); diff --git a/crates/core/src/store.rs b/crates/core/src/store.rs index cc8302d..402f3f8 100644 --- a/crates/core/src/store.rs +++ b/crates/core/src/store.rs @@ -87,9 +87,9 @@ fn write_through_temp(path: &Path, bytes: &[u8], private: bool) -> Result<()> { let dir = path.parent().context("path has no parent")?; fs::create_dir_all(dir)?; let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.subsec_nanos()); + // Short and independent of the target's name, so long file names still fit the 255 byte limit. let tmp = dir.join(format!( - ".{}.{}-{}-{nanos}.tmp", - path.file_name().and_then(|n| n.to_str()).unwrap_or("obj"), + ".beacon-{}-{}-{nanos}.tmp", std::process::id(), SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed), )); From 95f3bb6114db605957b4f80156685060f7cf75a3 Mon Sep 17 00:00:00 2001 From: RealDoc06 <73218979+RealDoc06@users.noreply.github.com> Date: Thu, 19 Nov 2026 05:42:58 +0100 Subject: [PATCH 23/33] fix(cli): check the gzip checksum and token links before a full restore deletes anything tar stops at its end marker before flate2 verifies the footer, so a damaged backup could restore corrupt data. The preflight now drains the stream and refuses link entries where the token's folder would be. --- crates/cli/src/backups.rs | 36 +++++++++++++++++++++++++++++++----- 1 file changed, 31 insertions(+), 5 deletions(-) diff --git a/crates/cli/src/backups.rs b/crates/cli/src/backups.rs index 7c808cc..1f6ef0e 100644 --- a/crates/cli/src/backups.rs +++ b/crates/cli/src/backups.rs @@ -309,8 +309,7 @@ pub fn restore(server: &Path, id: &str) -> Result<()> { // Canonical like `Archive::unpack`, which also gives Windows its long path prefix. let dest = server.canonicalize()?; let world = world_dir(server)?; - // Reading the whole archive first also refuses a truncated or corrupt backup up front. - let tokens: Vec = archive_entries(&file)?.iter().filter_map(|e| server_config_entry(Path::new(e))).collect(); + let tokens = check_full_archive(&file)?; // The token is only ever written into a real folder inside the server, never through a link. let refuse_link = |rel: &Path| -> Result<()> { let dir = dest.join(rel.parent().unwrap_or(rel)); @@ -372,6 +371,26 @@ pub fn restore(server: &Path, id: &str) -> Result<()> { Ok(()) } +/// Reads a whole server archive before a restore touches anything, returning the spellings of its +/// token entries. Refuses a truncated or corrupted backup (every entry, then the rest of the gzip +/// stream so its checksum is checked: tar stops at its end marker) and a link entry where the +/// token's folder would be. +fn check_full_archive(file: &Path) -> Result> { + let mut tar = tar::Archive::new(flate2::read::GzDecoder::new(fs::File::open(file)?)); + let mut tokens = vec![]; + for entry in tar.entries()? { + let entry = entry?; + let path = entry.path()?; + let kind = entry.header().entry_type(); + if (kind.is_symlink() || kind.is_hard_link()) && server_config_entry(&path.join("server.json")).is_some() { + bail!("the backup links {}; not restoring the server token through it", path.display()); + } + tokens.extend(server_config_entry(&path)); + } + std::io::copy(&mut tar.into_inner(), &mut std::io::sink()).context("the backup is damaged")?; + Ok(tokens) +} + fn archive_entries(file: &Path) -> Result> { if file.to_string_lossy().to_ascii_lowercase().ends_with(".zip") { let z = zip::ZipArchive::new(fs::File::open(file)?)?; @@ -443,6 +462,14 @@ mod tests { fs::write(own.join("1-truncated.tar.gz"), &bytes[..bytes.len() / 2]).unwrap(); assert!(find(&d, ".beacon/backups/1-truncated.tar.gz").unwrap().full); assert!(restore(&d, ".beacon/backups/1-truncated.tar.gz").is_err()); + // Only the gzip footer missing, or one flipped byte: tar alone would read these fine. + fs::write(own.join("1-footerless.tar.gz"), &bytes[..bytes.len() - 8]).unwrap(); + assert!(restore(&d, ".beacon/backups/1-footerless.tar.gz").is_err()); + let mut flipped = bytes.clone(); + let len = flipped.len(); + flipped[len - 5] ^= 0xff; + fs::write(own.join("1-flipped.tar.gz"), &flipped).unwrap(); + assert!(restore(&d, ".beacon/backups/1-flipped.tar.gz").is_err()); assert_eq!(fs::read_to_string(d.join("world/level.dat")).unwrap(), "old"); // A `.Beacon` link made by the archive itself is never written through. #[cfg(unix)] @@ -463,10 +490,9 @@ mod tests { tar.into_inner().unwrap().finish().unwrap(); assert!(find(&d, ".beacon/backups/2-linking.tar.gz").unwrap().full); let err = restore(&d, ".beacon/backups/2-linking.tar.gz").unwrap_err().to_string(); - // Case-sensitive disks reach the link check; case-insensitive ones can't create `.Beacon` - // next to the real `.beacon` at all. - assert!(err.contains("is a link") || cfg!(target_os = "macos"), "{err}"); + assert!(err.contains("links"), "{err}"); assert!(!outside.join("server.json").exists()); + assert_eq!(fs::read_to_string(d.join("world/level.dat")).unwrap(), "old", "refused before deleting"); fs::remove_dir_all(outside).ok(); } fs::remove_dir_all(d).ok(); From bd19d3d92187f0abadd2f2619c2f593355c0ebed Mon Sep 17 00:00:00 2001 From: RealDoc06 <73218979+RealDoc06@users.noreply.github.com> Date: Thu, 19 Nov 2026 05:46:59 +0100 Subject: [PATCH 24/33] fix(cli): refused restores change nothing, so the agent no longer rolls back after them restore() now plans (every check) before it applies, and errors from the plan come back as backups::Refused. The agent restores its safety backup only when a restore failed after changing files. Full restores also refuse rooted or .. entries, which tar would otherwise strip past the token checks. --- crates/cli/src/backups.rs | 137 +++++++++++++++++++++++++++----------- crates/cli/src/server.rs | 5 +- 2 files changed, 102 insertions(+), 40 deletions(-) diff --git a/crates/cli/src/backups.rs b/crates/cli/src/backups.rs index 1f6ef0e..79eeb30 100644 --- a/crates/cli/src/backups.rs +++ b/crates/cli/src/backups.rs @@ -299,53 +299,57 @@ fn clear(dir: &Path) -> Result<()> { } } +/// A restore error raised before any file changed: there is nothing to undo. +#[derive(Debug)] +pub struct Refused(String); + +impl std::fmt::Display for Refused { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.0) + } +} + +impl std::error::Error for Refused {} + +/// What a restore will do, worked out (and every check passed) before anything is deleted. +enum Plan { + /// A whole server backup: `dest` is the canonical server folder. + Full { file: PathBuf, dest: PathBuf, world: PathBuf }, + /// A mod-made world backup, unpacked into `dest` after clearing `old`. + World { file: PathBuf, dest: PathBuf, old: PathBuf }, +} + /// Restores a backup. Minecraft must be stopped. Whole server backups replace the pack files -/// and worlds; mod backups replace only the world they contain. +/// and worlds; mod backups replace only the world they contain. Errors from the checks that run +/// before anything is deleted come back as [`Refused`]. pub fn restore(server: &Path, id: &str) -> Result<()> { + let plan = plan(server, id).map_err(|e| anyhow::Error::new(Refused(format!("{e:#}"))))?; + apply(server, plan) +} + +/// The server token's folder, refused if it is a link: the token is only ever written into a real +/// folder inside the server. +fn refuse_link(dest: &Path, token: &Path) -> Result<()> { + let dir = dest.join(token.parent().unwrap_or(token)); + if fs::symlink_metadata(&dir).is_ok_and(|m| m.file_type().is_symlink()) { + bail!("{} is a link; not restoring the server token through it", dir.display()); + } + Ok(()) +} + +fn plan(server: &Path, id: &str) -> Result { let b = find(server, id)?; let file = server.join(&b.id); if b.full { - // Everything that can refuse runs first: a refused restore must leave the server as it was. // Canonical like `Archive::unpack`, which also gives Windows its long path prefix. let dest = server.canonicalize()?; let world = world_dir(server)?; let tokens = check_full_archive(&file)?; - // The token is only ever written into a real folder inside the server, never through a link. - let refuse_link = |rel: &Path| -> Result<()> { - let dir = dest.join(rel.parent().unwrap_or(rel)); - if fs::symlink_metadata(&dir).is_ok_and(|m| m.file_type().is_symlink()) { - bail!("{} is a link; not restoring the server token through it", dir.display()); - } - Ok(()) - }; - refuse_link(Path::new(".beacon/server.json"))?; - for rel in &tokens { - refuse_link(rel)?; - } - // Chunks generated after the backup would otherwise survive, so a world that can't be - // cleared stops the restore. - clear(&world)?; - if let Some(tree) = srv::applied_tree(server) { - for p in tree.files.keys() { - fs::remove_file(server.join(p)).ok(); - } - } - let mut archive = tar::Archive::new(flate2::read::GzDecoder::new(fs::File::open(file)?)); - for entry in archive.entries()? { - let mut entry = entry?; - // The server token goes back owner-only from the start, never through a default mode, - // and only into the server's own `.beacon` folder. - if let Some(rel) = server_config_entry(&entry.path()?) { - // Checked again right before writing, in case the archive itself created the link. - refuse_link(&rel)?; - let mut bytes = vec![]; - entry.read_to_end(&mut bytes)?; - beacon_core::store::write_private(&dest.join(rel), &bytes)?; - } else { - entry.unpack_in(&dest)?; - } + refuse_link(&dest, Path::new(".beacon/server.json"))?; + for t in &tokens { + refuse_link(&dest, t)?; } - return Ok(()); + return Ok(Plan::Full { file, dest, world }); } let name = b.id.to_ascii_lowercase(); if name.contains("incremental") || name.contains("differential") { @@ -361,9 +365,42 @@ pub fn restore(server: &Path, id: &str) -> Result<()> { } else { bail!("{} doesn't look like a world backup (no level.dat)", b.note); }; + Ok(Plan::World { file, dest, old }) +} + +fn apply(server: &Path, plan: Plan) -> Result<()> { + let (file, dest, old) = match plan { + Plan::World { file, dest, old } => (file, dest, old), + Plan::Full { file, dest, world } => { + // Chunks generated after the backup would otherwise survive, so a world that can't be + // cleared stops the restore. + clear(&world)?; + if let Some(tree) = srv::applied_tree(server) { + for p in tree.files.keys() { + fs::remove_file(server.join(p)).ok(); + } + } + let mut archive = tar::Archive::new(flate2::read::GzDecoder::new(fs::File::open(file)?)); + for entry in archive.entries()? { + let mut entry = entry?; + // The server token goes back owner-only from the start, never through a default + // mode, and only into the server's own `.beacon` folder. + if let Some(rel) = server_config_entry(&entry.path()?) { + // Checked again right before writing, in case the archive created the link. + refuse_link(&dest, &rel)?; + let mut bytes = vec![]; + entry.read_to_end(&mut bytes)?; + beacon_core::store::write_private(&dest.join(rel), &bytes)?; + } else { + entry.unpack_in(&dest)?; + } + } + return Ok(()); + } + }; clear(&old)?; fs::create_dir_all(&dest)?; - if b.id.to_ascii_lowercase().ends_with(".zip") { + if file.to_string_lossy().to_ascii_lowercase().ends_with(".zip") { zip::ZipArchive::new(fs::File::open(&file)?)?.extract(&dest)?; } else { tar::Archive::new(flate2::read::GzDecoder::new(fs::File::open(&file)?)).unpack(&dest)?; @@ -381,6 +418,11 @@ fn check_full_archive(file: &Path) -> Result> { for entry in tar.entries()? { let entry = entry?; let path = entry.path()?; + // BeaconSync writes relative paths only; tar would strip a root or drive and land these + // somewhere the checks below don't look. + if path.components().any(|c| matches!(c, Component::RootDir | Component::Prefix(_) | Component::ParentDir)) { + bail!("the backup has an unexpected path {}", path.display()); + } let kind = entry.header().entry_type(); if (kind.is_symlink() || kind.is_hard_link()) && server_config_entry(&path.join("server.json")).is_some() { bail!("the backup links {}; not restoring the server token through it", path.display()); @@ -461,7 +503,8 @@ mod tests { let bytes = fs::read(d.join(&good.id)).unwrap(); fs::write(own.join("1-truncated.tar.gz"), &bytes[..bytes.len() / 2]).unwrap(); assert!(find(&d, ".beacon/backups/1-truncated.tar.gz").unwrap().full); - assert!(restore(&d, ".beacon/backups/1-truncated.tar.gz").is_err()); + let err = restore(&d, ".beacon/backups/1-truncated.tar.gz").unwrap_err(); + assert!(err.downcast_ref::().is_some(), "refused up front, nothing to undo: {err:#}"); // Only the gzip footer missing, or one flipped byte: tar alone would read these fine. fs::write(own.join("1-footerless.tar.gz"), &bytes[..bytes.len() - 8]).unwrap(); assert!(restore(&d, ".beacon/backups/1-footerless.tar.gz").is_err()); @@ -493,6 +536,22 @@ mod tests { assert!(err.contains("links"), "{err}"); assert!(!outside.join("server.json").exists()); assert_eq!(fs::read_to_string(d.join("world/level.dat")).unwrap(), "old", "refused before deleting"); + // The same link spelled with a root (`/.beacon`), which tar would strip on unpack. + let mut tar = tar::Builder::new(flate2::write::GzEncoder::new( + fs::File::create(own.join("3-rooted.tar.gz")).unwrap(), + flate2::Compression::fast(), + )); + let mut link = tar::Header::new_gnu(); + link.as_gnu_mut().unwrap().name[..8].copy_from_slice(b"/.beacon"); + link.set_entry_type(tar::EntryType::Symlink); + link.set_link_name(&outside).unwrap(); + link.set_size(0); + link.set_cksum(); + tar.append(&link, std::io::empty()).unwrap(); + tar.into_inner().unwrap().finish().unwrap(); + let err = restore(&d, ".beacon/backups/3-rooted.tar.gz").unwrap_err(); + assert!(err.downcast_ref::().is_some() && err.to_string().contains("unexpected path"), "{err:#}"); + assert_eq!(fs::read_to_string(d.join("world/level.dat")).unwrap(), "old"); fs::remove_dir_all(outside).ok(); } fs::remove_dir_all(d).ok(); diff --git a/crates/cli/src/server.rs b/crates/cli/src/server.rs index d28c703..d036444 100644 --- a/crates/cli/src/server.rs +++ b/crates/cli/src/server.rs @@ -1332,7 +1332,10 @@ async fn act(dir: &Path, cfg: &mut ServerConfig, agent: &Option, mc: &mut O say("taking a safety backup first"); let safety = backups::create(&d, "before restore")?; if let Err(e) = backups::restore(&d, &id) { - backups::restore(&d, &safety.id)?; + // Refused up front means nothing changed, so there is nothing to undo. + if e.downcast_ref::().is_none() { + backups::restore(&d, &safety.id)?; + } return Err(e); } backups::prune(&d); From cbd3972b627f4b155a021e194d06c679348f8f9b Mon Sep 17 00:00:00 2001 From: RealDoc06 <73218979+RealDoc06@users.noreply.github.com> Date: Thu, 19 Nov 2026 05:50:22 +0100 Subject: [PATCH 25/33] fix(cli): the agent checks a restore before stopping Minecraft backups::plan runs every restore check without changing anything, so the agent runs it first: a refused restore no longer stops the server or writes an unpruned safety backup. backups::apply carries the plan out after shutdown and the safety backup, and a failed rollback keeps the original error. --- crates/cli/src/backups.rs | 55 +++++++++++++++++++-------------------- crates/cli/src/server.rs | 13 ++++----- 2 files changed, 34 insertions(+), 34 deletions(-) diff --git a/crates/cli/src/backups.rs b/crates/cli/src/backups.rs index 79eeb30..bf8b8b6 100644 --- a/crates/cli/src/backups.rs +++ b/crates/cli/src/backups.rs @@ -299,32 +299,29 @@ fn clear(dir: &Path) -> Result<()> { } } -/// A restore error raised before any file changed: there is nothing to undo. -#[derive(Debug)] -pub struct Refused(String); - -impl std::fmt::Display for Refused { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.write_str(&self.0) - } +/// A restore worked out by [`plan`], every check passed, before anything is deleted. +pub struct Plan { + id: String, + kind: PlanKind, } -impl std::error::Error for Refused {} - -/// What a restore will do, worked out (and every check passed) before anything is deleted. -enum Plan { +enum PlanKind { /// A whole server backup: `dest` is the canonical server folder. Full { file: PathBuf, dest: PathBuf, world: PathBuf }, /// A mod-made world backup, unpacked into `dest` after clearing `old`. World { file: PathBuf, dest: PathBuf, old: PathBuf }, } -/// Restores a backup. Minecraft must be stopped. Whole server backups replace the pack files -/// and worlds; mod backups replace only the world they contain. Errors from the checks that run -/// before anything is deleted come back as [`Refused`]. +impl Plan { + pub fn id(&self) -> &str { + &self.id + } +} + +/// Restores a backup: [`plan`], then [`apply`]. Minecraft must be stopped. Whole server backups +/// replace the pack files and worlds; mod backups replace only the world they contain. pub fn restore(server: &Path, id: &str) -> Result<()> { - let plan = plan(server, id).map_err(|e| anyhow::Error::new(Refused(format!("{e:#}"))))?; - apply(server, plan) + apply(server, plan(server, id)?) } /// The server token's folder, refused if it is a link: the token is only ever written into a real @@ -337,7 +334,9 @@ fn refuse_link(dest: &Path, token: &Path) -> Result<()> { Ok(()) } -fn plan(server: &Path, id: &str) -> Result { +/// Every check a restore makes, without changing anything: safe to run while Minecraft is up, so +/// a bad backup is refused before the server is stopped or a safety backup is taken. +pub fn plan(server: &Path, id: &str) -> Result { let b = find(server, id)?; let file = server.join(&b.id); if b.full { @@ -349,7 +348,7 @@ fn plan(server: &Path, id: &str) -> Result { for t in &tokens { refuse_link(&dest, t)?; } - return Ok(Plan::Full { file, dest, world }); + return Ok(Plan { id: b.id, kind: PlanKind::Full { file, dest, world } }); } let name = b.id.to_ascii_lowercase(); if name.contains("incremental") || name.contains("differential") { @@ -365,13 +364,14 @@ fn plan(server: &Path, id: &str) -> Result { } else { bail!("{} doesn't look like a world backup (no level.dat)", b.note); }; - Ok(Plan::World { file, dest, old }) + Ok(Plan { id: b.id, kind: PlanKind::World { file, dest, old } }) } -fn apply(server: &Path, plan: Plan) -> Result<()> { - let (file, dest, old) = match plan { - Plan::World { file, dest, old } => (file, dest, old), - Plan::Full { file, dest, world } => { +/// Carries out a [`plan`]. Minecraft must be stopped. +pub fn apply(server: &Path, plan: Plan) -> Result<()> { + let (file, dest, old) = match plan.kind { + PlanKind::World { file, dest, old } => (file, dest, old), + PlanKind::Full { file, dest, world } => { // Chunks generated after the backup would otherwise survive, so a world that can't be // cleared stops the restore. clear(&world)?; @@ -503,8 +503,7 @@ mod tests { let bytes = fs::read(d.join(&good.id)).unwrap(); fs::write(own.join("1-truncated.tar.gz"), &bytes[..bytes.len() / 2]).unwrap(); assert!(find(&d, ".beacon/backups/1-truncated.tar.gz").unwrap().full); - let err = restore(&d, ".beacon/backups/1-truncated.tar.gz").unwrap_err(); - assert!(err.downcast_ref::().is_some(), "refused up front, nothing to undo: {err:#}"); + assert!(plan(&d, ".beacon/backups/1-truncated.tar.gz").is_err(), "refused by the checks alone"); // Only the gzip footer missing, or one flipped byte: tar alone would read these fine. fs::write(own.join("1-footerless.tar.gz"), &bytes[..bytes.len() - 8]).unwrap(); assert!(restore(&d, ".beacon/backups/1-footerless.tar.gz").is_err()); @@ -549,8 +548,8 @@ mod tests { link.set_cksum(); tar.append(&link, std::io::empty()).unwrap(); tar.into_inner().unwrap().finish().unwrap(); - let err = restore(&d, ".beacon/backups/3-rooted.tar.gz").unwrap_err(); - assert!(err.downcast_ref::().is_some() && err.to_string().contains("unexpected path"), "{err:#}"); + let err = plan(&d, ".beacon/backups/3-rooted.tar.gz").err().unwrap().to_string(); + assert!(err.contains("unexpected path"), "{err}"); assert_eq!(fs::read_to_string(d.join("world/level.dat")).unwrap(), "old"); fs::remove_dir_all(outside).ok(); } diff --git a/crates/cli/src/server.rs b/crates/cli/src/server.rs index d036444..db9e00c 100644 --- a/crates/cli/src/server.rs +++ b/crates/cli/src/server.rs @@ -1320,7 +1320,11 @@ async fn act(dir: &Path, cfg: &mut ServerConfig, agent: &Option, mc: &mut O say(format!("backup done: {} ({})", b.id, size(b.size))); } ServerAction::Restore(id) => { - say(format!("restoring {id}")); + // Checked while Minecraft still runs: a refused restore stops nothing, takes no safety + // backup and changes nothing. + let d = dir.to_path_buf(); + let plan = tokio::task::spawn_blocking(move || backups::plan(&d, &id)).await??; + say(format!("restoring {}", plan.id())); if let Some(mut m) = mc.take() { m.send("say [BeaconSync] Restoring a backup, back in a minute").await; tokio::time::sleep(Duration::from_secs(3)).await; @@ -1331,11 +1335,8 @@ async fn act(dir: &Path, cfg: &mut ServerConfig, agent: &Option, mc: &mut O let restored = tokio::task::spawn_blocking(move || -> Result<()> { say("taking a safety backup first"); let safety = backups::create(&d, "before restore")?; - if let Err(e) = backups::restore(&d, &id) { - // Refused up front means nothing changed, so there is nothing to undo. - if e.downcast_ref::().is_none() { - backups::restore(&d, &safety.id)?; - } + if let Err(e) = backups::apply(&d, plan) { + backups::restore(&d, &safety.id).with_context(|| format!("{e:#}; undoing it failed too"))?; return Err(e); } backups::prune(&d); From 2693a097ac246012f3d224378d42ec7b40b76e30 Mon Sep 17 00:00:00 2001 From: RealDoc06 <73218979+RealDoc06@users.noreply.github.com> Date: Thu, 19 Nov 2026 05:54:00 +0100 Subject: [PATCH 26/33] fix(cli): restore the archive that was checked, and never lose a world named like a backup The plan keeps the archive open from the checks to extraction, so a backup mod deleting or replacing the file during shutdown can't change what is restored. Backups normalize level-name like restore does, so a world such as backup-world/ is backed up instead of skipped as a mod backup folder. If undoing a failed restore also fails, Minecraft stays stopped instead of starting a fresh world. --- crates/cli/src/backups.rs | 54 +++++++++++++++++++++++++++++---------- crates/cli/src/server.rs | 16 ++++++++---- 2 files changed, 51 insertions(+), 19 deletions(-) diff --git a/crates/cli/src/backups.rs b/crates/cli/src/backups.rs index bf8b8b6..85d5f70 100644 --- a/crates/cli/src/backups.rs +++ b/crates/cli/src/backups.rs @@ -190,7 +190,10 @@ pub fn create(server: &Path, note: &str) -> Result { let written = (|| -> Result<()> { let mut tar = tar::Builder::new(enc); tar.follow_symlinks(false); + // Normalized like restore's `world_dir` (`world/` is `world`), so the world restore + // clears is always one the backup kept, even when its name contains "backup". let world = level_name(server); + let world = one_folder(&world).map_or_else(|| world.clone(), |w| w.to_string_lossy().into_owned()); let walk = walkdir::WalkDir::new(server).min_depth(1).into_iter(); for e in walk.filter_entry(|e| !skip(server, &world, e.path().strip_prefix(server).unwrap_or(e.path()))) { let e = e?; @@ -302,14 +305,17 @@ fn clear(dir: &Path) -> Result<()> { /// A restore worked out by [`plan`], every check passed, before anything is deleted. pub struct Plan { id: String, + /// Opened before the checks and extracted from in [`apply`], so the archive that was checked + /// is the one restored even if a backup mod deletes or replaces the file in between. + archive: fs::File, kind: PlanKind, } enum PlanKind { /// A whole server backup: `dest` is the canonical server folder. - Full { file: PathBuf, dest: PathBuf, world: PathBuf }, + Full { dest: PathBuf, world: PathBuf }, /// A mod-made world backup, unpacked into `dest` after clearing `old`. - World { file: PathBuf, dest: PathBuf, old: PathBuf }, + World { zip: bool, dest: PathBuf, old: PathBuf }, } impl Plan { @@ -339,16 +345,17 @@ fn refuse_link(dest: &Path, token: &Path) -> Result<()> { pub fn plan(server: &Path, id: &str) -> Result { let b = find(server, id)?; let file = server.join(&b.id); + let archive = fs::File::open(&file)?; if b.full { // Canonical like `Archive::unpack`, which also gives Windows its long path prefix. let dest = server.canonicalize()?; let world = world_dir(server)?; - let tokens = check_full_archive(&file)?; + let tokens = check_full_archive(archive.try_clone()?)?; refuse_link(&dest, Path::new(".beacon/server.json"))?; for t in &tokens { refuse_link(&dest, t)?; } - return Ok(Plan { id: b.id, kind: PlanKind::Full { file, dest, world } }); + return Ok(Plan { id: b.id, archive, kind: PlanKind::Full { dest, world } }); } let name = b.id.to_ascii_lowercase(); if name.contains("incremental") || name.contains("differential") { @@ -364,14 +371,19 @@ pub fn plan(server: &Path, id: &str) -> Result { } else { bail!("{} doesn't look like a world backup (no level.dat)", b.note); }; - Ok(Plan { id: b.id, kind: PlanKind::World { file, dest, old } }) + let zip = file.to_string_lossy().to_ascii_lowercase().ends_with(".zip"); + Ok(Plan { id: b.id, archive, kind: PlanKind::World { zip, dest, old } }) } /// Carries out a [`plan`]. Minecraft must be stopped. pub fn apply(server: &Path, plan: Plan) -> Result<()> { - let (file, dest, old) = match plan.kind { - PlanKind::World { file, dest, old } => (file, dest, old), - PlanKind::Full { file, dest, world } => { + use std::io::{Seek, SeekFrom}; + let mut archive = plan.archive; + // The checks read through a clone of this handle, which shares its position. + archive.seek(SeekFrom::Start(0))?; + let (zip, dest, old) = match plan.kind { + PlanKind::World { zip, dest, old } => (zip, dest, old), + PlanKind::Full { dest, world } => { // Chunks generated after the backup would otherwise survive, so a world that can't be // cleared stops the restore. clear(&world)?; @@ -380,7 +392,7 @@ pub fn apply(server: &Path, plan: Plan) -> Result<()> { fs::remove_file(server.join(p)).ok(); } } - let mut archive = tar::Archive::new(flate2::read::GzDecoder::new(fs::File::open(file)?)); + let mut archive = tar::Archive::new(flate2::read::GzDecoder::new(archive)); for entry in archive.entries()? { let mut entry = entry?; // The server token goes back owner-only from the start, never through a default @@ -400,10 +412,10 @@ pub fn apply(server: &Path, plan: Plan) -> Result<()> { }; clear(&old)?; fs::create_dir_all(&dest)?; - if file.to_string_lossy().to_ascii_lowercase().ends_with(".zip") { - zip::ZipArchive::new(fs::File::open(&file)?)?.extract(&dest)?; + if zip { + zip::ZipArchive::new(archive)?.extract(&dest)?; } else { - tar::Archive::new(flate2::read::GzDecoder::new(fs::File::open(&file)?)).unpack(&dest)?; + tar::Archive::new(flate2::read::GzDecoder::new(archive)).unpack(&dest)?; } Ok(()) } @@ -412,8 +424,8 @@ pub fn apply(server: &Path, plan: Plan) -> Result<()> { /// token entries. Refuses a truncated or corrupted backup (every entry, then the rest of the gzip /// stream so its checksum is checked: tar stops at its end marker) and a link entry where the /// token's folder would be. -fn check_full_archive(file: &Path) -> Result> { - let mut tar = tar::Archive::new(flate2::read::GzDecoder::new(fs::File::open(file)?)); +fn check_full_archive(file: fs::File) -> Result> { + let mut tar = tar::Archive::new(flate2::read::GzDecoder::new(file)); let mut tokens = vec![]; for entry in tar.entries()? { let entry = entry?; @@ -494,6 +506,20 @@ mod tests { fs::remove_dir_all(d).ok(); } + #[test] + fn a_world_named_like_a_backup_folder_is_still_backed_up() { + let d = server(); + fs::create_dir_all(d.join("backup-world")).unwrap(); + fs::write(d.join("backup-world/level.dat"), "mine").unwrap(); + fs::write(d.join("server.properties"), "level-name=backup-world/\n").unwrap(); + let b = create(&d, "x").unwrap(); + assert!(archive_entries(&d.join(&b.id)).unwrap().iter().any(|e| e == "backup-world/level.dat")); + fs::write(d.join("backup-world/level.dat"), "newer").unwrap(); + restore(&d, &b.id).unwrap(); + assert_eq!(fs::read_to_string(d.join("backup-world/level.dat")).unwrap(), "mine"); + fs::remove_dir_all(d).ok(); + } + #[test] fn broken_or_linking_full_backups_are_refused() { let d = server(); diff --git a/crates/cli/src/server.rs b/crates/cli/src/server.rs index db9e00c..960d2a0 100644 --- a/crates/cli/src/server.rs +++ b/crates/cli/src/server.rs @@ -1332,17 +1332,23 @@ async fn act(dir: &Path, cfg: &mut ServerConfig, agent: &Option, mc: &mut O } let before = cfg.commit.clone(); let d = dir.to_path_buf(); - let restored = tokio::task::spawn_blocking(move || -> Result<()> { + // Outer error: the restore failed and so did undoing it. Minecraft stays stopped then, + // so it can't start a fresh world over the cleared one. Inner error: the server is as + // it was before the restore, so Minecraft starts again. + let restored = tokio::task::spawn_blocking(move || -> Result> { say("taking a safety backup first"); - let safety = backups::create(&d, "before restore")?; + let safety = match backups::create(&d, "before restore") { + Ok(s) => s, + Err(e) => return Ok(Err(e)), + }; if let Err(e) = backups::apply(&d, plan) { backups::restore(&d, &safety.id).with_context(|| format!("{e:#}; undoing it failed too"))?; - return Err(e); + return Ok(Err(e)); } backups::prune(&d); - Ok(()) + Ok(Ok(())) }) - .await?; + .await??; *cfg = ServerConfig::load(dir)?; *mc = Some(Mc::start(dir, cfg)?); restored?; From 2d36d3ee9c2b8942c828395f4067d8d16eedf447 Mon Sep 17 00:00:00 2001 From: RealDoc06 <73218979+RealDoc06@users.noreply.github.com> Date: Thu, 19 Nov 2026 05:57:48 +0100 Subject: [PATCH 27/33] fix(cli): nested world folders restore again, and deploys check their way back first level-name may be a nested relative path (worlds/survival) as before this PR; only .., roots and drives are refused. Mod backup layouts are read from the kept archive handle. A deploy plans the restore of its safety backup before changing the pack, and rolls back with that plan. --- crates/cli/src/backups.rs | 56 ++++++++++++++++++++++++++++----------- crates/cli/src/server.rs | 6 +++-- 2 files changed, 44 insertions(+), 18 deletions(-) diff --git a/crates/cli/src/backups.rs b/crates/cli/src/backups.rs index 85d5f70..b75d409 100644 --- a/crates/cli/src/backups.rs +++ b/crates/cli/src/backups.rs @@ -148,7 +148,7 @@ fn find(server: &Path, id: &str) -> Result { /// Left out of BeaconSync backups: caches, logs, other backups (and their retention rule) and /// files being written. -/// `world` is the world folder, always kept even if its name contains "backup". +/// `world` is the world's top folder, always kept even if its name contains "backup". fn skip(server: &Path, world: &str, rel: &Path) -> bool { // Forward slashes on every OS, so the prefixes below also match Windows paths. let s = rel.to_string_lossy().replace('\\', "/"); @@ -190,10 +190,13 @@ pub fn create(server: &Path, note: &str) -> Result { let written = (|| -> Result<()> { let mut tar = tar::Builder::new(enc); tar.follow_symlinks(false); - // Normalized like restore's `world_dir` (`world/` is `world`), so the world restore - // clears is always one the backup kept, even when its name contains "backup". + // The world's top folder, normalized like restore's `world_dir` (`world/` is `world`), + // so the world restore clears is always one the backup kept, even when its name + // contains "backup". let world = level_name(server); - let world = one_folder(&world).map_or_else(|| world.clone(), |w| w.to_string_lossy().into_owned()); + let world = world_rel(&world) + .and_then(|w| w.components().next().map(|c| c.as_os_str().to_string_lossy().into_owned())) + .unwrap_or(world); let walk = walkdir::WalkDir::new(server).min_depth(1).into_iter(); for e in walk.filter_entry(|e| !skip(server, &world, e.path().strip_prefix(server).unwrap_or(e.path()))) { let e = e?; @@ -270,12 +273,26 @@ fn one_folder(name: &str) -> Option<&std::ffi::OsStr> { } } -/// The world folder a restore clears, refused unless it sits directly inside the server. +/// `level-name` as a relative path of plain folder names (`world`, `worlds/survival`), rebuilt +/// from its parts so `world/` is `world`. `None` for `..`, `.`, a root or a drive: the world must +/// sit inside the server. +fn world_rel(name: &str) -> Option { + let mut out = PathBuf::new(); + for part in Path::new(name).components() { + match part { + Component::Normal(p) => out.push(p), + _ => return None, + } + } + (!out.as_os_str().is_empty()).then_some(out) +} + +/// The world folder a restore clears, refused unless it sits inside the server. fn world_dir(server: &Path) -> Result { let name = level_name(server); - let part = - one_folder(&name).with_context(|| format!("level-name {name:?} in server.properties isn't a plain folder name"))?; - Ok(server.join(part)) + let rel = + world_rel(&name).with_context(|| format!("level-name {name:?} in server.properties isn't a folder inside the server"))?; + Ok(server.join(rel)) } /// The archive path, without `./` parts, when it names `.beacon/server.json` (the server's config, @@ -361,7 +378,9 @@ pub fn plan(server: &Path, id: &str) -> Result { if name.contains("incremental") || name.contains("differential") { bail!("{} only holds changes since an earlier backup; restore it from {} itself", b.note, b.source); } - let entries = archive_entries(&file)?; + let zip = file.to_string_lossy().to_ascii_lowercase().ends_with(".zip"); + // Read through the kept handle, so the layout checked is the layout extracted. + let entries = archive_entries(archive.try_clone()?, zip)?; // Either the world's files at the root, or one folder holding them. let (dest, old) = if entries.iter().any(|e| e == "level.dat") { let world = world_dir(server)?; @@ -371,7 +390,6 @@ pub fn plan(server: &Path, id: &str) -> Result { } else { bail!("{} doesn't look like a world backup (no level.dat)", b.note); }; - let zip = file.to_string_lossy().to_ascii_lowercase().ends_with(".zip"); Ok(Plan { id: b.id, archive, kind: PlanKind::World { zip, dest, old } }) } @@ -445,15 +463,15 @@ fn check_full_archive(file: fs::File) -> Result> { Ok(tokens) } -fn archive_entries(file: &Path) -> Result> { - if file.to_string_lossy().to_ascii_lowercase().ends_with(".zip") { - let z = zip::ZipArchive::new(fs::File::open(file)?)?; +fn archive_entries(file: fs::File, zip: bool) -> Result> { + if zip { + let z = zip::ZipArchive::new(file)?; return Ok(z .file_names() .map(|n| n.map(|n| n.trim_start_matches("./").to_string())) .collect::>()?); } - let mut tar = tar::Archive::new(flate2::read::GzDecoder::new(fs::File::open(file)?)); + let mut tar = tar::Archive::new(flate2::read::GzDecoder::new(file)); let mut out = vec![]; for e in tar.entries()? { out.push(e?.path()?.to_string_lossy().trim_start_matches("./").to_string()); @@ -465,6 +483,10 @@ fn archive_entries(file: &Path) -> Result> { mod tests { use super::*; + fn entries(tar_gz: &Path) -> Vec { + archive_entries(fs::File::open(tar_gz).unwrap(), false).unwrap() + } + const SERVER_CONFIG: &str = ".beacon/server.json"; use std::io::Write; @@ -513,7 +535,7 @@ mod tests { fs::write(d.join("backup-world/level.dat"), "mine").unwrap(); fs::write(d.join("server.properties"), "level-name=backup-world/\n").unwrap(); let b = create(&d, "x").unwrap(); - assert!(archive_entries(&d.join(&b.id)).unwrap().iter().any(|e| e == "backup-world/level.dat")); + assert!(entries(&d.join(&b.id)).iter().any(|e| e == "backup-world/level.dat")); fs::write(d.join("backup-world/level.dat"), "newer").unwrap(); restore(&d, &b.id).unwrap(); assert_eq!(fs::read_to_string(d.join("backup-world/level.dat")).unwrap(), "mine"); @@ -599,7 +621,7 @@ mod tests { ); // Our own backups leave mod backups out. let own = create(&d, "manual").unwrap(); - assert!(!archive_entries(&d.join(&own.id)).unwrap().iter().any(|e| e.starts_with("backups/"))); + assert!(!entries(&d.join(&own.id)).iter().any(|e| e.starts_with("backups/"))); restore(&d, &b.id).unwrap(); assert_eq!(fs::read_to_string(d.join("world/level.dat")).unwrap(), "from mod"); assert!(restore(&d, "../etc/passwd").is_err()); @@ -618,6 +640,8 @@ mod tests { assert!(restore(&d, &own.id).is_err()); assert!(d.join("world/level.dat").exists() && d.join("mods/pack.jar").exists(), "a refused restore deletes nothing"); assert_eq!(one_folder("world/"), Some(std::ffi::OsStr::new("world"))); + assert_eq!(world_rel("worlds/survival/"), Some(PathBuf::from("worlds/survival"))); + assert_eq!(world_rel("../x").or(world_rel("/abs")).or(world_rel(".")), None); assert_eq!(server_config_entry(Path::new("./.Beacon/Server.json")), Some(PathBuf::from(".Beacon/Server.json"))); assert_eq!(server_config_entry(Path::new("x/.beacon/server.json")), None); fs::write(d.join("server.properties"), "level-name=world\n").unwrap(); diff --git a/crates/cli/src/server.rs b/crates/cli/src/server.rs index 960d2a0..a819978 100644 --- a/crates/cli/src/server.rs +++ b/crates/cli/src/server.rs @@ -1473,7 +1473,9 @@ async fn apply_with_backup( ) -> Result<()> { say("backing up"); let (d, note) = (dir.to_path_buf(), format!("before {}", t.release_name)); - let backup = tokio::task::spawn_blocking(move || backups::create(&d, ¬e)).await??; + // The way back is checked before the pack changes: if the safety backup couldn't be restored, + // the deploy stops here with nothing touched. + let undo = tokio::task::spawn_blocking(move || backups::create(&d, ¬e).and_then(|b| backups::plan(&d, &b.id))).await??; let fetcher = Fetcher::new(Some(store.clone()), Some(hub.base.clone())); let applied: Result<()> = async { srv::apply_tree(dir, tree, &fetcher, &log_progress).await?; @@ -1487,7 +1489,7 @@ async fn apply_with_backup( if let Err(e) = applied { say("restoring the backup"); let d = dir.to_path_buf(); - tokio::task::spawn_blocking(move || backups::restore(&d, &backup.id)).await??; + tokio::task::spawn_blocking(move || backups::apply(&d, undo)).await??; *cfg = ServerConfig::load(dir)?; return Err(e); } From 1f7d49ef947b5355929d186d09cc19394e56f5f3 Mon Sep 17 00:00:00 2001 From: RealDoc06 <73218979+RealDoc06@users.noreply.github.com> Date: Thu, 19 Nov 2026 06:02:24 +0100 Subject: [PATCH 28/33] fix(cli): only clear a world the backup holds, through real folders world_dir refuses a level-name with drive syntax in any part, a world behind a symlinked folder (backups don't follow links), and a world inside a folder backups leave out. A pack file where the world folder would be no longer blocks a rollback. A deploy whose way back is refused prunes its safety backup. --- crates/cli/src/backups.rs | 58 ++++++++++++++++++++++++++++++++++----- crates/cli/src/server.rs | 7 ++++- 2 files changed, 57 insertions(+), 8 deletions(-) diff --git a/crates/cli/src/backups.rs b/crates/cli/src/backups.rs index b75d409..57a2013 100644 --- a/crates/cli/src/backups.rs +++ b/crates/cli/src/backups.rs @@ -274,25 +274,39 @@ fn one_folder(name: &str) -> Option<&std::ffi::OsStr> { } /// `level-name` as a relative path of plain folder names (`world`, `worlds/survival`), rebuilt -/// from its parts so `world/` is `world`. `None` for `..`, `.`, a root or a drive: the world must +/// from its parts so `world/` is `world`. `None` for `..`, `.`, a root or a drive, including a +/// drive inside a later part (`worlds/D:x`, which Windows would join as a drive): the world must /// sit inside the server. fn world_rel(name: &str) -> Option { let mut out = PathBuf::new(); for part in Path::new(name).components() { match part { - Component::Normal(p) => out.push(p), + Component::Normal(p) if !p.to_string_lossy().contains(':') => out.push(p), _ => return None, } } (!out.as_os_str().is_empty()).then_some(out) } -/// The world folder a restore clears, refused unless it sits inside the server. +/// The world folder a restore clears. Refused unless it sits inside the server through real +/// folders (no link along the way, which backups don't follow) and is a folder backups keep, so +/// a restore only ever clears a world its backup holds. fn world_dir(server: &Path) -> Result { let name = level_name(server); let rel = world_rel(&name).with_context(|| format!("level-name {name:?} in server.properties isn't a folder inside the server"))?; - Ok(server.join(rel)) + let top = rel.components().next().map(|c| c.as_os_str().to_string_lossy().into_owned()).unwrap_or_default(); + if skip(server, &top, &rel) { + bail!("level-name {name:?} is inside a folder backups leave out"); + } + let mut dir = server.to_path_buf(); + for part in rel.components() { + dir.push(part); + if fs::symlink_metadata(&dir).is_ok_and(|m| m.file_type().is_symlink()) { + bail!("{} is a link; backups don't follow it, so a restore won't clear the world behind it", dir.display()); + } + } + Ok(dir) } /// The archive path, without `./` parts, when it names `.beacon/server.json` (the server's config, @@ -311,10 +325,12 @@ fn server_config_entry(path: &Path) -> Option { } } -/// Removes a world folder before a restore. Missing is fine; anything else stops the restore. +/// Removes a world folder before a restore. Missing is fine, and so is a file where the folder or +/// one of its parents would be (a pack file the restore removes next); anything else stops it. fn clear(dir: &Path) -> Result<()> { + use std::io::ErrorKind::{NotADirectory, NotFound}; match fs::remove_dir_all(dir) { - Err(e) if e.kind() != std::io::ErrorKind::NotFound => Err(e).with_context(|| format!("clearing {}", dir.display())), + Err(e) if !matches!(e.kind(), NotFound | NotADirectory) => Err(e).with_context(|| format!("clearing {}", dir.display())), _ => Ok(()), } } @@ -542,6 +558,34 @@ mod tests { fs::remove_dir_all(d).ok(); } + #[test] + fn nested_worlds_round_trip_and_unsafe_ones_are_refused() { + let d = server(); + fs::create_dir_all(d.join("worlds/survival")).unwrap(); + fs::write(d.join("worlds/survival/level.dat"), "mine").unwrap(); + fs::write(d.join("server.properties"), "level-name=worlds/survival\n").unwrap(); + let b = create(&d, "x").unwrap(); + fs::write(d.join("worlds/survival/level.dat"), "newer").unwrap(); + restore(&d, &b.id).unwrap(); + assert_eq!(fs::read_to_string(d.join("worlds/survival/level.dat")).unwrap(), "mine"); + // A world inside a folder backups leave out is never cleared. + fs::write(d.join("server.properties"), "level-name=.beacon/backup-world\n").unwrap(); + assert!(plan(&d, &b.id).is_err()); + // Nor one behind a link, which backups don't follow. + #[cfg(unix)] + { + let outside = std::env::temp_dir().join(format!("beacon-linked-{}", rand_suffix())); + fs::create_dir_all(outside.join("survival")).unwrap(); + fs::write(outside.join("survival/level.dat"), "elsewhere").unwrap(); + std::os::unix::fs::symlink(&outside, d.join("linked")).unwrap(); + fs::write(d.join("server.properties"), "level-name=linked/survival\n").unwrap(); + assert!(plan(&d, &b.id).is_err()); + assert!(outside.join("survival/level.dat").exists()); + fs::remove_dir_all(outside).ok(); + } + fs::remove_dir_all(d).ok(); + } + #[test] fn broken_or_linking_full_backups_are_refused() { let d = server(); @@ -641,7 +685,7 @@ mod tests { assert!(d.join("world/level.dat").exists() && d.join("mods/pack.jar").exists(), "a refused restore deletes nothing"); assert_eq!(one_folder("world/"), Some(std::ffi::OsStr::new("world"))); assert_eq!(world_rel("worlds/survival/"), Some(PathBuf::from("worlds/survival"))); - assert_eq!(world_rel("../x").or(world_rel("/abs")).or(world_rel(".")), None); + assert_eq!(world_rel("../x").or(world_rel("/abs")).or(world_rel(".")).or(world_rel("worlds/D:x")), None); assert_eq!(server_config_entry(Path::new("./.Beacon/Server.json")), Some(PathBuf::from(".Beacon/Server.json"))); assert_eq!(server_config_entry(Path::new("x/.beacon/server.json")), None); fs::write(d.join("server.properties"), "level-name=world\n").unwrap(); diff --git a/crates/cli/src/server.rs b/crates/cli/src/server.rs index a819978..87942c3 100644 --- a/crates/cli/src/server.rs +++ b/crates/cli/src/server.rs @@ -1475,7 +1475,12 @@ async fn apply_with_backup( let (d, note) = (dir.to_path_buf(), format!("before {}", t.release_name)); // The way back is checked before the pack changes: if the safety backup couldn't be restored, // the deploy stops here with nothing touched. - let undo = tokio::task::spawn_blocking(move || backups::create(&d, ¬e).and_then(|b| backups::plan(&d, &b.id))).await??; + let undo = tokio::task::spawn_blocking(move || { + let b = backups::create(&d, ¬e)?; + // A refused way back leaves no stray full backup behind each retried deploy. + backups::plan(&d, &b.id).inspect_err(|_| backups::prune(&d)) + }) + .await??; let fetcher = Fetcher::new(Some(store.clone()), Some(hub.base.clone())); let applied: Result<()> = async { srv::apply_tree(dir, tree, &fetcher, &log_progress).await?; From f642fbe5b2e5a4c2b0bcc166049586be67f0ffb1 Mon Sep 17 00:00:00 2001 From: RealDoc06 <73218979+RealDoc06@users.noreply.github.com> Date: Thu, 19 Nov 2026 06:07:21 +0100 Subject: [PATCH 29/33] fix(cli): refuse a full restore only when the archive lacks a world that exists Replaces the link and skipped-folder refusals with one rule: a full restore whose archive holds nothing under the world path is refused if the world on disk has content. Mod backups restore linked worlds again as on main. Clearing empties the world folder but keeps it (mount points). level-name may start with ./, and : is only refused on Windows. Deploys refuse a linked world before stopping Minecraft, and a refused way back deletes only the backup it just took. --- crates/cli/src/backups.rs | 97 +++++++++++++++++++++++++++------------ crates/cli/src/server.rs | 8 +++- 2 files changed, 74 insertions(+), 31 deletions(-) diff --git a/crates/cli/src/backups.rs b/crates/cli/src/backups.rs index 57a2013..373a042 100644 --- a/crates/cli/src/backups.rs +++ b/crates/cli/src/backups.rs @@ -273,40 +273,50 @@ fn one_folder(name: &str) -> Option<&std::ffi::OsStr> { } } -/// `level-name` as a relative path of plain folder names (`world`, `worlds/survival`), rebuilt -/// from its parts so `world/` is `world`. `None` for `..`, `.`, a root or a drive, including a -/// drive inside a later part (`worlds/D:x`, which Windows would join as a drive): the world must -/// sit inside the server. +/// `level-name` as a relative path of plain folder names (`world`, `./worlds/survival/`), +/// rebuilt from its parts. `None` for `..`, a root or a drive (on Windows also a drive inside a +/// later part, `worlds/D:x`, which would join as a drive): the world must sit inside the server. fn world_rel(name: &str) -> Option { let mut out = PathBuf::new(); for part in Path::new(name).components() { match part { - Component::Normal(p) if !p.to_string_lossy().contains(':') => out.push(p), + Component::CurDir => {} + Component::Normal(p) if !(cfg!(windows) && p.to_string_lossy().contains(':')) => out.push(p), _ => return None, } } (!out.as_os_str().is_empty()).then_some(out) } -/// The world folder a restore clears. Refused unless it sits inside the server through real -/// folders (no link along the way, which backups don't follow) and is a folder backups keep, so -/// a restore only ever clears a world its backup holds. +/// The world folder a restore clears, refused unless it sits inside the server. fn world_dir(server: &Path) -> Result { let name = level_name(server); let rel = world_rel(&name).with_context(|| format!("level-name {name:?} in server.properties isn't a folder inside the server"))?; - let top = rel.components().next().map(|c| c.as_os_str().to_string_lossy().into_owned()).unwrap_or_default(); - if skip(server, &top, &rel) { - bail!("level-name {name:?} is inside a folder backups leave out"); + Ok(server.join(rel)) +} + +/// Whether `world` has anything in it to lose: a link (whatever it points at) or a folder with +/// entries. A missing world, or a file where it would be, has nothing. +fn has_content(world: &Path) -> bool { + match fs::symlink_metadata(world) { + Ok(m) if m.file_type().is_symlink() => true, + Ok(m) if m.is_dir() => fs::read_dir(world).is_ok_and(|mut d| d.next().is_some()), + _ => false, } +} + +/// Refuses a deploy up front when its safety backup couldn't hold the world: one behind a link, +/// which backups don't follow. Checked before Minecraft is stopped. +pub fn check_world(server: &Path) -> Result<()> { let mut dir = server.to_path_buf(); - for part in rel.components() { + for part in world_dir(server)?.strip_prefix(server)?.components() { dir.push(part); if fs::symlink_metadata(&dir).is_ok_and(|m| m.file_type().is_symlink()) { - bail!("{} is a link; backups don't follow it, so a restore won't clear the world behind it", dir.display()); + bail!("{} is a link, which backups don't follow; move the world into the server folder", dir.display()); } } - Ok(dir) + Ok(()) } /// The archive path, without `./` parts, when it names `.beacon/server.json` (the server's config, @@ -325,14 +335,29 @@ fn server_config_entry(path: &Path) -> Option { } } -/// Removes a world folder before a restore. Missing is fine, and so is a file where the folder or -/// one of its parents would be (a pack file the restore removes next); anything else stops it. +/// Empties a world folder before a restore, keeping the folder itself (it may be a mount point). +/// A link there is removed, not followed. Missing is fine, and so is a file where the folder or a +/// parent would be (a pack file the restore removes next); anything else stops the restore. fn clear(dir: &Path) -> Result<()> { use std::io::ErrorKind::{NotADirectory, NotFound}; - match fs::remove_dir_all(dir) { - Err(e) if !matches!(e.kind(), NotFound | NotADirectory) => Err(e).with_context(|| format!("clearing {}", dir.display())), - _ => Ok(()), + let ctx = || format!("clearing {}", dir.display()); + let meta = match fs::symlink_metadata(dir) { + Err(e) if matches!(e.kind(), NotFound | NotADirectory) => return Ok(()), + meta => meta.with_context(ctx)?, + }; + if meta.file_type().is_symlink() { + return fs::remove_file(dir).with_context(ctx); + } + if !meta.is_dir() { + return Ok(()); + } + for entry in fs::read_dir(dir).with_context(ctx)? { + let entry = entry.with_context(ctx)?; + let path = entry.path(); + let removed = if entry.file_type()?.is_dir() { fs::remove_dir_all(&path) } else { fs::remove_file(&path) }; + removed.with_context(|| format!("clearing {}", path.display()))?; } + Ok(()) } /// A restore worked out by [`plan`], every check passed, before anything is deleted. @@ -383,7 +408,12 @@ pub fn plan(server: &Path, id: &str) -> Result { // Canonical like `Archive::unpack`, which also gives Windows its long path prefix. let dest = server.canonicalize()?; let world = world_dir(server)?; - let tokens = check_full_archive(archive.try_clone()?)?; + let (tokens, has_world) = check_full_archive(archive.try_clone()?, world.strip_prefix(server)?)?; + // A world the archive doesn't hold (behind a link, in a folder backups skip, spelled + // differently on a case-insensitive disk) would be cleared and never put back. + if !has_world && has_content(&world) { + bail!("this backup doesn't contain the world at {}; restoring it would leave the world empty", world.display()); + } refuse_link(&dest, Path::new(".beacon/server.json"))?; for t in &tokens { refuse_link(&dest, t)?; @@ -455,12 +485,12 @@ pub fn apply(server: &Path, plan: Plan) -> Result<()> { } /// Reads a whole server archive before a restore touches anything, returning the spellings of its -/// token entries. Refuses a truncated or corrupted backup (every entry, then the rest of the gzip +/// token entries and whether it holds anything under `world`. Refuses a truncated or corrupted backup (every entry, then the rest of the gzip /// stream so its checksum is checked: tar stops at its end marker) and a link entry where the /// token's folder would be. -fn check_full_archive(file: fs::File) -> Result> { +fn check_full_archive(file: fs::File, world: &Path) -> Result<(Vec, bool)> { let mut tar = tar::Archive::new(flate2::read::GzDecoder::new(file)); - let mut tokens = vec![]; + let (mut tokens, mut has_world) = (vec![], false); for entry in tar.entries()? { let entry = entry?; let path = entry.path()?; @@ -474,9 +504,10 @@ fn check_full_archive(file: fs::File) -> Result> { bail!("the backup links {}; not restoring the server token through it", path.display()); } tokens.extend(server_config_entry(&path)); + has_world |= path.starts_with(world); } std::io::copy(&mut tar.into_inner(), &mut std::io::sink()).context("the backup is damaged")?; - Ok(tokens) + Ok((tokens, has_world)) } fn archive_entries(file: fs::File, zip: bool) -> Result> { @@ -568,10 +599,15 @@ mod tests { fs::write(d.join("worlds/survival/level.dat"), "newer").unwrap(); restore(&d, &b.id).unwrap(); assert_eq!(fs::read_to_string(d.join("worlds/survival/level.dat")).unwrap(), "mine"); - // A world inside a folder backups leave out is never cleared. + // `./` is fine; a world the backup doesn't hold is never cleared. + fs::write(d.join("server.properties"), "level-name=./worlds/survival\n").unwrap(); + assert!(plan(&d, &b.id).is_ok()); + fs::create_dir_all(d.join(".beacon/backup-world")).unwrap(); + fs::write(d.join(".beacon/backup-world/level.dat"), "skipped").unwrap(); fs::write(d.join("server.properties"), "level-name=.beacon/backup-world\n").unwrap(); - assert!(plan(&d, &b.id).is_err()); - // Nor one behind a link, which backups don't follow. + let skipped = create(&d, "skipped").unwrap(); + assert!(plan(&d, &skipped.id).is_err()); + // Nor one behind a link, which backups don't follow, and deploys say so before stopping. #[cfg(unix)] { let outside = std::env::temp_dir().join(format!("beacon-linked-{}", rand_suffix())); @@ -579,7 +615,9 @@ mod tests { fs::write(outside.join("survival/level.dat"), "elsewhere").unwrap(); std::os::unix::fs::symlink(&outside, d.join("linked")).unwrap(); fs::write(d.join("server.properties"), "level-name=linked/survival\n").unwrap(); - assert!(plan(&d, &b.id).is_err()); + assert!(check_world(&d).is_err()); + let linked = create(&d, "linked").unwrap(); + assert!(plan(&d, &linked.id).is_err()); assert!(outside.join("survival/level.dat").exists()); fs::remove_dir_all(outside).ok(); } @@ -685,7 +723,8 @@ mod tests { assert!(d.join("world/level.dat").exists() && d.join("mods/pack.jar").exists(), "a refused restore deletes nothing"); assert_eq!(one_folder("world/"), Some(std::ffi::OsStr::new("world"))); assert_eq!(world_rel("worlds/survival/"), Some(PathBuf::from("worlds/survival"))); - assert_eq!(world_rel("../x").or(world_rel("/abs")).or(world_rel(".")).or(world_rel("worlds/D:x")), None); + assert_eq!(world_rel("../x").or(world_rel("/abs")).or(world_rel(".")), None); + assert_eq!(world_rel("worlds/D:x").is_none(), cfg!(windows)); assert_eq!(server_config_entry(Path::new("./.Beacon/Server.json")), Some(PathBuf::from(".Beacon/Server.json"))); assert_eq!(server_config_entry(Path::new("x/.beacon/server.json")), None); fs::write(d.join("server.properties"), "level-name=world\n").unwrap(); diff --git a/crates/cli/src/server.rs b/crates/cli/src/server.rs index 87942c3..77017b8 100644 --- a/crates/cli/src/server.rs +++ b/crates/cli/src/server.rs @@ -1441,6 +1441,8 @@ async fn apply_update(dir: &Path, cfg: &mut ServerConfig, store: &ObjectStore, h report(&agent, dep.clone(), "applying", format!("updating to {}", t.release_name), cfg.commit.clone()).await; let result: Result<()> = async { let tree = fetch_tree(hub, store, &t.commit).await?; + // Before announcing or stopping anything: a world the safety backup can't hold stops here. + backups::check_world(dir)?; if let Some(mut m) = mc { m.send(&format!("say [BeaconSync] Updating to {} in 30 seconds", t.release_name)).await; tokio::time::sleep(Duration::from_secs(20)).await; @@ -1477,8 +1479,10 @@ async fn apply_with_backup( // the deploy stops here with nothing touched. let undo = tokio::task::spawn_blocking(move || { let b = backups::create(&d, ¬e)?; - // A refused way back leaves no stray full backup behind each retried deploy. - backups::plan(&d, &b.id).inspect_err(|_| backups::prune(&d)) + // A refused way back removes only the backup just taken, keeping the older ones. + backups::plan(&d, &b.id).inspect_err(|_| { + backups::delete(&d, &b.id).ok(); + }) }) .await??; let fetcher = Fetcher::new(Some(store.clone()), Some(hub.base.clone())); From af921f2b273eccdda44d939511993871a7cc6575 Mon Sep 17 00:00:00 2001 From: RealDoc06 <73218979+RealDoc06@users.noreply.github.com> Date: Thu, 19 Nov 2026 14:21:04 +0100 Subject: [PATCH 30/33] Revert "fix(cli): refuse a full restore only when the archive lacks a world that exists" This reverts commit f642fbe5b2e5a4c2b0bcc166049586be67f0ffb1. --- crates/cli/src/backups.rs | 97 ++++++++++++--------------------------- crates/cli/src/server.rs | 8 +--- 2 files changed, 31 insertions(+), 74 deletions(-) diff --git a/crates/cli/src/backups.rs b/crates/cli/src/backups.rs index 373a042..57a2013 100644 --- a/crates/cli/src/backups.rs +++ b/crates/cli/src/backups.rs @@ -273,50 +273,40 @@ fn one_folder(name: &str) -> Option<&std::ffi::OsStr> { } } -/// `level-name` as a relative path of plain folder names (`world`, `./worlds/survival/`), -/// rebuilt from its parts. `None` for `..`, a root or a drive (on Windows also a drive inside a -/// later part, `worlds/D:x`, which would join as a drive): the world must sit inside the server. +/// `level-name` as a relative path of plain folder names (`world`, `worlds/survival`), rebuilt +/// from its parts so `world/` is `world`. `None` for `..`, `.`, a root or a drive, including a +/// drive inside a later part (`worlds/D:x`, which Windows would join as a drive): the world must +/// sit inside the server. fn world_rel(name: &str) -> Option { let mut out = PathBuf::new(); for part in Path::new(name).components() { match part { - Component::CurDir => {} - Component::Normal(p) if !(cfg!(windows) && p.to_string_lossy().contains(':')) => out.push(p), + Component::Normal(p) if !p.to_string_lossy().contains(':') => out.push(p), _ => return None, } } (!out.as_os_str().is_empty()).then_some(out) } -/// The world folder a restore clears, refused unless it sits inside the server. +/// The world folder a restore clears. Refused unless it sits inside the server through real +/// folders (no link along the way, which backups don't follow) and is a folder backups keep, so +/// a restore only ever clears a world its backup holds. fn world_dir(server: &Path) -> Result { let name = level_name(server); let rel = world_rel(&name).with_context(|| format!("level-name {name:?} in server.properties isn't a folder inside the server"))?; - Ok(server.join(rel)) -} - -/// Whether `world` has anything in it to lose: a link (whatever it points at) or a folder with -/// entries. A missing world, or a file where it would be, has nothing. -fn has_content(world: &Path) -> bool { - match fs::symlink_metadata(world) { - Ok(m) if m.file_type().is_symlink() => true, - Ok(m) if m.is_dir() => fs::read_dir(world).is_ok_and(|mut d| d.next().is_some()), - _ => false, + let top = rel.components().next().map(|c| c.as_os_str().to_string_lossy().into_owned()).unwrap_or_default(); + if skip(server, &top, &rel) { + bail!("level-name {name:?} is inside a folder backups leave out"); } -} - -/// Refuses a deploy up front when its safety backup couldn't hold the world: one behind a link, -/// which backups don't follow. Checked before Minecraft is stopped. -pub fn check_world(server: &Path) -> Result<()> { let mut dir = server.to_path_buf(); - for part in world_dir(server)?.strip_prefix(server)?.components() { + for part in rel.components() { dir.push(part); if fs::symlink_metadata(&dir).is_ok_and(|m| m.file_type().is_symlink()) { - bail!("{} is a link, which backups don't follow; move the world into the server folder", dir.display()); + bail!("{} is a link; backups don't follow it, so a restore won't clear the world behind it", dir.display()); } } - Ok(()) + Ok(dir) } /// The archive path, without `./` parts, when it names `.beacon/server.json` (the server's config, @@ -335,29 +325,14 @@ fn server_config_entry(path: &Path) -> Option { } } -/// Empties a world folder before a restore, keeping the folder itself (it may be a mount point). -/// A link there is removed, not followed. Missing is fine, and so is a file where the folder or a -/// parent would be (a pack file the restore removes next); anything else stops the restore. +/// Removes a world folder before a restore. Missing is fine, and so is a file where the folder or +/// one of its parents would be (a pack file the restore removes next); anything else stops it. fn clear(dir: &Path) -> Result<()> { use std::io::ErrorKind::{NotADirectory, NotFound}; - let ctx = || format!("clearing {}", dir.display()); - let meta = match fs::symlink_metadata(dir) { - Err(e) if matches!(e.kind(), NotFound | NotADirectory) => return Ok(()), - meta => meta.with_context(ctx)?, - }; - if meta.file_type().is_symlink() { - return fs::remove_file(dir).with_context(ctx); - } - if !meta.is_dir() { - return Ok(()); - } - for entry in fs::read_dir(dir).with_context(ctx)? { - let entry = entry.with_context(ctx)?; - let path = entry.path(); - let removed = if entry.file_type()?.is_dir() { fs::remove_dir_all(&path) } else { fs::remove_file(&path) }; - removed.with_context(|| format!("clearing {}", path.display()))?; + match fs::remove_dir_all(dir) { + Err(e) if !matches!(e.kind(), NotFound | NotADirectory) => Err(e).with_context(|| format!("clearing {}", dir.display())), + _ => Ok(()), } - Ok(()) } /// A restore worked out by [`plan`], every check passed, before anything is deleted. @@ -408,12 +383,7 @@ pub fn plan(server: &Path, id: &str) -> Result { // Canonical like `Archive::unpack`, which also gives Windows its long path prefix. let dest = server.canonicalize()?; let world = world_dir(server)?; - let (tokens, has_world) = check_full_archive(archive.try_clone()?, world.strip_prefix(server)?)?; - // A world the archive doesn't hold (behind a link, in a folder backups skip, spelled - // differently on a case-insensitive disk) would be cleared and never put back. - if !has_world && has_content(&world) { - bail!("this backup doesn't contain the world at {}; restoring it would leave the world empty", world.display()); - } + let tokens = check_full_archive(archive.try_clone()?)?; refuse_link(&dest, Path::new(".beacon/server.json"))?; for t in &tokens { refuse_link(&dest, t)?; @@ -485,12 +455,12 @@ pub fn apply(server: &Path, plan: Plan) -> Result<()> { } /// Reads a whole server archive before a restore touches anything, returning the spellings of its -/// token entries and whether it holds anything under `world`. Refuses a truncated or corrupted backup (every entry, then the rest of the gzip +/// token entries. Refuses a truncated or corrupted backup (every entry, then the rest of the gzip /// stream so its checksum is checked: tar stops at its end marker) and a link entry where the /// token's folder would be. -fn check_full_archive(file: fs::File, world: &Path) -> Result<(Vec, bool)> { +fn check_full_archive(file: fs::File) -> Result> { let mut tar = tar::Archive::new(flate2::read::GzDecoder::new(file)); - let (mut tokens, mut has_world) = (vec![], false); + let mut tokens = vec![]; for entry in tar.entries()? { let entry = entry?; let path = entry.path()?; @@ -504,10 +474,9 @@ fn check_full_archive(file: fs::File, world: &Path) -> Result<(Vec, boo bail!("the backup links {}; not restoring the server token through it", path.display()); } tokens.extend(server_config_entry(&path)); - has_world |= path.starts_with(world); } std::io::copy(&mut tar.into_inner(), &mut std::io::sink()).context("the backup is damaged")?; - Ok((tokens, has_world)) + Ok(tokens) } fn archive_entries(file: fs::File, zip: bool) -> Result> { @@ -599,15 +568,10 @@ mod tests { fs::write(d.join("worlds/survival/level.dat"), "newer").unwrap(); restore(&d, &b.id).unwrap(); assert_eq!(fs::read_to_string(d.join("worlds/survival/level.dat")).unwrap(), "mine"); - // `./` is fine; a world the backup doesn't hold is never cleared. - fs::write(d.join("server.properties"), "level-name=./worlds/survival\n").unwrap(); - assert!(plan(&d, &b.id).is_ok()); - fs::create_dir_all(d.join(".beacon/backup-world")).unwrap(); - fs::write(d.join(".beacon/backup-world/level.dat"), "skipped").unwrap(); + // A world inside a folder backups leave out is never cleared. fs::write(d.join("server.properties"), "level-name=.beacon/backup-world\n").unwrap(); - let skipped = create(&d, "skipped").unwrap(); - assert!(plan(&d, &skipped.id).is_err()); - // Nor one behind a link, which backups don't follow, and deploys say so before stopping. + assert!(plan(&d, &b.id).is_err()); + // Nor one behind a link, which backups don't follow. #[cfg(unix)] { let outside = std::env::temp_dir().join(format!("beacon-linked-{}", rand_suffix())); @@ -615,9 +579,7 @@ mod tests { fs::write(outside.join("survival/level.dat"), "elsewhere").unwrap(); std::os::unix::fs::symlink(&outside, d.join("linked")).unwrap(); fs::write(d.join("server.properties"), "level-name=linked/survival\n").unwrap(); - assert!(check_world(&d).is_err()); - let linked = create(&d, "linked").unwrap(); - assert!(plan(&d, &linked.id).is_err()); + assert!(plan(&d, &b.id).is_err()); assert!(outside.join("survival/level.dat").exists()); fs::remove_dir_all(outside).ok(); } @@ -723,8 +685,7 @@ mod tests { assert!(d.join("world/level.dat").exists() && d.join("mods/pack.jar").exists(), "a refused restore deletes nothing"); assert_eq!(one_folder("world/"), Some(std::ffi::OsStr::new("world"))); assert_eq!(world_rel("worlds/survival/"), Some(PathBuf::from("worlds/survival"))); - assert_eq!(world_rel("../x").or(world_rel("/abs")).or(world_rel(".")), None); - assert_eq!(world_rel("worlds/D:x").is_none(), cfg!(windows)); + assert_eq!(world_rel("../x").or(world_rel("/abs")).or(world_rel(".")).or(world_rel("worlds/D:x")), None); assert_eq!(server_config_entry(Path::new("./.Beacon/Server.json")), Some(PathBuf::from(".Beacon/Server.json"))); assert_eq!(server_config_entry(Path::new("x/.beacon/server.json")), None); fs::write(d.join("server.properties"), "level-name=world\n").unwrap(); diff --git a/crates/cli/src/server.rs b/crates/cli/src/server.rs index 77017b8..87942c3 100644 --- a/crates/cli/src/server.rs +++ b/crates/cli/src/server.rs @@ -1441,8 +1441,6 @@ async fn apply_update(dir: &Path, cfg: &mut ServerConfig, store: &ObjectStore, h report(&agent, dep.clone(), "applying", format!("updating to {}", t.release_name), cfg.commit.clone()).await; let result: Result<()> = async { let tree = fetch_tree(hub, store, &t.commit).await?; - // Before announcing or stopping anything: a world the safety backup can't hold stops here. - backups::check_world(dir)?; if let Some(mut m) = mc { m.send(&format!("say [BeaconSync] Updating to {} in 30 seconds", t.release_name)).await; tokio::time::sleep(Duration::from_secs(20)).await; @@ -1479,10 +1477,8 @@ async fn apply_with_backup( // the deploy stops here with nothing touched. let undo = tokio::task::spawn_blocking(move || { let b = backups::create(&d, ¬e)?; - // A refused way back removes only the backup just taken, keeping the older ones. - backups::plan(&d, &b.id).inspect_err(|_| { - backups::delete(&d, &b.id).ok(); - }) + // A refused way back leaves no stray full backup behind each retried deploy. + backups::plan(&d, &b.id).inspect_err(|_| backups::prune(&d)) }) .await??; let fetcher = Fetcher::new(Some(store.clone()), Some(hub.base.clone())); From 782cf3a768798df55f3135723d32196b50efe1bd Mon Sep 17 00:00:00 2001 From: RealDoc06 <73218979+RealDoc06@users.noreply.github.com> Date: Thu, 19 Nov 2026 14:21:04 +0100 Subject: [PATCH 31/33] Revert "fix(cli): only clear a world the backup holds, through real folders" This reverts commit 1f7d49ef947b5355929d186d09cc19394e56f5f3. --- crates/cli/src/backups.rs | 58 +++++---------------------------------- crates/cli/src/server.rs | 7 +---- 2 files changed, 8 insertions(+), 57 deletions(-) diff --git a/crates/cli/src/backups.rs b/crates/cli/src/backups.rs index 57a2013..b75d409 100644 --- a/crates/cli/src/backups.rs +++ b/crates/cli/src/backups.rs @@ -274,39 +274,25 @@ fn one_folder(name: &str) -> Option<&std::ffi::OsStr> { } /// `level-name` as a relative path of plain folder names (`world`, `worlds/survival`), rebuilt -/// from its parts so `world/` is `world`. `None` for `..`, `.`, a root or a drive, including a -/// drive inside a later part (`worlds/D:x`, which Windows would join as a drive): the world must +/// from its parts so `world/` is `world`. `None` for `..`, `.`, a root or a drive: the world must /// sit inside the server. fn world_rel(name: &str) -> Option { let mut out = PathBuf::new(); for part in Path::new(name).components() { match part { - Component::Normal(p) if !p.to_string_lossy().contains(':') => out.push(p), + Component::Normal(p) => out.push(p), _ => return None, } } (!out.as_os_str().is_empty()).then_some(out) } -/// The world folder a restore clears. Refused unless it sits inside the server through real -/// folders (no link along the way, which backups don't follow) and is a folder backups keep, so -/// a restore only ever clears a world its backup holds. +/// The world folder a restore clears, refused unless it sits inside the server. fn world_dir(server: &Path) -> Result { let name = level_name(server); let rel = world_rel(&name).with_context(|| format!("level-name {name:?} in server.properties isn't a folder inside the server"))?; - let top = rel.components().next().map(|c| c.as_os_str().to_string_lossy().into_owned()).unwrap_or_default(); - if skip(server, &top, &rel) { - bail!("level-name {name:?} is inside a folder backups leave out"); - } - let mut dir = server.to_path_buf(); - for part in rel.components() { - dir.push(part); - if fs::symlink_metadata(&dir).is_ok_and(|m| m.file_type().is_symlink()) { - bail!("{} is a link; backups don't follow it, so a restore won't clear the world behind it", dir.display()); - } - } - Ok(dir) + Ok(server.join(rel)) } /// The archive path, without `./` parts, when it names `.beacon/server.json` (the server's config, @@ -325,12 +311,10 @@ fn server_config_entry(path: &Path) -> Option { } } -/// Removes a world folder before a restore. Missing is fine, and so is a file where the folder or -/// one of its parents would be (a pack file the restore removes next); anything else stops it. +/// Removes a world folder before a restore. Missing is fine; anything else stops the restore. fn clear(dir: &Path) -> Result<()> { - use std::io::ErrorKind::{NotADirectory, NotFound}; match fs::remove_dir_all(dir) { - Err(e) if !matches!(e.kind(), NotFound | NotADirectory) => Err(e).with_context(|| format!("clearing {}", dir.display())), + Err(e) if e.kind() != std::io::ErrorKind::NotFound => Err(e).with_context(|| format!("clearing {}", dir.display())), _ => Ok(()), } } @@ -558,34 +542,6 @@ mod tests { fs::remove_dir_all(d).ok(); } - #[test] - fn nested_worlds_round_trip_and_unsafe_ones_are_refused() { - let d = server(); - fs::create_dir_all(d.join("worlds/survival")).unwrap(); - fs::write(d.join("worlds/survival/level.dat"), "mine").unwrap(); - fs::write(d.join("server.properties"), "level-name=worlds/survival\n").unwrap(); - let b = create(&d, "x").unwrap(); - fs::write(d.join("worlds/survival/level.dat"), "newer").unwrap(); - restore(&d, &b.id).unwrap(); - assert_eq!(fs::read_to_string(d.join("worlds/survival/level.dat")).unwrap(), "mine"); - // A world inside a folder backups leave out is never cleared. - fs::write(d.join("server.properties"), "level-name=.beacon/backup-world\n").unwrap(); - assert!(plan(&d, &b.id).is_err()); - // Nor one behind a link, which backups don't follow. - #[cfg(unix)] - { - let outside = std::env::temp_dir().join(format!("beacon-linked-{}", rand_suffix())); - fs::create_dir_all(outside.join("survival")).unwrap(); - fs::write(outside.join("survival/level.dat"), "elsewhere").unwrap(); - std::os::unix::fs::symlink(&outside, d.join("linked")).unwrap(); - fs::write(d.join("server.properties"), "level-name=linked/survival\n").unwrap(); - assert!(plan(&d, &b.id).is_err()); - assert!(outside.join("survival/level.dat").exists()); - fs::remove_dir_all(outside).ok(); - } - fs::remove_dir_all(d).ok(); - } - #[test] fn broken_or_linking_full_backups_are_refused() { let d = server(); @@ -685,7 +641,7 @@ mod tests { assert!(d.join("world/level.dat").exists() && d.join("mods/pack.jar").exists(), "a refused restore deletes nothing"); assert_eq!(one_folder("world/"), Some(std::ffi::OsStr::new("world"))); assert_eq!(world_rel("worlds/survival/"), Some(PathBuf::from("worlds/survival"))); - assert_eq!(world_rel("../x").or(world_rel("/abs")).or(world_rel(".")).or(world_rel("worlds/D:x")), None); + assert_eq!(world_rel("../x").or(world_rel("/abs")).or(world_rel(".")), None); assert_eq!(server_config_entry(Path::new("./.Beacon/Server.json")), Some(PathBuf::from(".Beacon/Server.json"))); assert_eq!(server_config_entry(Path::new("x/.beacon/server.json")), None); fs::write(d.join("server.properties"), "level-name=world\n").unwrap(); diff --git a/crates/cli/src/server.rs b/crates/cli/src/server.rs index 87942c3..a819978 100644 --- a/crates/cli/src/server.rs +++ b/crates/cli/src/server.rs @@ -1475,12 +1475,7 @@ async fn apply_with_backup( let (d, note) = (dir.to_path_buf(), format!("before {}", t.release_name)); // The way back is checked before the pack changes: if the safety backup couldn't be restored, // the deploy stops here with nothing touched. - let undo = tokio::task::spawn_blocking(move || { - let b = backups::create(&d, ¬e)?; - // A refused way back leaves no stray full backup behind each retried deploy. - backups::plan(&d, &b.id).inspect_err(|_| backups::prune(&d)) - }) - .await??; + let undo = tokio::task::spawn_blocking(move || backups::create(&d, ¬e).and_then(|b| backups::plan(&d, &b.id))).await??; let fetcher = Fetcher::new(Some(store.clone()), Some(hub.base.clone())); let applied: Result<()> = async { srv::apply_tree(dir, tree, &fetcher, &log_progress).await?; From 1a6d45f971130ac45451ca4f73a7271ba7f8311c Mon Sep 17 00:00:00 2001 From: RealDoc06 <73218979+RealDoc06@users.noreply.github.com> Date: Thu, 19 Nov 2026 14:21:49 +0100 Subject: [PATCH 32/33] fix(cli): trim the round 12-14 restore guards back to the reviewed core Deploys roll back with restore() again (no pre-plan of the safety backup). Kept: nested level-name support (./ ignored, : refused only on Windows) and mod-backup layouts read from the kept archive handle. --- crates/cli/src/backups.rs | 11 +++++++---- crates/cli/src/server.rs | 6 ++---- 2 files changed, 9 insertions(+), 8 deletions(-) diff --git a/crates/cli/src/backups.rs b/crates/cli/src/backups.rs index b75d409..2c53813 100644 --- a/crates/cli/src/backups.rs +++ b/crates/cli/src/backups.rs @@ -273,14 +273,15 @@ fn one_folder(name: &str) -> Option<&std::ffi::OsStr> { } } -/// `level-name` as a relative path of plain folder names (`world`, `worlds/survival`), rebuilt -/// from its parts so `world/` is `world`. `None` for `..`, `.`, a root or a drive: the world must -/// sit inside the server. +/// `level-name` as a relative path of plain folder names (`world`, `./worlds/survival/`), +/// rebuilt from its parts. `None` for `..`, a root or a drive (on Windows also a drive inside a +/// later part, `worlds/D:x`, which would join as a drive): the world must sit inside the server. fn world_rel(name: &str) -> Option { let mut out = PathBuf::new(); for part in Path::new(name).components() { match part { - Component::Normal(p) => out.push(p), + Component::CurDir => {} + Component::Normal(p) if !(cfg!(windows) && p.to_string_lossy().contains(':')) => out.push(p), _ => return None, } } @@ -642,6 +643,8 @@ mod tests { assert_eq!(one_folder("world/"), Some(std::ffi::OsStr::new("world"))); assert_eq!(world_rel("worlds/survival/"), Some(PathBuf::from("worlds/survival"))); assert_eq!(world_rel("../x").or(world_rel("/abs")).or(world_rel(".")), None); + assert_eq!(world_rel("./worlds/survival"), Some(PathBuf::from("worlds/survival"))); + assert_eq!(world_rel("worlds/D:x").is_none(), cfg!(windows)); assert_eq!(server_config_entry(Path::new("./.Beacon/Server.json")), Some(PathBuf::from(".Beacon/Server.json"))); assert_eq!(server_config_entry(Path::new("x/.beacon/server.json")), None); fs::write(d.join("server.properties"), "level-name=world\n").unwrap(); diff --git a/crates/cli/src/server.rs b/crates/cli/src/server.rs index a819978..960d2a0 100644 --- a/crates/cli/src/server.rs +++ b/crates/cli/src/server.rs @@ -1473,9 +1473,7 @@ async fn apply_with_backup( ) -> Result<()> { say("backing up"); let (d, note) = (dir.to_path_buf(), format!("before {}", t.release_name)); - // The way back is checked before the pack changes: if the safety backup couldn't be restored, - // the deploy stops here with nothing touched. - let undo = tokio::task::spawn_blocking(move || backups::create(&d, ¬e).and_then(|b| backups::plan(&d, &b.id))).await??; + let backup = tokio::task::spawn_blocking(move || backups::create(&d, ¬e)).await??; let fetcher = Fetcher::new(Some(store.clone()), Some(hub.base.clone())); let applied: Result<()> = async { srv::apply_tree(dir, tree, &fetcher, &log_progress).await?; @@ -1489,7 +1487,7 @@ async fn apply_with_backup( if let Err(e) = applied { say("restoring the backup"); let d = dir.to_path_buf(); - tokio::task::spawn_blocking(move || backups::apply(&d, undo)).await??; + tokio::task::spawn_blocking(move || backups::restore(&d, &backup.id)).await??; *cfg = ServerConfig::load(dir)?; return Err(e); } From 1b674e073b227661eca3e998a14674539f5b2149 Mon Sep 17 00:00:00 2001 From: RealDoc06 <73218979+RealDoc06@users.noreply.github.com> Date: Thu, 19 Nov 2026 14:26:11 +0100 Subject: [PATCH 33/33] fix: final council nits Restores without a token entry no longer refuse a linked .beacon folder (as on main), at most 32 sign ins wait for Argon2, register and login are documented separately, and the one_folder comment matches its use. --- crates/cli/src/backups.rs | 7 +++---- crates/hub/src/routes.rs | 2 +- docs/ARCHITECTURE.md | 3 ++- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/crates/cli/src/backups.rs b/crates/cli/src/backups.rs index 2c53813..576706d 100644 --- a/crates/cli/src/backups.rs +++ b/crates/cli/src/backups.rs @@ -262,9 +262,9 @@ fn level_name(server: &Path) -> String { .unwrap_or_else(|| "world".into()) } -/// `name` as one plain folder name, so a restore only ever clears a folder directly inside the -/// server (not `..`, `.`, an absolute path or a nested one). Callers join the returned part, not -/// `name`, so a trailing `/` can't make deletion follow a symlinked folder. +/// `name` as one plain folder name (not `..`, `.`, an absolute path or a nested one): the single +/// top folder of a mod-made backup. Callers join the returned part, not `name`, so a trailing `/` +/// can't make deletion follow a symlinked folder. fn one_folder(name: &str) -> Option<&std::ffi::OsStr> { let mut parts = Path::new(name).components(); match (parts.next(), parts.next()) { @@ -369,7 +369,6 @@ pub fn plan(server: &Path, id: &str) -> Result { let dest = server.canonicalize()?; let world = world_dir(server)?; let tokens = check_full_archive(archive.try_clone()?)?; - refuse_link(&dest, Path::new(".beacon/server.json"))?; for t in &tokens { refuse_link(&dest, t)?; } diff --git a/crates/hub/src/routes.rs b/crates/hub/src/routes.rs index cfe31c5..d2bdfbd 100644 --- a/crates/hub/src/routes.rs +++ b/crates/hub/src/routes.rs @@ -216,7 +216,7 @@ static ARGON: LazyLock> = /// Sign ins and registrations allowed to wait for [`ARGON`] at once; past that the hub answers /// 503 right away instead of holding more requests (and their bodies) in memory. -const MAX_ARGON_WAITING: usize = 256; +const MAX_ARGON_WAITING: usize = 32; static ARGON_WAITING: AtomicUsize = AtomicUsize::new(0); /// A place in the queue for [`ARGON`], taken before anything else is recorded so a busy hub diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 3a7964a..601e16f 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -134,7 +134,8 @@ GET /api/objects/:hash -> raw object bytes (blobs, trees, commits) Authenticated: ``` -POST /api/auth/register|login { username, password } -> { token, user } (429 after 10 wrong passwords for a username, existing or not, within 15 minutes; per account, so it can keep a known username's password sign in locked, but tokens keep working; 503 when too many sign ins are already waiting) +POST /api/auth/register { username, password } -> { token, user } (503 when too many sign ins are already waiting) +POST /api/auth/login { username, password } -> { token, user } (429 after 10 wrong passwords for a username, existing or not, within 15 minutes; per account, so it can keep a known username's password sign in locked, but tokens keep working; 503 when too many sign ins are already waiting) POST /api/auth/device/start -> { device_code, user_code, expires_in } POST /api/auth/device/poll { device_code } -> { token, user } | 428 pending POST /api/auth/device/approve { user_code }