From 9d135765cd6ac87ae3d743f8461f3d2e6ead8920 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=94=D0=BC=D0=B8=D1=82=D1=80=D0=B8=D0=B9?= Date: Thu, 22 Oct 2026 15:34:37 +0500 Subject: [PATCH] feat(multiruleset): complete MR1.1 foundation correctness gate --- crates/coa-control-proto/src/app.rs | 21 +- crates/coa-control-proto/src/lib.rs | 2 +- crates/coa-core/examples/migration_plan.rs | 173 ++- crates/coa-core/examples/upgrade_fixture.rs | 86 +- crates/coa-core/src/backup.rs | 37 +- crates/coa-core/src/channels.rs | 64 +- crates/coa-core/src/client.rs | 75 +- crates/coa-core/src/console.rs | 12 +- crates/coa-core/src/control/service.rs | 28 +- crates/coa-core/src/custom_races.rs | 5 +- crates/coa-core/src/db.rs | 59 +- crates/coa-core/src/diag.rs | 7 +- crates/coa-core/src/docker/lifecycle.rs | 25 +- crates/coa-core/src/docker/logs.rs | 36 +- crates/coa-core/src/docker/sharing.rs | 86 +- crates/coa-core/src/fsx.rs | 37 +- crates/coa-core/src/manifest.rs | 107 +- crates/coa-core/src/migrations.rs | 26 +- crates/coa-core/src/modules.rs | 41 +- crates/coa-core/src/multiworld.rs | 13 +- crates/coa-core/src/mysql_snapshot.rs | 1058 ++++++++++++++--- crates/coa-core/src/portable/compat.rs | 5 +- .../src/portable/migrations/001_init.sql | 2 +- .../portable/migrations/009_multiruleset.sql | 27 +- crates/coa-core/src/portable/model.rs | 33 +- .../src/portable/realm/collections.rs | 20 +- .../src/portable/realm/live_wardrobe.rs | 23 +- crates/coa-core/src/portable/realm/profile.rs | 8 +- .../coa-core/src/portable/service/engine.rs | 11 +- .../src/portable/session/collection_tests.rs | 45 +- crates/coa-core/src/portable/session/host.rs | 16 +- crates/coa-core/src/portable/session/owner.rs | 32 +- .../src/portable/session/projection_tests.rs | 7 +- .../coa-core/src/portable/session/protocol.rs | 167 ++- crates/coa-core/src/portable/store.rs | 2 + crates/coa-core/src/portable/store/owner.rs | 16 +- crates/coa-core/src/portable/store/tests.rs | 188 ++- crates/coa-core/src/realms.rs | 323 ++++- crates/coa-core/src/squid.rs | 81 +- crates/coa-core/src/update.rs | 12 +- crates/coa-core/src/update_isolation.rs | 200 +++- crates/coa-core/src/update_route.rs | 92 +- crates/coa-release/src/main.rs | 95 +- docs/MULTIRULESET_PORTABLE_AUDIT.md | 36 +- docs/REBORN_PORTABLE_AUDIT.md | 19 +- services/coa-control-e2e/Cargo.lock | 10 +- services/coa-control-e2e/tests/control.rs | 12 +- .../coa-control-e2e/tests/live_control.rs | 8 +- src-tauri/src/lib.rs | 2 +- 49 files changed, 2790 insertions(+), 700 deletions(-) diff --git a/crates/coa-control-proto/src/app.rs b/crates/coa-control-proto/src/app.rs index f3e0129..56a114b 100644 --- a/crates/coa-control-proto/src/app.rs +++ b/crates/coa-control-proto/src/app.rs @@ -16,10 +16,6 @@ pub const MIN_PASSWORD: usize = 8; pub const MAX_PASSWORD: usize = 16; pub const MAX_CHARACTERS: usize = 200; -fn default_ruleset() -> String { - "coa".to_string() -} - /// A game account name: 3 to 16 ASCII letters, digits or `_`, not beginning or ending with `_`. pub fn valid_username(s: &str) -> bool { (MIN_USERNAME..=MAX_USERNAME).contains(&s.len()) @@ -107,7 +103,6 @@ pub enum Request { TransferOffer { transfer_id: Uuid, character_id: Uuid, - #[serde(default = "default_ruleset")] ruleset: String, canonical_revision: u64, content_hash: String, @@ -478,5 +473,21 @@ mod tests { }; let resp_dec = decode_response(&encode_response(&resp)).unwrap(); assert_eq!(resp, resp_dec); + + // Control protocol v2 requires ruleset in TransferOffer; missing is rejected + let missing_ruleset_json = serde_json::json!({ + "op": "transfer_offer", + "transfer_id": tid, + "character_id": cid, + "canonical_revision": 5, + "content_hash": hash, + "total_size": 1024, + "collections": {} + }); + let encoded_missing = serde_json::to_vec(&missing_ruleset_json).unwrap(); + assert!( + decode_request(&encoded_missing).is_err(), + "missing ruleset in v2 must be rejected" + ); } } diff --git a/crates/coa-control-proto/src/lib.rs b/crates/coa-control-proto/src/lib.rs index dd3723f..7480a2a 100644 --- a/crates/coa-control-proto/src/lib.rs +++ b/crates/coa-control-proto/src/lib.rs @@ -16,7 +16,7 @@ pub mod coord; pub mod noise; pub mod relay; -pub const CONTROL_PROTOCOL_VERSION: u32 = 1; +pub const CONTROL_PROTOCOL_VERSION: u32 = 2; #[derive(Debug, thiserror::Error, PartialEq, Eq)] pub enum ControlError { diff --git a/crates/coa-core/examples/migration_plan.rs b/crates/coa-core/examples/migration_plan.rs index db5fc57..e73b962 100644 --- a/crates/coa-core/examples/migration_plan.rs +++ b/crates/coa-core/examples/migration_plan.rs @@ -1,57 +1,124 @@ //! Read-only audit, or explicit SQL checks on a disposable database fixture. -use coa_core::{db::{Account, Db}, migrations::{self, Store}, manifest::Manifest, realms::Mode}; +use coa_core::{ + db::{Account, Db}, + manifest::Manifest, + migrations::{self, Store}, + realms::Mode, +}; fn main() -> Result<(), Box> { - let args: Vec<_> = std::env::args().collect(); - if args.len() < 3 { return Err("usage: migration_plan [--apply|--sql-only ]".into()); } - let root = std::path::Path::new(&args[1]); - let bytes = std::fs::read(&args[2])?; - let signature = std::fs::read_to_string(format!("{}.sig",args[2]))?; - coa_core::signing::verify(&bytes, &signature, coa_core::signing::EMBEDDED_PUBLIC_KEY)?; - let manifest = Manifest::parse(&bytes)?; - for (index,mode) in [Mode::Coa, Mode::Wildcard].into_iter().enumerate() { - let db = Db::from_repack(root, Account::Admin)?.for_realm(mode); - let rows = db.load_readonly()?; - let relevant: Vec<_> = rows.iter().filter(|r| r.id == "rev_20260903_01_live_class_baseline").map(|r| format!("{} {:?} {}",r.db,r.status,r.baseline)).collect(); - println!("{} baseline history: {:?}",mode.name(),relevant); - let list: Vec<_> = manifest.migrations.iter().filter(|m|index==0 || m.db!="auth").cloned().collect(); - let plan = migrations::status(&db,&list)?; - println!("{} pending: {:?}",mode.name(),plan.iter().filter(|m|m.status!=migrations::Status::Applied).map(|m|(&m.db,&m.id,m.status)).collect::>()); - } - if args.get(3).is_some_and(|s| s == "--apply" || s == "--sql-only") { - assert!(root.file_name().unwrap().to_string_lossy().starts_with("update-database-diagnosis-") && root.join(".coa-update-fixture").is_file(), "Only disposable fixture roots may be changed"); - if args[3] == "--sql-only" { - let db = Db::from_repack(root, Account::Admin)?.for_realm(Mode::Coa); - let identity = || -> coa_core::Result { - let mut rows = String::new(); - for (schema,table,columns) in [("acore_auth","account","id,HEX(username)"),("acore_characters","characters","guid,account,HEX(name)"),("acore_characters_wildcard","characters","guid,account,HEX(name)")] { - rows.push_str(schema); - rows.push_str(&db.query(&format!("SELECT {columns} FROM {schema}.{table} ORDER BY 1;"))?); + let args: Vec<_> = std::env::args().collect(); + if args.len() < 3 { + return Err("usage: migration_plan [--apply|--sql-only ]".into()); } - Ok(coa_core::fsx::sha256_bytes(rows.as_bytes())) - }; - let before = identity()?; - migrations::verify_files(&manifest.migrations,std::path::Path::new(&args[4]))?; - for (index,mode) in [Mode::Coa,Mode::Wildcard].into_iter().enumerate() { - let realm_db = db.clone().for_realm(mode); - let list: Vec<_> = manifest.migrations.iter().filter(|m|index==0 || m.db!="auth").cloned().collect(); - let result = migrations::apply_pending(&realm_db,&list,std::path::Path::new(&args[4]),&||Ok("disposable fixture".into()))?; - println!("{} SQL result: {}",mode.name(),serde_json::to_string(&result)?); - if result.failed.is_some() {return Err("SQL failed; fixture preserved".into());} - } - assert_eq!(before,identity()?,"Account or character identity changed"); - println!("Account and character identities preserved: {}",before); - let capture = root.join("captured-schema"); - coa_core::schema_check::capture(&db,&capture)?; - println!("Captured schema SHA256: {}",coa_core::fsx::sha256_file(&capture.join(coa_core::schema_check::CONTRACT))?); - return Ok(()); - } - if args.len() != 5 { return Err("Migration directory required".into()); } - use coa_core::update::{Env, RepackEnv}; - let meta = coa_core::registry::metadata_dir_for(root)?; - let env = RepackEnv { root, meta_dir: &meta }; - let result = env.migrate(&manifest, std::path::Path::new(&args[4])); - let _ = coa_core::driver::run(root, coa_core::driver::Verb::StopAll); - println!("Application result: {}",serde_json::to_string(&result?)?); - } - Ok(()) + let root = std::path::Path::new(&args[1]); + let bytes = std::fs::read(&args[2])?; + let signature = std::fs::read_to_string(format!("{}.sig", args[2]))?; + coa_core::signing::verify(&bytes, &signature, coa_core::signing::EMBEDDED_PUBLIC_KEY)?; + let manifest = Manifest::parse(&bytes)?; + for (index, mode) in [Mode::Coa, Mode::Wildcard].into_iter().enumerate() { + let db = Db::from_repack(root, Account::Admin)?.for_realm(mode); + let rows = db.load_readonly()?; + let relevant: Vec<_> = rows + .iter() + .filter(|r| r.id == "rev_20260903_01_live_class_baseline") + .map(|r| format!("{} {:?} {}", r.db, r.status, r.baseline)) + .collect(); + println!("{} baseline history: {:?}", mode.name(), relevant); + let list: Vec<_> = manifest + .migrations + .iter() + .filter(|m| index == 0 || m.db != "auth") + .cloned() + .collect(); + let plan = migrations::status(&db, &list)?; + println!( + "{} pending: {:?}", + mode.name(), + plan.iter() + .filter(|m| m.status != migrations::Status::Applied) + .map(|m| (&m.db, &m.id, m.status)) + .collect::>() + ); + } + if args + .get(3) + .is_some_and(|s| s == "--apply" || s == "--sql-only") + { + assert!( + root.file_name() + .unwrap() + .to_string_lossy() + .starts_with("update-database-diagnosis-") + && root.join(".coa-update-fixture").is_file(), + "Only disposable fixture roots may be changed" + ); + if args[3] == "--sql-only" { + let db = Db::from_repack(root, Account::Admin)?.for_realm(Mode::Coa); + let identity = || -> coa_core::Result { + let mut rows = String::new(); + for (schema, table, columns) in [ + ("acore_auth", "account", "id,HEX(username)"), + ("acore_characters", "characters", "guid,account,HEX(name)"), + ( + "acore_characters_wildcard", + "characters", + "guid,account,HEX(name)", + ), + ] { + rows.push_str(schema); + rows.push_str(&db.query(&format!( + "SELECT {columns} FROM {schema}.{table} ORDER BY 1;" + ))?); + } + Ok(coa_core::fsx::sha256_bytes(rows.as_bytes())) + }; + let before = identity()?; + migrations::verify_files(&manifest.migrations, std::path::Path::new(&args[4]))?; + for (index, mode) in [Mode::Coa, Mode::Wildcard].into_iter().enumerate() { + let realm_db = db.clone().for_realm(mode); + let list: Vec<_> = manifest + .migrations + .iter() + .filter(|m| index == 0 || m.db != "auth") + .cloned() + .collect(); + let result = migrations::apply_pending( + &realm_db, + &list, + std::path::Path::new(&args[4]), + &|| Ok("disposable fixture".into()), + )?; + println!( + "{} SQL result: {}", + mode.name(), + serde_json::to_string(&result)? + ); + if result.failed.is_some() { + return Err("SQL failed; fixture preserved".into()); + } + } + assert_eq!(before, identity()?, "Account or character identity changed"); + println!("Account and character identities preserved: {}", before); + let capture = root.join("captured-schema"); + coa_core::schema_check::capture(&db, &capture)?; + println!( + "Captured schema SHA256: {}", + coa_core::fsx::sha256_file(&capture.join(coa_core::schema_check::CONTRACT))? + ); + return Ok(()); + } + if args.len() != 5 { + return Err("Migration directory required".into()); + } + use coa_core::update::{Env, RepackEnv}; + let meta = coa_core::registry::metadata_dir_for(root)?; + let env = RepackEnv { + root, + meta_dir: &meta, + }; + let result = env.migrate(&manifest, std::path::Path::new(&args[4])); + let _ = coa_core::driver::run(root, coa_core::driver::Verb::StopAll); + println!("Application result: {}", serde_json::to_string(&result?)?); + } + Ok(()) } diff --git a/crates/coa-core/examples/upgrade_fixture.rs b/crates/coa-core/examples/upgrade_fixture.rs index 4b7d617..00ff649 100644 --- a/crates/coa-core/examples/upgrade_fixture.rs +++ b/crates/coa-core/examples/upgrade_fixture.rs @@ -1,28 +1,62 @@ //! Exercise the production updater only on a disposable copy of an installed server. -use coa_core::{registry::MetaDir, update::{self, Env, RepackEnv}}; -fn main() -> Result<(),Box> { - let args:Vec<_>=std::env::args().collect(); - if args.len()!=3 && args.len()!=4 {return Err("usage: upgrade_fixture ".into());} - let root=std::path::Path::new(&args[1]); - assert!(root.file_name().unwrap().to_string_lossy().starts_with("coa-schema-fixture-real") && root.join(".coa-update-fixture").is_file(),"Disposable fixture required"); - let meta=coa_core::registry::metadata_dir_for(root)?; - let (_,installed)=MetaDir::open(&meta)?; - assert_eq!(coa_core::fsx::canonicalize_lenient(std::path::Path::new(&installed.server_path))?,coa_core::fsx::canonicalize_lenient(root)?,"Fixture metadata must point to the copy"); - assert!(installed.client_path.is_none(),"Detach the real client from fixture metadata"); - let env=RepackEnv{root,meta_dir:&meta}; - if args.get(3).is_some_and(|flag|flag=="--validate-only") { - let result=env.validate(); - let _=coa_core::driver::run(root,coa_core::driver::Verb::StopAll); - result?; - println!("Startup and identity validation passed"); - return Ok(()); - } - let outcome=update::apply(&update::Params{root,meta_dir:&meta,source:coa_core::pkgsource::Source::Dir(args[2].clone().into()),trusted_key:coa_core::signing::EMBEDDED_PUBLIC_KEY,cancel:Default::default(),resolutions:Default::default(),env:&env,fail_after_ops:None},&|phase,percent|println!("{percent}% {phase}")); - let stopped=coa_core::driver::run(root,coa_core::driver::Verb::StopAll); - println!("Shutdown after test: {:?}",stopped.map(|r|r.ok)); - let outcome=outcome?; - println!("Final transaction: {:?}",outcome.txn.state); - env.ensure_stopped()?; - assert_eq!(outcome.txn.state,update::State::Committed); - Ok(()) +use coa_core::{ + registry::MetaDir, + update::{self, Env, RepackEnv}, +}; +fn main() -> Result<(), Box> { + let args: Vec<_> = std::env::args().collect(); + if args.len() != 3 && args.len() != 4 { + return Err("usage: upgrade_fixture ".into()); + } + let root = std::path::Path::new(&args[1]); + assert!( + root.file_name() + .unwrap() + .to_string_lossy() + .starts_with("coa-schema-fixture-real") + && root.join(".coa-update-fixture").is_file(), + "Disposable fixture required" + ); + let meta = coa_core::registry::metadata_dir_for(root)?; + let (_, installed) = MetaDir::open(&meta)?; + assert_eq!( + coa_core::fsx::canonicalize_lenient(std::path::Path::new(&installed.server_path))?, + coa_core::fsx::canonicalize_lenient(root)?, + "Fixture metadata must point to the copy" + ); + assert!( + installed.client_path.is_none(), + "Detach the real client from fixture metadata" + ); + let env = RepackEnv { + root, + meta_dir: &meta, + }; + if args.get(3).is_some_and(|flag| flag == "--validate-only") { + let result = env.validate(); + let _ = coa_core::driver::run(root, coa_core::driver::Verb::StopAll); + result?; + println!("Startup and identity validation passed"); + return Ok(()); + } + let outcome = update::apply( + &update::Params { + root, + meta_dir: &meta, + source: coa_core::pkgsource::Source::Dir(args[2].clone().into()), + trusted_key: coa_core::signing::EMBEDDED_PUBLIC_KEY, + cancel: Default::default(), + resolutions: Default::default(), + env: &env, + fail_after_ops: None, + }, + &|phase, percent| println!("{percent}% {phase}"), + ); + let stopped = coa_core::driver::run(root, coa_core::driver::Verb::StopAll); + println!("Shutdown after test: {:?}", stopped.map(|r| r.ok)); + let outcome = outcome?; + println!("Final transaction: {:?}", outcome.txn.state); + env.ensure_stopped()?; + assert_eq!(outcome.txn.state, update::State::Committed); + Ok(()) } diff --git a/crates/coa-core/src/backup.rs b/crates/coa-core/src/backup.rs index 6fa675b..627d820 100644 --- a/crates/coa-core/src/backup.rs +++ b/crates/coa-core/src/backup.rs @@ -261,7 +261,9 @@ pub fn config_files(root: &Path) -> Vec { for e in rd.flatten() { let n = e.file_name().to_string_lossy().to_string(); // database.json holds generated database passwords; it is launcher state, not configuration. - if e.path().is_file() && (n.contains(".template") || n == "repack.json" || n == "docker.json") { + if e.path().is_file() + && (n.contains(".template") || n == "repack.json" || n == "docker.json") + { out.push(format!("Settings/{n}")); } } @@ -381,12 +383,19 @@ pub fn create( let build = || -> Result> { let mut components = Vec::new(); let realm = crate::realms::state(root)?; - let mut databases: Vec<(String, &str)> = wanted_databases(kind).iter() - .map(|name| Ok((name.to_string(), realm.active.schema(name)?))).collect::>()?; + let mut databases: Vec<(String, &str)> = wanted_databases(kind) + .iter() + .map(|name| Ok((name.to_string(), realm.active.schema(name)?))) + .collect::>()?; if kind != Kind::Config { for other in realm.modes().into_iter().filter(|m| *m != realm.active) { - databases.push((format!("{}-characters", other.name()), other.schema("characters")?)); - if kind == Kind::Full { databases.push((format!("{}-world", other.name()), other.schema("world")?)); } + databases.push(( + format!("{}-characters", other.name()), + other.schema("characters")?, + )); + if kind == Kind::Full { + databases.push((format!("{}-world", other.name()), other.schema("world")?)); + } } } if kind != Kind::Config && with_database(root, |db| db.schema_exists("acore_playerbots"))? { @@ -427,16 +436,24 @@ pub fn create( return Err(e); } }; - let mysql_snapshot = if kind == Kind::Full && matches!(trigger, Trigger::BeforeUpdate | Trigger::BeforeRepair) && cfg!(windows) && !crate::docker::is_docker(root) { + let mysql_snapshot = if kind == Kind::Full + && matches!(trigger, Trigger::BeforeUpdate | Trigger::BeforeRepair) + && cfg!(windows) + && !crate::docker::is_docker(root) + { progress("Saving a complete stopped MySQL recovery copy"); match crate::mysql_snapshot::capture(root, &partial) { Ok(snapshot) => Some(snapshot), Err(error) => { - if let Ok(owned) = fsx::ensure_within(&backups_dir(meta), &partial) { let _ = fs::remove_dir_all(owned); } + if let Ok(owned) = fsx::ensure_within(&backups_dir(meta), &partial) { + let _ = fs::remove_dir_all(owned); + } return Err(error); } } - } else { None }; + } else { + None + }; let point = RecoveryPoint { realm: crate::realms::state(root)?.active, schema: 1, @@ -485,7 +502,9 @@ pub fn verify(meta: &Path, id: &str) -> Result { let dir = point_dir(meta, id)?; let mut problems = Vec::new(); if let Some(snapshot) = &point.mysql_snapshot { - if let Err(error) = crate::mysql_snapshot::verify(&dir, snapshot) { problems.push(error.to_string()); } + if let Err(error) = crate::mysql_snapshot::verify(&dir, snapshot) { + problems.push(error.to_string()); + } } let mut names = std::collections::BTreeSet::new(); let mut schemas = std::collections::BTreeSet::new(); diff --git a/crates/coa-core/src/channels.rs b/crates/coa-core/src/channels.rs index 53d787a..db5ac3e 100644 --- a/crates/coa-core/src/channels.rs +++ b/crates/coa-core/src/channels.rs @@ -1,7 +1,7 @@ //! Signed channel pointers select one immutable package for an entire transaction. -use serde::{Deserialize, Serialize}; -use crate::{Error, Result}; use crate::pkgsource::{fetch_small, Source}; +use crate::{Error, Result}; +use serde::{Deserialize, Serialize}; #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] @@ -21,15 +21,22 @@ pub struct Envelope { } pub fn verify(bytes: &[u8], channel: &str, key: &str) -> Result { - let envelope: Envelope = serde_json::from_slice(bytes).map_err(|e| Error::InvalidManifest(e.to_string()))?; + let envelope: Envelope = + serde_json::from_slice(bytes).map_err(|e| Error::InvalidManifest(e.to_string()))?; crate::signing::verify(envelope.payload.as_bytes(), &envelope.signature, key)?; - let pointer: Pointer = serde_json::from_str(&envelope.payload).map_err(|e| Error::InvalidManifest(e.to_string()))?; - if pointer.schema != 1 || pointer.channel != channel + let pointer: Pointer = serde_json::from_str(&envelope.payload) + .map_err(|e| Error::InvalidManifest(e.to_string()))?; + if pointer.schema != 1 + || pointer.channel != channel || pointer.release_tag != format!("server-{}", pointer.version) || pointer.version.is_empty() - || !pointer.version.bytes().all(|b| b.is_ascii_digit() || b == b'.') + || !pointer + .version + .bytes() + .all(|b| b.is_ascii_digit() || b == b'.') || pointer.snapshot.len() != 64 - || !pointer.snapshot.bytes().all(|b| b.is_ascii_hexdigit()) { + || !pointer.snapshot.bytes().all(|b| b.is_ascii_hexdigit()) + { return Err(Error::InvalidManifest("Invalid channel pointer".into())); } Ok(pointer) @@ -39,21 +46,37 @@ pub fn resolve(channel: &str) -> Result { if channel != "stable" && channel != "edge" { return Err(Error::InvalidManifest("Unknown release channel".into())); } - let source = Source::Url("https://raw.githubusercontent.com/Corfirean/coa-server-build/channels".into()); + let source = + Source::Url("https://raw.githubusercontent.com/Corfirean/coa-server-build/channels".into()); let bytes = fetch_small(&source, &format!("{channel}.json"))?; let pointer = verify(&bytes, channel, crate::signing::EMBEDDED_PUBLIC_KEY)?; - Ok(Source::Url(format!("https://github.com/Corfirean/coa-server-build/releases/download/{}", pointer.release_tag))) + Ok(Source::Url(format!( + "https://github.com/Corfirean/coa-server-build/releases/download/{}", + pointer.release_tag + ))) } pub fn sign(pointer: &Pointer, seed: &str) -> Result> { use base64::{engine::general_purpose::STANDARD, Engine}; use ed25519_dalek::{Signer, SigningKey}; - let seed: [u8; 32] = STANDARD.decode(seed.trim()).map_err(|_| Error::Invalid("Invalid signing key".into()))? - .try_into().map_err(|_| Error::Invalid("Invalid signing key length".into()))?; + let seed: [u8; 32] = STANDARD + .decode(seed.trim()) + .map_err(|_| Error::Invalid("Invalid signing key".into()))? + .try_into() + .map_err(|_| Error::Invalid("Invalid signing key length".into()))?; let payload = serde_json::to_string(pointer).map_err(|e| Error::Invalid(e.to_string()))?; - let signature = STANDARD.encode(SigningKey::from_bytes(&seed).sign(payload.as_bytes()).to_bytes()); - let bytes = serde_json::to_vec(&Envelope { payload, signature }).map_err(|e| Error::Invalid(e.to_string()))?; - verify(&bytes, &pointer.channel, crate::signing::EMBEDDED_PUBLIC_KEY)?; + let signature = STANDARD.encode( + SigningKey::from_bytes(&seed) + .sign(payload.as_bytes()) + .to_bytes(), + ); + let bytes = serde_json::to_vec(&Envelope { payload, signature }) + .map_err(|e| Error::Invalid(e.to_string()))?; + verify( + &bytes, + &pointer.channel, + crate::signing::EMBEDDED_PUBLIC_KEY, + )?; Ok(bytes) } @@ -67,12 +90,21 @@ mod tests { let sk = SigningKey::from_bytes(&[17; 32]); let payload = serde_json::to_string(pointer).unwrap(); let signature = STANDARD.encode(sk.sign(payload.as_bytes()).to_bytes()); - (serde_json::to_vec(&Envelope { payload, signature }).unwrap(), STANDARD.encode(sk.verifying_key().to_bytes())) + ( + serde_json::to_vec(&Envelope { payload, signature }).unwrap(), + STANDARD.encode(sk.verifying_key().to_bytes()), + ) } #[test] fn verifies_identity_signature_and_immutable_tag() { - let mut p = Pointer { schema: 1, channel: "stable".into(), version: "0.261010.40".into(), release_tag: "server-0.261010.40".into(), snapshot: "a".repeat(64) }; + let mut p = Pointer { + schema: 1, + channel: "stable".into(), + version: "0.261010.40".into(), + release_tag: "server-0.261010.40".into(), + snapshot: "a".repeat(64), + }; let (bytes, key) = signed(&p); assert_eq!(verify(&bytes, "stable", &key).unwrap().version, p.version); assert!(verify(&bytes, "edge", &key).is_err()); diff --git a/crates/coa-core/src/client.rs b/crates/coa-core/src/client.rs index fa9ebfc..814e87c 100644 --- a/crates/coa-core/src/client.rs +++ b/crates/coa-core/src/client.rs @@ -417,11 +417,21 @@ pub fn launch(client: &Path) -> Result { return crate::wine::launch(client, exe); } let executable = client.join(exe); - let spawn = || Command::new(&executable).current_dir(client).spawn().map(|child| child.id()); + let spawn = || { + Command::new(&executable) + .current_dir(client) + .spawn() + .map(|child| child.id()) + }; #[cfg(windows)] - { launch_with_elevation_fallback(spawn, || launch_elevated(&executable, client)).map_err(Into::into) } + { + launch_with_elevation_fallback(spawn, || launch_elevated(&executable, client)) + .map_err(Into::into) + } #[cfg(not(windows))] - { spawn().map_err(Into::into) } + { + spawn().map_err(Into::into) + } } /// Start normally first; ask Windows for elevation only when the client requires it (ERROR_ELEVATION_REQUIRED, 740). @@ -443,9 +453,15 @@ fn launch_elevated(executable: &Path, directory: &Path) -> std::io::Result use std::os::windows::ffi::OsStrExt; use windows_sys::Win32::Foundation::CloseHandle; use windows_sys::Win32::System::Threading::GetProcessId; - use windows_sys::Win32::UI::Shell::{ShellExecuteExW, SHELLEXECUTEINFOW, SEE_MASK_NOCLOSEPROCESS, SEE_MASK_NOASYNC}; + use windows_sys::Win32::UI::Shell::{ + ShellExecuteExW, SEE_MASK_NOASYNC, SEE_MASK_NOCLOSEPROCESS, SHELLEXECUTEINFOW, + }; use windows_sys::Win32::UI::WindowsAndMessaging::SW_SHOWNORMAL; - let file: Vec = executable.as_os_str().encode_wide().chain(Some(0)).collect(); + let file: Vec = executable + .as_os_str() + .encode_wide() + .chain(Some(0)) + .collect(); let cwd: Vec = directory.as_os_str().encode_wide().chain(Some(0)).collect(); let verb: Vec = "runas".encode_utf16().chain(Some(0)).collect(); let mut info = SHELLEXECUTEINFOW { @@ -457,12 +473,22 @@ fn launch_elevated(executable: &Path, directory: &Path) -> std::io::Result nShow: SW_SHOWNORMAL, ..Default::default() }; - if unsafe { ShellExecuteExW(&mut info) } == 0 { return Err(std::io::Error::last_os_error()); } - if info.hProcess.is_null() { return Err(std::io::Error::other("Windows did not return the game process handle.")); } + if unsafe { ShellExecuteExW(&mut info) } == 0 { + return Err(std::io::Error::last_os_error()); + } + if info.hProcess.is_null() { + return Err(std::io::Error::other( + "Windows did not return the game process handle.", + )); + } let pid = unsafe { GetProcessId(info.hProcess) }; let error = std::io::Error::last_os_error(); - unsafe { CloseHandle(info.hProcess); } - if pid == 0 { return Err(error); } + unsafe { + CloseHandle(info.hProcess); + } + if pid == 0 { + return Err(error); + } Ok(pid) } @@ -585,11 +611,29 @@ mod tests { #[cfg(windows)] #[test] fn elevation_is_requested_only_when_windows_requires_it() { - assert_eq!(launch_with_elevation_fallback(|| Ok(17), || panic!("unneeded elevation")).unwrap(), 17); - assert_eq!(launch_with_elevation_fallback(|| Err(std::io::Error::from_raw_os_error(740)), || Ok(23)).unwrap(), 23); - let error = launch_with_elevation_fallback(|| Err(std::io::Error::from_raw_os_error(2)), || panic!("wrong error elevated")).unwrap_err(); + assert_eq!( + launch_with_elevation_fallback(|| Ok(17), || panic!("unneeded elevation")).unwrap(), + 17 + ); + assert_eq!( + launch_with_elevation_fallback( + || Err(std::io::Error::from_raw_os_error(740)), + || Ok(23) + ) + .unwrap(), + 23 + ); + let error = launch_with_elevation_fallback( + || Err(std::io::Error::from_raw_os_error(2)), + || panic!("wrong error elevated"), + ) + .unwrap_err(); assert_eq!(error.raw_os_error(), Some(2)); - let cancelled = launch_with_elevation_fallback(|| Err(std::io::Error::from_raw_os_error(740)), || Err(std::io::Error::from_raw_os_error(1223))).unwrap_err(); + let cancelled = launch_with_elevation_fallback( + || Err(std::io::Error::from_raw_os_error(740)), + || Err(std::io::Error::from_raw_os_error(1223)), + ) + .unwrap_err(); assert_eq!(cancelled.raw_os_error(), Some(1223)); } @@ -620,7 +664,10 @@ mod tests { assert!(sync_realm(&c, &meta, crate::realms::Mode::Wildcard).unwrap()); assert_eq!(fs::read(c.join("WTF/Config.wtf")).unwrap(), original); assert!(sync_realm(&c, &meta, crate::realms::Mode::Reborn).unwrap()); - assert_eq!(fs::read(c.join("WTF/Config.wtf")).unwrap(), b"SET sound 1\r\nSET realmName \"Warcraft Reborn\"\r\n"); + assert_eq!( + fs::read(c.join("WTF/Config.wtf")).unwrap(), + b"SET sound 1\r\nSET realmName \"Warcraft Reborn\"\r\n" + ); } #[test] diff --git a/crates/coa-core/src/console.rs b/crates/coa-core/src/console.rs index 91098ad..b370d46 100644 --- a/crates/coa-core/src/console.rs +++ b/crates/coa-core/src/console.rs @@ -61,8 +61,16 @@ pub fn lines_from_text(text: &str, filter: Option<&str>, max_lines: usize) -> Ve let out: Vec = text .lines() .filter(|l| !l.trim().is_empty()) - .filter(|l| needle.as_ref().map(|n| l.to_lowercase().contains(n)).unwrap_or(true)) - .map(|l| Line { level: classify(l), text: crate::diag::redact(l) }) + .filter(|l| { + needle + .as_ref() + .map(|n| l.to_lowercase().contains(n)) + .unwrap_or(true) + }) + .map(|l| Line { + level: classify(l), + text: crate::diag::redact(l), + }) .collect(); let skip = out.len().saturating_sub(max_lines); out.into_iter().skip(skip).collect() diff --git a/crates/coa-core/src/control/service.rs b/crates/coa-core/src/control/service.rs index 36f84d4..27cbf6f 100644 --- a/crates/coa-core/src/control/service.rs +++ b/crates/coa-core/src/control/service.rs @@ -761,7 +761,7 @@ impl HostService { ); } for kind in collections.keys() { - if !kind.starts_with(offer_ruleset.as_str()) { + if !crate::portable::session::protocol::carried_kind_for(kind, offer_ruleset) { return err( AppError::Incompatible, "Collection kind does not belong to this ruleset.", @@ -1454,7 +1454,7 @@ mod tests { &Uuid::now_v7(), "K", Request::Hello { - protocol: 1, + protocol: coa_control_proto::CONTROL_PROTOCOL_VERSION, client: "t".into(), }, ) @@ -2435,7 +2435,13 @@ mod tests { collections: BTreeMap::new(), }; let r = s.handle(&mut session, &p, "K", wc_offer); - assert!(matches!(r, Response::Error { code: AppError::Incompatible, .. })); + assert!(matches!( + r, + Response::Error { + code: AppError::Incompatible, + .. + } + )); // 2. Host is CoA, offer is Reborn -> Rejected let rb_offer = Request::TransferOffer { @@ -2448,7 +2454,13 @@ mod tests { collections: BTreeMap::new(), }; let r = s.handle(&mut session, &p, "K", rb_offer); - assert!(matches!(r, Response::Error { code: AppError::Incompatible, .. })); + assert!(matches!( + r, + Response::Error { + code: AppError::Incompatible, + .. + } + )); // 3. Collection kinds for another ruleset -> Rejected let foreign_coll_offer = Request::TransferOffer { @@ -2461,7 +2473,13 @@ mod tests { collections: BTreeMap::from([("wildcard:appearance".into(), vec![1, 2, 3])]), }; let r = s.handle(&mut session, &p, "K", foreign_coll_offer); - assert!(matches!(r, Response::Error { code: AppError::Incompatible, .. })); + assert!(matches!( + r, + Response::Error { + code: AppError::Incompatible, + .. + } + )); // Ensure 0 DB imports happened assert!(realm.imported.lock().unwrap().is_empty()); diff --git a/crates/coa-core/src/custom_races.rs b/crates/coa-core/src/custom_races.rs index 6d3904c..72bf9a4 100644 --- a/crates/coa-core/src/custom_races.rs +++ b/crates/coa-core/src/custom_races.rs @@ -206,10 +206,9 @@ fn patch_files(client: &Path) -> Result> { )); } Some(name.to_string()) - } else if let Some(name) = line.strip_prefix("ADDON:") { - Some(format!("Interface/AddOns/{name}")) } else { - None + line.strip_prefix("ADDON:") + .map(|name| format!("Interface/AddOns/{name}")) }; if let Some(path) = path { fsx::safe_join(client, &path)?; diff --git a/crates/coa-core/src/db.rs b/crates/coa-core/src/db.rs index 593f0af..53f1b1c 100644 --- a/crates/coa-core/src/db.rs +++ b/crates/coa-core/src/db.rs @@ -75,11 +75,23 @@ pub const SCHEMAS: [(&str, &str); 3] = [ ]; pub fn schema_of(kind: &str) -> Result<&'static str> { - if kind == "playerbots" { return Ok("acore_playerbots"); } - if let Some(kind) = kind.strip_prefix("wildcard-") { return crate::realms::Mode::Wildcard.schema(kind); } - if let Some(kind) = kind.strip_prefix("reborn-") { return crate::realms::Mode::Reborn.schema(kind); } - if let Some(kind) = kind.strip_prefix("coa-") { return crate::realms::Mode::Coa.schema(kind); } - SCHEMAS.iter().find(|(k, _)| *k == kind).map(|(_, s)| *s).ok_or_else(|| Error::Invalid(format!("unknown database {kind}"))) + if kind == "playerbots" { + return Ok("acore_playerbots"); + } + if let Some(kind) = kind.strip_prefix("wildcard-") { + return crate::realms::Mode::Wildcard.schema(kind); + } + if let Some(kind) = kind.strip_prefix("reborn-") { + return crate::realms::Mode::Reborn.schema(kind); + } + if let Some(kind) = kind.strip_prefix("coa-") { + return crate::realms::Mode::Coa.schema(kind); + } + SCHEMAS + .iter() + .find(|(k, _)| *k == kind) + .map(|(_, s)| *s) + .ok_or_else(|| Error::Invalid(format!("unknown database {kind}"))) } fn ident_ok(name: &str) -> bool { @@ -357,9 +369,11 @@ impl Db { pub fn recovery_objects(&self, schema: &str) -> Result> { let schema = self.realm_schema(schema); - if !ident_ok(schema) { return Err(Error::Invalid("bad schema name".into())); } + if !ident_ok(schema) { + return Err(Error::Invalid("bad schema name".into())); + } let sql = format!("SELECT routine_type,HEX(routine_name) FROM information_schema.routines WHERE routine_schema='{schema}' UNION ALL SELECT 'TRIGGER',HEX(trigger_name) FROM information_schema.triggers WHERE trigger_schema='{schema}' UNION ALL SELECT 'VIEW',HEX(table_name) FROM information_schema.views WHERE table_schema='{schema}' ORDER BY 1,2;"); - parse_recovery_objects(&schema, &self.query(&sql)?) + parse_recovery_objects(schema, &self.query(&sql)?) } /// Consistent dump of one schema, zstd-compressed to `out`. Returns (compressed bytes, sha256 of the file). @@ -469,15 +483,23 @@ impl Db { } fn parse_recovery_objects(schema: &str, text: &str) -> Result> { - text.lines().filter(|line| !line.is_empty()).map(|line| { - let (kind, name) = line.split_once('\t').ok_or_else(|| Error::Invalid("unexpected database object reply".into()))?; - if !matches!(kind, "PROCEDURE" | "FUNCTION" | "TRIGGER" | "VIEW") { - return Err(Error::Invalid("unexpected database object type".into())); - } - let name = hex::decode(name).ok().and_then(|bytes| String::from_utf8(bytes).ok()) - .filter(|name| !name.is_empty()).ok_or_else(|| Error::Invalid("unexpected database object name".into()))?; - Ok(serde_json::json!({ "database": schema, "kind": kind, "name": name })) - }).collect() + text.lines() + .filter(|line| !line.is_empty()) + .map(|line| { + let (kind, name) = line + .split_once('\t') + .ok_or_else(|| Error::Invalid("unexpected database object reply".into()))?; + if !matches!(kind, "PROCEDURE" | "FUNCTION" | "TRIGGER" | "VIEW") { + return Err(Error::Invalid("unexpected database object type".into())); + } + let name = hex::decode(name) + .ok() + .and_then(|bytes| String::from_utf8(bytes).ok()) + .filter(|name| !name.is_empty()) + .ok_or_else(|| Error::Invalid("unexpected database object name".into()))?; + Ok(serde_json::json!({ "database": schema, "kind": kind, "name": name })) + }) + .collect() } /// Name of the service account the Manager uses for the server console (RA). Accounts are stored upper-case. @@ -587,7 +609,10 @@ mod tests { use crate::realms::Mode; let sql = "SELECT * FROM `acore_characters`.characters WHERE name='acore_world'; -- acore_world\nSELECT * FROM acore_world.items; SELECT * FROM acore_world_wildcard.items;"; assert_eq!(super::route_sql(sql, Mode::Reborn), "SELECT * FROM `acore_characters_reborn`.characters WHERE name='acore_world'; -- acore_world\nSELECT * FROM acore_world_reborn.items; SELECT * FROM acore_world_wildcard.items;"); - assert_eq!(super::schema_of("reborn-characters").unwrap(), "acore_characters_reborn"); + assert_eq!( + super::schema_of("reborn-characters").unwrap(), + "acore_characters_reborn" + ); assert_eq!(super::schema_of("reborn-auth").unwrap(), "acore_auth"); } use super::*; diff --git a/crates/coa-core/src/diag.rs b/crates/coa-core/src/diag.rs index 8aca557..10ca4a8 100644 --- a/crates/coa-core/src/diag.rs +++ b/crates/coa-core/src/diag.rs @@ -1045,7 +1045,12 @@ real error fn stop_diagnostics_survive_while_portable_pins_remain_hidden() { let ordinary = "MySQL is still stopping; wait before copying the repack."; assert_eq!(redact(ordinary), ordinary); - for secret in ["PIN: 123456", "pin=123456", "transfer_pin=123456", "PIN123456"] { + for secret in [ + "PIN: 123456", + "pin=123456", + "transfer_pin=123456", + "PIN123456", + ] { let output = redact(&format!("{ordinary}\n{secret}")); assert!(output.contains(ordinary)); assert!(!output.contains("123456")); diff --git a/crates/coa-core/src/docker/lifecycle.rs b/crates/coa-core/src/docker/lifecycle.rs index 4abec44..c249b9a 100644 --- a/crates/coa-core/src/docker/lifecycle.rs +++ b/crates/coa-core/src/docker/lifecycle.rs @@ -1249,12 +1249,27 @@ mod tests { "db;3306;acore;apppw;acore_characters" ); let wild = database_env(&s, true, crate::realms::Mode::Wildcard); - assert_eq!(get(&wild, "AC_WORLD_DATABASE_INFO").unwrap(), "db;3306;acore;apppw;acore_world_wildcard"); - assert_eq!(get(&wild, "AC_CHARACTER_DATABASE_INFO").unwrap(), "db;3306;acore;apppw;acore_characters_wildcard"); + assert_eq!( + get(&wild, "AC_WORLD_DATABASE_INFO").unwrap(), + "db;3306;acore;apppw;acore_world_wildcard" + ); + assert_eq!( + get(&wild, "AC_CHARACTER_DATABASE_INFO").unwrap(), + "db;3306;acore;apppw;acore_characters_wildcard" + ); let reborn = database_env(&s, true, crate::realms::Mode::Reborn); - assert_eq!(get(&reborn, "AC_WORLD_DATABASE_INFO").unwrap(), "db;3306;acore;apppw;acore_world_reborn"); - assert_eq!(get(&reborn, "AC_CHARACTER_DATABASE_INFO").unwrap(), "db;3306;acore;apppw;acore_characters_reborn"); - assert_eq!(get(&reborn, "AC_LOGIN_DATABASE_INFO").unwrap(), "db;3306;acore;apppw;acore_auth"); + assert_eq!( + get(&reborn, "AC_WORLD_DATABASE_INFO").unwrap(), + "db;3306;acore;apppw;acore_world_reborn" + ); + assert_eq!( + get(&reborn, "AC_CHARACTER_DATABASE_INFO").unwrap(), + "db;3306;acore;apppw;acore_characters_reborn" + ); + assert_eq!( + get(&reborn, "AC_LOGIN_DATABASE_INFO").unwrap(), + "db;3306;acore;apppw;acore_auth" + ); // Accounts are shared by both realms; the auth server never sees the others. assert_eq!( get(&wild, "AC_LOGIN_DATABASE_INFO").unwrap(), diff --git a/crates/coa-core/src/docker/logs.rs b/crates/coa-core/src/docker/logs.rs index 19ca170..64ef8a0 100644 --- a/crates/coa-core/src/docker/logs.rs +++ b/crates/coa-core/src/docker/logs.rs @@ -12,16 +12,28 @@ pub fn database_log(root: &Path, filter: Option<&str>, max_lines: usize) -> Resu database_log_with(&SystemDocker, root, filter, max_lines) } -pub fn database_log_with(d: &dyn Docker, root: &Path, filter: Option<&str>, max_lines: usize) -> Result> { +pub fn database_log_with( + d: &dyn Docker, + root: &Path, + filter: Option<&str>, + max_lines: usize, +) -> Result> { let name = Config::load(root)?.names().db; // Ask for more than wanted: the filter may drop most of them. let tail = (max_lines * 4).clamp(200, 8000).to_string(); - let out = d.run(&Call::new(&["logs", "--tail", &tail, &name], Duration::from_secs(20)))?; + let out = d.run(&Call::new( + &["logs", "--tail", &tail, &name], + Duration::from_secs(20), + ))?; if !out.ok() { return Err(Error::Invalid("This log does not exist yet.".into())); } // MySQL writes to the error stream. - Ok(crate::console::lines_from_text(&format!("{}\n{}", out.stderr, out.stdout), filter, max_lines)) + Ok(crate::console::lines_from_text( + &format!("{}\n{}", out.stderr, out.stdout), + filter, + max_lines, + )) } #[cfg(test)] @@ -58,7 +70,9 @@ mod tests { assert_eq!(fake.calls.borrow()[0][..2], ["logs", "--tail"]); assert_eq!(fake.calls.borrow()[0].last().unwrap(), "coa-t1-db"); assert_eq!(lines.len(), 3); - assert!(lines.iter().any(|l| l.text.contains("boom") && l.level == crate::console::Level::Error)); + assert!(lines + .iter() + .any(|l| l.text.contains("boom") && l.level == crate::console::Level::Error)); let only = database_log_with(&fake, &root, Some("slow"), 100).unwrap(); assert_eq!(only.len(), 1); } @@ -66,7 +80,17 @@ mod tests { #[test] fn a_database_that_never_ran_has_no_log_yet() { let (_d, root) = root(); - let fake = Fake { out: Output { code: Some(1), stdout: String::new(), stderr: "Error: No such container: coa-t1-db".into() }, calls: Default::default() }; - assert!(database_log_with(&fake, &root, None, 10).unwrap_err().to_string().contains("does not exist yet")); + let fake = Fake { + out: Output { + code: Some(1), + stdout: String::new(), + stderr: "Error: No such container: coa-t1-db".into(), + }, + calls: Default::default(), + }; + assert!(database_log_with(&fake, &root, None, 10) + .unwrap_err() + .to_string() + .contains("does not exist yet")); } } diff --git a/crates/coa-core/src/docker/sharing.rs b/crates/coa-core/src/docker/sharing.rs index 1c0d120..0d78aaa 100644 --- a/crates/coa-core/src/docker/sharing.rs +++ b/crates/coa-core/src/docker/sharing.rs @@ -18,7 +18,10 @@ use crate::net::Exposure; use crate::process::{ServiceState, ServiceStatus}; fn is_open(cfg: &Config) -> bool { - cfg.bind_address.parse::().map(|ip| !ip.is_loopback()).unwrap_or(false) + cfg.bind_address + .parse::() + .map(|ip| !ip.is_loopback()) + .unwrap_or(false) } /// Whether the login and world servers are published beyond this computer. @@ -46,7 +49,11 @@ pub fn set_open(root: &Path, meta: &Path, open: bool) -> Result { if let Ok(bytes) = fs::read(&coa_conf) { let mut conf = ConfFile::parse_bytes(&bytes)?; if conf.get("CoA.AllowRemoteClients").map(str::trim) != Some("1") { - conf.set("CoA.AllowRemoteClients", "1", &["Set by CoA Server Manager together with the friends mode"]); + conf.set( + "CoA.AllowRemoteClients", + "1", + &["Set by CoA Server Manager together with the friends mode"], + ); originals.push((coa_conf.clone(), bytes)); coa_edit = Some(conf.to_text()); } @@ -55,7 +62,16 @@ pub fn set_open(root: &Path, meta: &Path, open: bool) -> Result { if !changed && coa_edit.is_none() { return Ok(false); } - take_snapshot(meta, Scope::Server, if open { "before opening the servers to friends" } else { "before closing the servers to friends" }, &originals)?; + take_snapshot( + meta, + Scope::Server, + if open { + "before opening the servers to friends" + } else { + "before closing the servers to friends" + }, + &originals, + )?; if changed { fsx::atomic_write_json(&root.join(MARKER), &cfg)?; } @@ -73,10 +89,30 @@ pub fn exposure(root: &Path, ports: &Ports) -> Vec { let observed = crate::process::observe(root, ports); let up = |s: &ServiceStatus| matches!(s.state, ServiceState::Running | ServiceState::Starting); vec![ - Exposure { port: ports.mysql, what: "database", listening: up(&observed.mysql), reachable_from_network: false }, - Exposure { port: ports.ra, what: "server console", listening: up(&observed.world), reachable_from_network: false }, - Exposure { port: ports.auth, what: "login server", listening: up(&observed.auth), reachable_from_network: open && up(&observed.auth) }, - Exposure { port: ports.world, what: "game world", listening: up(&observed.world), reachable_from_network: open && up(&observed.world) }, + Exposure { + port: ports.mysql, + what: "database", + listening: up(&observed.mysql), + reachable_from_network: false, + }, + Exposure { + port: ports.ra, + what: "server console", + listening: up(&observed.world), + reachable_from_network: false, + }, + Exposure { + port: ports.auth, + what: "login server", + listening: up(&observed.auth), + reachable_from_network: open && up(&observed.auth), + }, + Exposure { + port: ports.world, + what: "game world", + listening: up(&observed.world), + reachable_from_network: open && up(&observed.world), + }, ] } @@ -91,9 +127,15 @@ mod tests { fs::create_dir_all(root.join("Settings")).unwrap(); fs::create_dir_all(root.join("Core/configs/modules")).unwrap(); fs::create_dir_all(&meta).unwrap(); - let extra = bind.map(|b| format!(r#","bindAddress":"{b}""#)).unwrap_or_default(); + let extra = bind + .map(|b| format!(r#","bindAddress":"{b}""#)) + .unwrap_or_default(); fs::write(root.join(MARKER), format!(r#"{{"project":"t1"{extra}}}"#)).unwrap(); - fs::write(root.join("Core/configs/modules/coa.conf"), "CoA.Enable = 1\n").unwrap(); + fs::write( + root.join("Core/configs/modules/coa.conf"), + "CoA.Enable = 1\n", + ) + .unwrap(); (d, root, meta) } @@ -104,8 +146,15 @@ mod tests { assert!(set_open(&root, &meta, true).unwrap(), "a restart is needed"); assert!(bind_is_open(&root)); assert_eq!(Config::load(&root).unwrap().bind_address, "0.0.0.0"); - assert!(fs::read_to_string(root.join("Core/configs/modules/coa.conf")).unwrap().contains("CoA.AllowRemoteClients = 1")); - assert!(!set_open(&root, &meta, true).unwrap(), "nothing left to change"); + assert!( + fs::read_to_string(root.join("Core/configs/modules/coa.conf")) + .unwrap() + .contains("CoA.AllowRemoteClients = 1") + ); + assert!( + !set_open(&root, &meta, true).unwrap(), + "nothing left to change" + ); assert!(set_open(&root, &meta, false).unwrap()); assert!(!bind_is_open(&root)); assert_eq!(Config::load(&root).unwrap().bind_address, "127.0.0.1"); @@ -114,7 +163,11 @@ mod tests { #[test] fn enabling_remote_client_protocol_requires_restart_even_when_ports_are_open() { let (_d, root, meta) = server(Some("0.0.0.0")); - fs::write(root.join("Core/configs/modules/coa.conf"), "CoA.Enable = 1\nCoA.AllowRemoteClients = 0\n").unwrap(); + fs::write( + root.join("Core/configs/modules/coa.conf"), + "CoA.Enable = 1\nCoA.AllowRemoteClients = 0\n", + ) + .unwrap(); assert!(set_open(&root, &meta, true).unwrap()); assert_eq!(Config::load(&root).unwrap().bind_address, "0.0.0.0"); assert!(!set_open(&root, &meta, true).unwrap()); @@ -123,7 +176,10 @@ mod tests { #[test] fn an_address_chosen_by_hand_is_kept_when_opening_and_other_settings_survive() { let (_d, root, meta) = server(Some("192.168.1.20")); - assert!(bind_is_open(&root), "any address but the loopback is the network"); + assert!( + bind_is_open(&root), + "any address but the loopback is the network" + ); set_open(&root, &meta, true).unwrap(); let cfg = Config::load(&root).unwrap(); assert_eq!(cfg.bind_address, "192.168.1.20"); @@ -142,7 +198,9 @@ mod tests { let (_d, root, _meta) = server(Some("0.0.0.0")); let rows = exposure(&root, &Ports::default()); let by = |what: &str| rows.iter().find(|e| e.what == what).unwrap(); - assert!(!by("database").reachable_from_network && !by("server console").reachable_from_network); + assert!( + !by("database").reachable_from_network && !by("server console").reachable_from_network + ); // Nothing runs in this test (docker is not asked to start anything), so nothing is reachable yet. assert!(rows.iter().all(|e| !e.reachable_from_network)); } diff --git a/crates/coa-core/src/fsx.rs b/crates/coa-core/src/fsx.rs index 40614b2..80d89f1 100644 --- a/crates/coa-core/src/fsx.rs +++ b/crates/coa-core/src/fsx.rs @@ -36,7 +36,12 @@ fn key(path: &Path) -> Vec { return format!("{}:", char::from(drive).to_ascii_lowercase()); } Prefix::UNC(server, share) | Prefix::VerbatimUNC(server, share) => { - return format!("\\\\{}\\{}", server.to_string_lossy(), share.to_string_lossy()).to_lowercase(); + return format!( + "\\\\{}\\{}", + server.to_string_lossy(), + share.to_string_lossy() + ) + .to_lowercase(); } _ => {} } @@ -337,12 +342,30 @@ mod tests { #[cfg(windows)] #[test] fn containment_matches_verbatim_drive_and_unc_prefixes() { - assert!(starts_with_ci(Path::new(r"\\?\C:\server\Extras\file.sql"), Path::new(r"C:\server"))); - assert!(starts_with_ci(Path::new(r"C:\server\Extras\file.sql"), Path::new(r"\\?\c:\server"))); - assert!(starts_with_ci(Path::new(r"\\?\UNC\host\share\server\file.sql"), Path::new(r"\\host\share\server"))); - assert!(!starts_with_ci(Path::new(r"\\?\D:\server\file.sql"), Path::new(r"C:\server"))); - assert!(!starts_with_ci(Path::new(r"\\?\C:\server-other\file.sql"), Path::new(r"C:\server"))); - assert!(!starts_with_ci(Path::new(r"\\?\UNC\host\other\server\file.sql"), Path::new(r"\\host\share\server"))); + assert!(starts_with_ci( + Path::new(r"\\?\C:\server\Extras\file.sql"), + Path::new(r"C:\server") + )); + assert!(starts_with_ci( + Path::new(r"C:\server\Extras\file.sql"), + Path::new(r"\\?\c:\server") + )); + assert!(starts_with_ci( + Path::new(r"\\?\UNC\host\share\server\file.sql"), + Path::new(r"\\host\share\server") + )); + assert!(!starts_with_ci( + Path::new(r"\\?\D:\server\file.sql"), + Path::new(r"C:\server") + )); + assert!(!starts_with_ci( + Path::new(r"\\?\C:\server-other\file.sql"), + Path::new(r"C:\server") + )); + assert!(!starts_with_ci( + Path::new(r"\\?\UNC\host\other\server\file.sql"), + Path::new(r"\\host\share\server") + )); } #[cfg(windows)] diff --git a/crates/coa-core/src/manifest.rs b/crates/coa-core/src/manifest.rs index 0edf72f..a1c2697 100644 --- a/crates/coa-core/src/manifest.rs +++ b/crates/coa-core/src/manifest.rs @@ -165,21 +165,38 @@ impl Manifest { } if let Some(c) = &self.compatibility { if parse_version(&self.min_manager_version).is_none_or(|v| v < (0, 6, 13)) { - return bad("Release compatibility matrices require Manager 0.6.13 or newer".into()); + return bad( + "Release compatibility matrices require Manager 0.6.13 or newer".into(), + ); } - if c.schema != 1 || !matches!(c.platform.as_str(), "windows-x86_64" | "linux-x86_64") - || !is_commit(&c.core_commit) || self.core.commit.as_deref() != Some(&c.core_commit) - || c.module_commits.is_empty() || c.module_commits.values().any(|sha| !is_commit(sha)) - || self.bots.as_ref().and_then(|r| r.commit.as_ref()).is_some_and(|sha| c.module_commits.get("bots") != Some(sha)) + if c.schema != 1 + || !matches!(c.platform.as_str(), "windows-x86_64" | "linux-x86_64") + || !is_commit(&c.core_commit) + || self.core.commit.as_deref() != Some(&c.core_commit) + || c.module_commits.is_empty() + || c.module_commits.values().any(|sha| !is_commit(sha)) + || self + .bots + .as_ref() + .and_then(|r| r.commit.as_ref()) + .is_some_and(|sha| c.module_commits.get("bots") != Some(sha)) || parse_version(&c.client_patch_version).is_none() - || c.source_versions.is_empty() || c.source_versions.iter().any(|v| parse_version(v).is_none()) - || c.source_versions.iter().collect::>().len() != c.source_versions.len() { + || c.source_versions.is_empty() + || c.source_versions.iter().any(|v| parse_version(v).is_none()) + || c.source_versions.iter().collect::>().len() != c.source_versions.len() + { return bad("Invalid release compatibility matrix".into()); } - if !c.source_databases.is_empty() && (c.source_databases.len() != c.source_versions.len() - || c.source_versions.iter().any(|v| !c.source_databases.contains_key(v)) - || c.source_databases.values().any(|s| !is_sha256(&s.manifest_sha256) - || s.schema_sha256.as_ref().is_some_and(|sha| !is_sha256(sha)))) { + if !c.source_databases.is_empty() + && (c.source_databases.len() != c.source_versions.len() + || c.source_versions + .iter() + .any(|v| !c.source_databases.contains_key(v)) + || c.source_databases.values().any(|s| { + !is_sha256(&s.manifest_sha256) + || s.schema_sha256.as_ref().is_some_and(|sha| !is_sha256(sha)) + })) + { return bad("Invalid source database compatibility".into()); } } @@ -308,9 +325,15 @@ mod tests { fn compatibility_matrix_binds_core_and_requires_tested_sources() { let mut m = Manifest::parse(sample("").as_bytes()).unwrap(); m.min_manager_version = "0.6.13".into(); - m.compatibility = Some(Compatibility { schema: 1, platform: "windows-x86_64".into(), - core_commit: "a".repeat(40), module_commits: [("squid".into(), "b".repeat(40))].into(), - source_databases: Default::default(), client_patch_version: "1.5.1".into(), source_versions: vec!["0.261010.32".into()] }); + m.compatibility = Some(Compatibility { + schema: 1, + platform: "windows-x86_64".into(), + core_commit: "a".repeat(40), + module_commits: [("squid".into(), "b".repeat(40))].into(), + source_databases: Default::default(), + client_patch_version: "1.5.1".into(), + source_versions: vec!["0.261010.32".into()], + }); m.validate().unwrap(); m.compatibility.as_mut().unwrap().core_commit = "c".repeat(40); assert!(m.validate().is_err()); @@ -323,14 +346,30 @@ mod tests { fn compatibility_cannot_claim_a_different_packaged_bot_revision() { let mut m = Manifest::parse(sample("").as_bytes()).unwrap(); m.min_manager_version = "0.6.13".into(); - m.bots = Some(Revision { commit: Some("b".repeat(40)) }); - m.compatibility = Some(Compatibility { schema: 1, platform: "windows-x86_64".into(), - core_commit: "a".repeat(40), module_commits: [("bots".into(), "c".repeat(40))].into(), - source_databases: Default::default(), client_patch_version: "1.5.1".into(), source_versions: vec!["0.2.0".into()] }); + m.bots = Some(Revision { + commit: Some("b".repeat(40)), + }); + m.compatibility = Some(Compatibility { + schema: 1, + platform: "windows-x86_64".into(), + core_commit: "a".repeat(40), + module_commits: [("bots".into(), "c".repeat(40))].into(), + source_databases: Default::default(), + client_patch_version: "1.5.1".into(), + source_versions: vec!["0.2.0".into()], + }); assert!(m.validate().is_err()); - m.compatibility.as_mut().unwrap().module_commits.insert("bots".into(), "b".repeat(40)); + m.compatibility + .as_mut() + .unwrap() + .module_commits + .insert("bots".into(), "b".repeat(40)); m.validate().unwrap(); - m.compatibility.as_mut().unwrap().source_versions.push("0.2.0".into()); + m.compatibility + .as_mut() + .unwrap() + .source_versions + .push("0.2.0".into()); assert!(m.validate().is_err()); } @@ -338,12 +377,30 @@ mod tests { fn source_database_contracts_must_cover_the_exact_upgrade_versions() { let mut m = Manifest::parse(sample("").as_bytes()).unwrap(); m.min_manager_version = "0.6.13".into(); - m.compatibility = Some(Compatibility { schema: 1, platform: "windows-x86_64".into(), - core_commit: "a".repeat(40), module_commits: [("squid".into(), "b".repeat(40))].into(), - client_patch_version: "1.5.1".into(), source_versions: vec!["0.2.0".into()], - source_databases: [("0.2.0".into(), SourceDatabase { manifest_sha256: "a".repeat(64), schema_sha256: None })].into() }); + m.compatibility = Some(Compatibility { + schema: 1, + platform: "windows-x86_64".into(), + core_commit: "a".repeat(40), + module_commits: [("squid".into(), "b".repeat(40))].into(), + client_patch_version: "1.5.1".into(), + source_versions: vec!["0.2.0".into()], + source_databases: [( + "0.2.0".into(), + SourceDatabase { + manifest_sha256: "a".repeat(64), + schema_sha256: None, + }, + )] + .into(), + }); m.validate().unwrap(); - m.compatibility.as_mut().unwrap().source_databases.get_mut("0.2.0").unwrap().schema_sha256 = Some("bad".into()); + m.compatibility + .as_mut() + .unwrap() + .source_databases + .get_mut("0.2.0") + .unwrap() + .schema_sha256 = Some("bad".into()); assert!(m.validate().is_err()); let c = m.compatibility.as_mut().unwrap(); c.source_databases.get_mut("0.2.0").unwrap().schema_sha256 = None; diff --git a/crates/coa-core/src/migrations.rs b/crates/coa-core/src/migrations.rs index fe250e3..a6b3a23 100644 --- a/crates/coa-core/src/migrations.rs +++ b/crates/coa-core/src/migrations.rs @@ -101,8 +101,19 @@ impl Store for Db { let connection = self.clone().for_realm(crate::realms::Mode::Coa); let world = self.realm_schema("acore_world"); let characters = self.realm_schema("acore_characters"); - let others: Vec<_> = [crate::realms::Mode::Coa, crate::realms::Mode::Wildcard, crate::realms::Mode::Reborn].into_iter().filter(|m| *m != self.realm()).map(|m| m.schema("world").unwrap()).collect(); - let schemas: std::collections::BTreeSet<_> = [world, characters, AUTH_LEDGER_SCHEMA].into_iter().chain(others.iter().copied()).collect(); + let others: Vec<_> = [ + crate::realms::Mode::Coa, + crate::realms::Mode::Wildcard, + crate::realms::Mode::Reborn, + ] + .into_iter() + .filter(|m| *m != self.realm()) + .map(|m| m.schema("world").unwrap()) + .collect(); + let schemas: std::collections::BTreeSet<_> = [world, characters, AUTH_LEDGER_SCHEMA] + .into_iter() + .chain(others.iter().copied()) + .collect(); let catalog = connection.query(&format!("SELECT table_schema,table_name FROM information_schema.tables WHERE table_schema IN ('{}') AND table_name IN ('updates','{LEDGER_TABLE}') AND table_type='BASE TABLE';", schemas.into_iter().collect::>().join("','")))?; let available: std::collections::BTreeSet<_> = catalog .lines() @@ -120,7 +131,16 @@ impl Store for Db { queries.push(format!("SELECT 'core','{kind}',{},REPEAT('0',64),'applied',1,'' FROM `{schema}`.`updates` WHERE BINARY RIGHT(name,4)='.sql'",text("LEFT(name,CHAR_LENGTH(name)-4)"))); } } - for (origin, schema, filter) in [("local",world,""), ("shared",AUTH_LEDGER_SCHEMA,"")].into_iter().chain(others.iter().map(|schema| ("other", *schema, " WHERE `db` IN ('auth','coa-auth','wildcard-auth','reborn-auth')"))) { + for (origin, schema, filter) in [("local", world, ""), ("shared", AUTH_LEDGER_SCHEMA, "")] + .into_iter() + .chain(others.iter().map(|schema| { + ( + "other", + *schema, + " WHERE `db` IN ('auth','coa-auth','wildcard-auth','reborn-auth')", + ) + })) + { if available.contains(&(schema, LEDGER_TABLE)) { queries.push(format!("SELECT '{origin}',{},{},{},{},`baseline`,{} FROM `{schema}`.`{LEDGER_TABLE}`{filter}",text("`db`"),text("`id`"),text("`sha256`"),text("`status`"),text("COALESCE(HEX(`error`),'')"))); } diff --git a/crates/coa-core/src/modules.rs b/crates/coa-core/src/modules.rs index 3b63b9b..e1e0b30 100644 --- a/crates/coa-core/src/modules.rs +++ b/crates/coa-core/src/modules.rs @@ -173,7 +173,9 @@ fn installed_module_commits(root: &Path) -> BTreeMap { fn list_in(cat: &[Entry], root: &Path) -> Vec { let installed_commits = installed_module_commits(root); - let wildcard = crate::realms::state(root).map(|s| s.active != crate::realms::Mode::Coa).unwrap_or(true); + let wildcard = crate::realms::state(root) + .map(|s| s.active != crate::realms::Mode::Coa) + .unwrap_or(true); cat.iter() .cloned() .map(|e| { @@ -532,10 +534,17 @@ fn save_settings_in( )); } } - if id == "content-scaling" && key.starts_with("CoAContentScaling.Difficulty.Health.") && key.ends_with("Multiplier") { - let multiplier = value.parse::().map_err(|_| Error::Invalid("Health multipliers must be a number from 0.1 to 10.".into()))?; + if id == "content-scaling" + && key.starts_with("CoAContentScaling.Difficulty.Health.") + && key.ends_with("Multiplier") + { + let multiplier = value.parse::().map_err(|_| { + Error::Invalid("Health multipliers must be a number from 0.1 to 10.".into()) + })?; if !multiplier.is_finite() || !(0.1..=10.0).contains(&multiplier) { - return Err(Error::Invalid("Health multipliers must be a number from 0.1 to 10.".into())); + return Err(Error::Invalid( + "Health multipliers must be a number from 0.1 to 10.".into(), + )); } } if id == "content-scaling" && key == "CoAContentScaling.World.Leech.Percent" { @@ -1202,17 +1211,33 @@ mod tests { for key in keys { let changes = |v: &str| BTreeMap::from([(key.to_string(), v.to_string())]); for bad in ["NaN", "inf", "0", "0.09", "10.01", "-1", "abc", ""] { - assert!(save_settings_in(&cat, &root, &meta, "content-scaling", &changes(bad)).is_err(), "{key} {bad}"); + assert!( + save_settings_in(&cat, &root, &meta, "content-scaling", &changes(bad)).is_err(), + "{key} {bad}" + ); } for good in ["0.1", "0.4", "1", "2.5", "10"] { - assert_eq!(save_settings_in(&cat, &root, &meta, "content-scaling", &changes(good)).unwrap(), [key]); - assert_eq!(settings_in(&cat, &root, "content-scaling").unwrap().iter().find(|s| s.key == key).unwrap().value, good); + assert_eq!( + save_settings_in(&cat, &root, &meta, "content-scaling", &changes(good)) + .unwrap(), + [key] + ); + assert_eq!( + settings_in(&cat, &root, "content-scaling") + .unwrap() + .iter() + .find(|s| s.key == key) + .unwrap() + .value, + good + ); } } } #[test] - fn an_older_file_name_is_used_when_the_current_one_is_missing_and_a_part_that_cannot_be_switched_stays_on() { + fn an_older_file_name_is_used_when_the_current_one_is_missing_and_a_part_that_cannot_be_switched_stays_on( + ) { let d = tempfile::tempdir().unwrap(); let (root, meta) = server(d.path()); fs::write( diff --git a/crates/coa-core/src/multiworld.rs b/crates/coa-core/src/multiworld.rs index ba18bf8..5ec782d 100644 --- a/crates/coa-core/src/multiworld.rs +++ b/crates/coa-core/src/multiworld.rs @@ -62,8 +62,17 @@ pub fn set_enabled(main: &Path, enabled: bool) -> Result { )); } if enabled { - if realms::state(main)?.active == Mode::Reborn { return Err(Error::Invalid("Simultaneous startup supports CoA and Wildcard. Select one of these realms first.".into())); } - if !realms::view(main)?.supported { return Err(Error::Invalid("Update the server to a build with Wildcard support first.".into())); } + if realms::state(main)?.active == Mode::Reborn { + return Err(Error::Invalid( + "Simultaneous startup supports CoA and Wildcard. Select one of these realms first." + .into(), + )); + } + if !realms::view(main)?.supported { + return Err(Error::Invalid( + "Update the server to a build with Wildcard support first.".into(), + )); + } secondary_launcher(&fs::read_to_string(main.join("Scripts/manage.py"))?)?; } let status = process::observe(main, &crate::layout::read_ports(main)); diff --git a/crates/coa-core/src/mysql_snapshot.rs b/crates/coa-core/src/mysql_snapshot.rs index 2ec2fee..fc8ff56 100644 --- a/crates/coa-core/src/mysql_snapshot.rs +++ b/crates/coa-core/src/mysql_snapshot.rs @@ -1,7 +1,11 @@ -use std::{collections::{BTreeMap, BTreeSet}, fs, path::{Path, PathBuf}}; -use std::io::{BufReader, BufWriter, Write}; -use serde::{Deserialize, Serialize}; use crate::{fsx, Error, Result}; +use serde::{Deserialize, Serialize}; +use std::io::{BufReader, BufWriter, Write}; +use std::{ + collections::{BTreeMap, BTreeSet}, + fs, + path::{Path, PathBuf}, +}; #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(deny_unknown_fields)] @@ -20,8 +24,16 @@ pub(crate) struct Snapshot { fn reject_link(metadata: &fs::Metadata) -> Result<()> { let linked = metadata.file_type().is_symlink(); - #[cfg(windows)] let linked = { use std::os::windows::fs::MetadataExt; linked || metadata.file_attributes() & 0x400 != 0 }; - if linked { return Err(Error::Invalid("Recovery copies cannot follow symbolic links or junctions.".into())); } + #[cfg(windows)] + let linked = { + use std::os::windows::fs::MetadataExt; + linked || metadata.file_attributes() & 0x400 != 0 + }; + if linked { + return Err(Error::Invalid( + "Recovery copies cannot follow symbolic links or junctions.".into(), + )); + } Ok(()) } @@ -36,7 +48,11 @@ fn directories(root: &Path) -> Result> { reject_link(&fs::symlink_metadata(entry.path())?)?; let path = fsx::ensure_within(root, &entry.path())?; if entry.file_type()?.is_dir() { - let relative = path.strip_prefix(root).map_err(|e| Error::Invalid(e.to_string()))?.to_string_lossy().replace('\\', "/"); + let relative = path + .strip_prefix(root) + .map_err(|e| Error::Invalid(e.to_string()))? + .to_string_lossy() + .replace('\\', "/"); result.insert(relative); pending.push(path); } @@ -48,8 +64,14 @@ fn directories(root: &Path) -> Result> { fn copy_snapshot(point: &Path, snapshot: &Snapshot, target: &Path) -> Result<()> { if snapshot.archive_sha256.is_some() { verify(point, snapshot)?; - if target.exists() { return Err(Error::Invalid("The recovery destination already exists.".into())); } - let parent = target.parent().ok_or_else(|| Error::Invalid("Invalid recovery destination.".into()))?; + if target.exists() { + return Err(Error::Invalid( + "The recovery destination already exists.".into(), + )); + } + let parent = target + .parent() + .ok_or_else(|| Error::Invalid("Invalid recovery destination.".into()))?; fs::create_dir_all(parent)?; fsx::require_space(parent, snapshot.expanded_bytes)?; fs::create_dir(target)?; @@ -60,28 +82,60 @@ fn copy_snapshot(point: &Path, snapshot: &Snapshot, target: &Path) -> Result<()> let mut expanded = 0u64; for entry in archive.entries()? { let mut entry = entry?; - let name = entry.path()?.to_string_lossy().trim_end_matches('/').to_string(); - if !seen.insert(name.clone()) { return Err(Error::Invalid("Duplicate entry in MySQL recovery archive.".into())); } + let name = entry + .path()? + .to_string_lossy() + .trim_end_matches('/') + .to_string(); + if !seen.insert(name.clone()) { + return Err(Error::Invalid( + "Duplicate entry in MySQL recovery archive.".into(), + )); + } let output = fsx::ensure_within(target, &fsx::safe_join(target, &name)?)?; if entry.header().entry_type().is_dir() && snapshot.directories.contains(&name) { fs::create_dir_all(output)?; } else if entry.header().entry_type().is_file() && snapshot.files.contains_key(&name) { - expanded = expanded.checked_add(entry.size()).filter(|bytes| *bytes <= snapshot.expanded_bytes) - .ok_or_else(|| Error::Invalid("MySQL recovery archive exceeds its declared size.".into()))?; + expanded = expanded + .checked_add(entry.size()) + .filter(|bytes| *bytes <= snapshot.expanded_bytes) + .ok_or_else(|| { + Error::Invalid("MySQL recovery archive exceeds its declared size.".into()) + })?; fs::create_dir_all(output.parent().unwrap())?; - let mut file = fs::OpenOptions::new().write(true).create_new(true).open(output)?; - if std::io::copy(&mut entry, &mut file)? != entry.size() { return Err(Error::Invalid("Truncated MySQL recovery file.".into())); } + let mut file = fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(output)?; + if std::io::copy(&mut entry, &mut file)? != entry.size() { + return Err(Error::Invalid("Truncated MySQL recovery file.".into())); + } file.flush()?; - } else { return Err(Error::Invalid("Unexpected entry in MySQL recovery archive.".into())); } + } else { + return Err(Error::Invalid( + "Unexpected entry in MySQL recovery archive.".into(), + )); + } } if expanded != snapshot.expanded_bytes || inventory(target)? != snapshot.files { - return Err(Error::Invalid("MySQL recovery files failed verification.".into())); + return Err(Error::Invalid( + "MySQL recovery files failed verification.".into(), + )); } - } else { copy_verified(&point.join(&snapshot.path), target, &snapshot.files)?; } + } else { + copy_verified(&point.join(&snapshot.path), target, &snapshot.files)?; + } for directory in &snapshot.directories { - fs::create_dir_all(fsx::ensure_within(target, &fsx::safe_join(target, directory)?)?)?; + fs::create_dir_all(fsx::ensure_within( + target, + &fsx::safe_join(target, directory)?, + )?)?; + } + if directories(target)? != snapshot.directories { + return Err(Error::Invalid( + "The recovery directory inventory differs.".into(), + )); } - if directories(target)? != snapshot.directories { return Err(Error::Invalid("The recovery directory inventory differs.".into())); } Ok(()) } @@ -90,11 +144,17 @@ fn compress(source: &Path, point: &Path, snapshot: &mut Snapshot) -> Result<()> let path = fsx::safe_join(point, &snapshot.path)?; fs::create_dir_all(point)?; fsx::require_space(point, snapshot.expanded_bytes)?; - let file = fs::OpenOptions::new().write(true).create_new(true).open(&path)?; + let file = fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(&path)?; let encoder = zstd::Encoder::new(BufWriter::new(file), 3)?; let mut archive = tar::Builder::new(encoder); for directory in &snapshot.directories { - archive.append_dir(directory, fsx::ensure_within(source, &fsx::safe_join(source, directory)?)?)?; + archive.append_dir( + directory, + fsx::ensure_within(source, &fsx::safe_join(source, directory)?)?, + )?; } for name in snapshot.files.keys() { let input = fsx::ensure_within(source, &fsx::safe_join(source, name)?)?; @@ -117,24 +177,49 @@ pub(crate) fn inventory(root: &Path) -> Result> { let metadata = fs::symlink_metadata(entry.path())?; let path = fsx::ensure_within(root, &entry.path())?; reject_link(&metadata)?; - if metadata.is_dir() { directories.push(path); continue; } - if !metadata.is_file() { return Err(Error::Invalid("Unsupported database snapshot file.".into())); } - let relative = path.strip_prefix(root).map_err(|e| Error::Invalid(e.to_string()))?.to_string_lossy().replace('\\', "/"); + if metadata.is_dir() { + directories.push(path); + continue; + } + if !metadata.is_file() { + return Err(Error::Invalid("Unsupported database snapshot file.".into())); + } + let relative = path + .strip_prefix(root) + .map_err(|e| Error::Invalid(e.to_string()))? + .to_string_lossy() + .replace('\\', "/"); fsx::safe_join(root, &relative)?; - if relative.ends_with(".isl") { return Err(Error::Invalid("External MySQL tablespaces require a separate recovery method.".into())); } + if relative.ends_with(".isl") { + return Err(Error::Invalid( + "External MySQL tablespaces require a separate recovery method.".into(), + )); + } files.insert(relative, fsx::sha256_file(&path)?); } } Ok(files) } -pub(crate) fn copy_verified(source: &Path, target: &Path, files: &BTreeMap) -> Result<()> { - if target.exists() { return Err(Error::Invalid("Database snapshot destination already exists.".into())); } +pub(crate) fn copy_verified( + source: &Path, + target: &Path, + files: &BTreeMap, +) -> Result<()> { + if target.exists() { + return Err(Error::Invalid( + "Database snapshot destination already exists.".into(), + )); + } let bytes = files.keys().try_fold(0u64, |total, name| -> Result { let path = fsx::ensure_within(source, &fsx::safe_join(source, name)?)?; - total.checked_add(fs::metadata(path)?.len()).ok_or_else(|| Error::Invalid("Snapshot size overflow.".into())) + total + .checked_add(fs::metadata(path)?.len()) + .ok_or_else(|| Error::Invalid("Snapshot size overflow.".into())) })?; - let parent = target.parent().ok_or_else(|| Error::Invalid("Invalid snapshot destination.".into()))?; + let parent = target + .parent() + .ok_or_else(|| Error::Invalid("Invalid snapshot destination.".into()))?; fs::create_dir_all(parent)?; fsx::require_space(parent, bytes)?; fs::create_dir(target)?; @@ -143,56 +228,121 @@ pub(crate) fn copy_verified(source: &Path, target: &Path, files: &BTreeMap Result<()> { let observed = crate::process::observe(root, &crate::layout::read_ports(root)); - if [observed.mysql.state, observed.auth.state, observed.world.state].iter().all(|state| *state == crate::process::ServiceState::Stopped) - && !crate::multiworld::is_running(root) { return Ok(()); } - let outcome = crate::driver::run(root, crate::driver::Verb::StopAll) - .map_err(|error| Error::Invalid(format!("Could not stop server {} before copying or restoring MySQL: {error}", root.display())))?; + if [ + observed.mysql.state, + observed.auth.state, + observed.world.state, + ] + .iter() + .all(|state| *state == crate::process::ServiceState::Stopped) + && !crate::multiworld::is_running(root) + { + return Ok(()); + } + let outcome = crate::driver::run(root, crate::driver::Verb::StopAll).map_err(|error| { + Error::Invalid(format!( + "Could not stop server {} before copying or restoring MySQL: {error}", + root.display() + )) + })?; let status = crate::process::observe(root, &crate::layout::read_ports(root)); - if !outcome.ok || [status.mysql.state, status.auth.state, status.world.state].iter().any(|state| *state != crate::process::ServiceState::Stopped) - || crate::multiworld::is_running(root) { + if !outcome.ok + || [status.mysql.state, status.auth.state, status.world.state] + .iter() + .any(|state| *state != crate::process::ServiceState::Stopped) + || crate::multiworld::is_running(root) + { return Err(Error::Invalid(stop_failure(root, &status, &outcome))); } Ok(()) } -fn stop_failure(root: &Path, status: &crate::process::Observed, outcome: &crate::driver::DriverOutcome) -> String { - let mut details = vec![format!("The complete server must be stopped before copying or restoring MySQL. Server: {}.", root.display())]; - for service in [&status.mysql, &status.auth, &status.world].into_iter().chain(status.secondary_world.iter()) { +fn stop_failure( + root: &Path, + status: &crate::process::Observed, + outcome: &crate::driver::DriverOutcome, +) -> String { + let mut details = vec![format!( + "The complete server must be stopped before copying or restoring MySQL. Server: {}.", + root.display() + )]; + for service in [&status.mysql, &status.auth, &status.world] + .into_iter() + .chain(status.secondary_world.iter()) + { if service.state != crate::process::ServiceState::Stopped { - details.push(format!("{}: {:?}; PID: {}; port: {}.", service.name, service.state, service.pid.map(|pid| pid.to_string()).unwrap_or_else(|| "unknown".into()), service.port)); + details.push(format!( + "{}: {:?}; PID: {}; port: {}.", + service.name, + service.state, + service + .pid + .map(|pid| pid.to_string()) + .unwrap_or_else(|| "unknown".into()), + service.port + )); } if let Some(conflict) = &service.conflict { - details.push(format!("Port {} is used by process {} ({}).", conflict.port, conflict.pid, conflict.exe.as_deref().unwrap_or("executable unavailable"))); + details.push(format!( + "Port {} is used by process {} ({}).", + conflict.port, + conflict.pid, + conflict.exe.as_deref().unwrap_or("executable unavailable") + )); } } let output = crate::diag::redact(&outcome.output); let lines: Vec<_> = output.lines().rev().take(12).collect(); - if !lines.is_empty() { details.push(lines.into_iter().rev().collect::>().join("\n")); } - else if !outcome.ok { details.push(format!("The stop command failed (exit code: {:?}).", outcome.exit_code)); } + if !lines.is_empty() { + details.push(lines.into_iter().rev().collect::>().join("\n")); + } else if !outcome.ok { + details.push(format!( + "The stop command failed (exit code: {:?}).", + outcome.exit_code + )); + } details.join("\n") } pub(crate) fn stop_previous_rehearsals(meta: &Path) -> Result<()> { let location = meta.join("rehearsals"); - if !location.exists() { return Ok(()); } + if !location.exists() { + return Ok(()); + } for entry in fs::read_dir(&location)? { let entry = entry?; let name = entry.file_name().to_string_lossy().into_owned(); - if name.len() != 32 || !name.bytes().all(|byte| byte.is_ascii_hexdigit()) { continue; } + if name.len() != 32 || !name.bytes().all(|byte| byte.is_ascii_hexdigit()) { + continue; + } let fixture = fsx::ensure_within(&location, &entry.path().join("server"))?; let metadata = crate::registry::metadata_dir_for(&fixture)?; - if !metadata.join("install.json").is_file() { continue; } + if !metadata.join("install.json").is_file() { + continue; + } let (_, installed) = crate::registry::MetaDir::open(&metadata)?; - if fsx::canonicalize_lenient(Path::new(&installed.server_path))? != fsx::canonicalize_lenient(&fixture)? { - return Err(Error::Invalid("The interrupted rehearsal metadata does not match its private server.".into())); + if fsx::canonicalize_lenient(Path::new(&installed.server_path))? + != fsx::canonicalize_lenient(&fixture)? + { + return Err(Error::Invalid( + "The interrupted rehearsal metadata does not match its private server.".into(), + )); } stop(&fixture)?; } @@ -200,13 +350,26 @@ pub(crate) fn stop_previous_rehearsals(meta: &Path) -> Result<()> { } pub(crate) fn capture(root: &Path, partial: &Path) -> Result { - if crate::docker::is_docker(root) || !cfg!(windows) { return Err(Error::Invalid("Cold MySQL snapshots require a Windows repack.".into())); } + if crate::docker::is_docker(root) || !cfg!(windows) { + return Err(Error::Invalid( + "Cold MySQL snapshots require a Windows repack.".into(), + )); + } crate::backup::with_database(root, |db| { - if db.query("SELECT COUNT(*) FROM performance_schema.replication_connection_configuration;")?.trim() != "0" { - return Err(Error::Invalid("A replicated MySQL instance requires a separate isolated recovery method.".into())); + if db + .query("SELECT COUNT(*) FROM performance_schema.replication_connection_configuration;")? + .trim() + != "0" + { + return Err(Error::Invalid( + "A replicated MySQL instance requires a separate isolated recovery method.".into(), + )); } let data = fsx::ensure_within(root, &root.join("mysql/data"))?; - for path in db.query("SELECT PATH FROM information_schema.INNODB_DATAFILES;")?.lines() { + for path in db + .query("SELECT PATH FROM information_schema.INNODB_DATAFILES;")? + .lines() + { fsx::ensure_within(&data, &data.join(path))?; } Ok(()) @@ -214,13 +377,25 @@ pub(crate) fn capture(root: &Path, partial: &Path) -> Result { stop(root)?; let data = fsx::ensure_within(root, &root.join("mysql/data"))?; if !data.join("mysql").is_dir() || !data.join("ibdata1").is_file() { - return Err(Error::Invalid("The bundled MySQL data directory is incomplete.".into())); + return Err(Error::Invalid( + "The bundled MySQL data directory is incomplete.".into(), + )); } let files = inventory(&data)?; let bytes = files.keys().try_fold(0u64, |total, file| -> Result { - total.checked_add(fs::metadata(fsx::safe_join(&data, file)?)?.len()).ok_or_else(|| Error::Invalid("Snapshot size overflow.".into())) + total + .checked_add(fs::metadata(fsx::safe_join(&data, file)?)?.len()) + .ok_or_else(|| Error::Invalid("Snapshot size overflow.".into())) })?; - let mut snapshot = Snapshot { path: "mysql-data".into(), files, directories:directories(&data)?, server_sha256: fsx::sha256_file(&root.join("mysql/bin/mysqld.exe"))?, bytes, expanded_bytes:bytes, archive_sha256:None }; + let mut snapshot = Snapshot { + path: "mysql-data".into(), + files, + directories: directories(&data)?, + server_sha256: fsx::sha256_file(&root.join("mysql/bin/mysqld.exe"))?, + bytes, + expanded_bytes: bytes, + archive_sha256: None, + }; compress(&data, partial, &mut snapshot)?; verify(partial, &snapshot)?; Ok(snapshot) @@ -228,27 +403,54 @@ pub(crate) fn capture(root: &Path, partial: &Path) -> Result { pub(crate) fn verify(point: &Path, snapshot: &Snapshot) -> Result<()> { if snapshot.files.is_empty() || snapshot.server_sha256.len() != 64 { - return Err(Error::Invalid("Invalid cold MySQL recovery inventory.".into())); + return Err(Error::Invalid( + "Invalid cold MySQL recovery inventory.".into(), + )); } let data = fsx::ensure_within(point, &fsx::safe_join(point, &snapshot.path)?)?; if let Some(hash) = &snapshot.archive_sha256 { - if snapshot.path != "mysql-data.tar.zst" || snapshot.expanded_bytes == 0 || fsx::sha256_file(&data)? != *hash { - return Err(Error::Invalid("The compressed MySQL recovery copy is damaged.".into())); + if snapshot.path != "mysql-data.tar.zst" + || snapshot.expanded_bytes == 0 + || fsx::sha256_file(&data)? != *hash + { + return Err(Error::Invalid( + "The compressed MySQL recovery copy is damaged.".into(), + )); + } + for name in snapshot.files.keys().chain(snapshot.directories.iter()) { + fsx::safe_join(point, name)?; } - for name in snapshot.files.keys().chain(snapshot.directories.iter()) { fsx::safe_join(point, name)?; } return Ok(()); } - if snapshot.path != "mysql-data" { return Err(Error::Invalid("Unsupported MySQL recovery format.".into())); } - if inventory(&data)? != snapshot.files { return Err(Error::Invalid("The cold MySQL recovery copy is damaged or incomplete.".into())); } - if directories(&data)? != snapshot.directories { return Err(Error::Invalid("The cold MySQL recovery directories are incomplete.".into())); } + if snapshot.path != "mysql-data" { + return Err(Error::Invalid("Unsupported MySQL recovery format.".into())); + } + if inventory(&data)? != snapshot.files { + return Err(Error::Invalid( + "The cold MySQL recovery copy is damaged or incomplete.".into(), + )); + } + if directories(&data)? != snapshot.directories { + return Err(Error::Invalid( + "The cold MySQL recovery directories are incomplete.".into(), + )); + } Ok(()) } // Keep the replaced data directory. If interrupted between renames, a retry can install a new verified copy. -pub(crate) fn swap(root: &Path, meta: &Path, point: &Path, snapshot: &Snapshot, fail_after_move: bool) -> Result { +pub(crate) fn swap( + root: &Path, + meta: &Path, + point: &Path, + snapshot: &Snapshot, + fail_after_move: bool, +) -> Result { verify(point, snapshot)?; if fsx::sha256_file(&root.join("mysql/bin/mysqld.exe"))? != snapshot.server_sha256 { - return Err(Error::Invalid("The MySQL executable differs from the recovery point.".into())); + return Err(Error::Invalid( + "The MySQL executable differs from the recovery point.".into(), + )); } let mysql = fsx::ensure_within(root, &root.join("mysql"))?; let token = uuid::Uuid::new_v4().simple().to_string(); @@ -256,12 +458,26 @@ pub(crate) fn swap(root: &Path, meta: &Path, point: &Path, snapshot: &Snapshot, let previous = fsx::ensure_within(&mysql, &mysql.join(format!("data-before-restore-{token}")))?; let live = fsx::ensure_within(&mysql, &mysql.join("data"))?; copy_snapshot(point, snapshot, &staging)?; - let journal = meta.join("diagnostics").join(format!("database-restore-{token}.json")); - fsx::atomic_write_json(&journal, &serde_json::json!({"schema":1,"state":"prepared","previous":previous,"staging":staging}))?; - if live.exists() { fs::rename(&live, &previous)?; } - if fail_after_move { return Err(Error::Invalid("Simulated interruption after saving the previous MySQL directory.".into())); } + let journal = meta + .join("diagnostics") + .join(format!("database-restore-{token}.json")); + fsx::atomic_write_json( + &journal, + &serde_json::json!({"schema":1,"state":"prepared","previous":previous,"staging":staging}), + )?; + if live.exists() { + fs::rename(&live, &previous)?; + } + if fail_after_move { + return Err(Error::Invalid( + "Simulated interruption after saving the previous MySQL directory.".into(), + )); + } fs::rename(&staging, &live)?; - fsx::atomic_write_json(&journal, &serde_json::json!({"schema":1,"state":"restored","previous":previous}))?; + fsx::atomic_write_json( + &journal, + &serde_json::json!({"schema":1,"state":"restored","previous":previous}), + )?; Ok(previous) } @@ -270,12 +486,42 @@ mod tests { use super::*; #[test] fn failed_stop_identifies_the_server_process_and_retains_redacted_launcher_reason() { - use crate::process::{Observed, ServiceStatus, ServiceState}; - let stopped = |name| ServiceStatus { name, state: ServiceState::Stopped, pid: None, port: 0, port_ready: false, conflict: None, uptime_secs: None }; - let status = Observed { mysql: ServiceStatus { state: ServiceState::Stopping, pid: Some(42), port: 3307, ..stopped("mysql") }, auth: stopped("auth"), world: stopped("world"), secondary_world: None }; - let outcome = crate::driver::DriverOutcome { ok: false, exit_code: Some(1), code: None, human: None, output: "MySQL is still stopping; wait before copying the repack.\nrootPassword=hunter2".into() }; + use crate::process::{Observed, ServiceState, ServiceStatus}; + let stopped = |name| ServiceStatus { + name, + state: ServiceState::Stopped, + pid: None, + port: 0, + port_ready: false, + conflict: None, + uptime_secs: None, + }; + let status = Observed { + mysql: ServiceStatus { + state: ServiceState::Stopping, + pid: Some(42), + port: 3307, + ..stopped("mysql") + }, + auth: stopped("auth"), + world: stopped("world"), + secondary_world: None, + }; + let outcome = crate::driver::DriverOutcome { + ok: false, + exit_code: Some(1), + code: None, + human: None, + output: + "MySQL is still stopping; wait before copying the repack.\nrootPassword=hunter2" + .into(), + }; let message = stop_failure(Path::new("private-rehearsal/server"), &status, &outcome); - assert!(message.contains("private-rehearsal") && message.contains("PID: 42") && message.contains("3307")); + assert!( + message.contains("private-rehearsal") + && message.contains("PID: 42") + && message.contains("3307") + ); assert!(message.contains("MySQL is still stopping")); assert!(!message.contains("hunter2")); } @@ -283,61 +529,169 @@ mod tests { #[test] #[ignore = "requires COA_MYSQL_TEST_BIN pointing to a repack with Runtime/python and Scripts/manage.py"] fn real_shutdown_with_broken_templates_preserves_database_rows() { - use std::process::{Child, Command, Stdio}; use std::os::windows::process::CommandExt; + use std::process::{Child, Command, Stdio}; struct Server(Child); - impl Drop for Server { fn drop(&mut self) { let _ = self.0.kill(); let _ = self.0.wait(); } } + impl Drop for Server { + fn drop(&mut self) { + let _ = self.0.kill(); + let _ = self.0.wait(); + } + } let bin = PathBuf::from(std::env::var("COA_MYSQL_TEST_BIN").unwrap()); let source = bin.parent().unwrap().parent().unwrap(); let temp = tempfile::tempdir().unwrap(); let root = temp.path().join("shutdown-fixture"); copy_verified(&bin, &root.join("mysql/bin"), &inventory(&bin).unwrap()).unwrap(); - copy_verified(&source.join("Runtime/python"), &root.join("Runtime/python"), &inventory(&source.join("Runtime/python")).unwrap()).unwrap(); - fsx::atomic_write(&root.join("Scripts/manage.py"), &fs::read(source.join("Scripts/manage.py")).unwrap()).unwrap(); + copy_verified( + &source.join("Runtime/python"), + &root.join("Runtime/python"), + &inventory(&source.join("Runtime/python")).unwrap(), + ) + .unwrap(); + fsx::atomic_write( + &root.join("Scripts/manage.py"), + &fs::read(source.join("Scripts/manage.py")).unwrap(), + ) + .unwrap(); let data = root.join("mysql/data"); let executable = root.join("mysql/bin/mysqld.exe"); - let initialized = Command::new(&executable).args(["--no-defaults", "--initialize-insecure"]) - .arg(format!("--datadir={}", data.display())).creation_flags(0x0800_0000).output().unwrap(); - assert!(initialized.status.success(), "{}", String::from_utf8_lossy(&initialized.stderr)); - let sockets: Vec<_> = (0..4).map(|_| std::net::TcpListener::bind("127.0.0.1:0").unwrap()).collect(); - let ports: Vec<_> = sockets.iter().map(|socket| socket.local_addr().unwrap().port()).collect(); + let initialized = Command::new(&executable) + .args(["--no-defaults", "--initialize-insecure"]) + .arg(format!("--datadir={}", data.display())) + .creation_flags(0x0800_0000) + .output() + .unwrap(); + assert!( + initialized.status.success(), + "{}", + String::from_utf8_lossy(&initialized.stderr) + ); + let sockets: Vec<_> = (0..4) + .map(|_| std::net::TcpListener::bind("127.0.0.1:0").unwrap()) + .collect(); + let ports: Vec<_> = sockets + .iter() + .map(|socket| socket.local_addr().unwrap().port()) + .collect(); fsx::atomic_write_json(&root.join("Settings/repack.json"), &serde_json::json!({"mysqlPort":ports[0],"authPort":ports[1],"worldPort":ports[2],"raPort":ports[3]})).unwrap(); drop(sockets); - fsx::atomic_write_json(&root.join("Settings/database.json"), &serde_json::json!({"rootPassword":"","appPassword":""})).unwrap(); - fsx::atomic_write(&root.join("mysql/admin-client.ini"), format!("[client]\nuser=root\nhost=127.0.0.1\nport={}\nprotocol=tcp\n", ports[0]).as_bytes()).unwrap(); - fsx::atomic_write(&root.join("Settings/worldserver.conf.template"), b"WorldDatabaseInfo = @UNKNOWN_DATABASE@\n").unwrap(); + fsx::atomic_write_json( + &root.join("Settings/database.json"), + &serde_json::json!({"rootPassword":"","appPassword":""}), + ) + .unwrap(); + fsx::atomic_write( + &root.join("mysql/admin-client.ini"), + format!( + "[client]\nuser=root\nhost=127.0.0.1\nport={}\nprotocol=tcp\n", + ports[0] + ) + .as_bytes(), + ) + .unwrap(); + fsx::atomic_write( + &root.join("Settings/worldserver.conf.template"), + b"WorldDatabaseInfo = @UNKNOWN_DATABASE@\n", + ) + .unwrap(); let original = fs::read(root.join("Settings/worldserver.conf.template")).unwrap(); let db = crate::db::Db::from_repack(&root, crate::db::Account::Admin).unwrap(); let start = || { - let server = Server(Command::new(&executable).args(["--no-defaults", "--bind-address=127.0.0.1", "--mysqlx=0", "--skip-log-bin"]) - .arg(format!("--datadir={}", data.display())).arg(format!("--port={}", ports[0])) - .arg(format!("--log-error={}", root.join("mysql-test.log").display())) - .stdout(Stdio::null()).stderr(Stdio::null()).creation_flags(0x0800_0000).spawn().unwrap()); + let server = Server( + Command::new(&executable) + .args([ + "--no-defaults", + "--bind-address=127.0.0.1", + "--mysqlx=0", + "--skip-log-bin", + ]) + .arg(format!("--datadir={}", data.display())) + .arg(format!("--port={}", ports[0])) + .arg(format!( + "--log-error={}", + root.join("mysql-test.log").display() + )) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .creation_flags(0x0800_0000) + .spawn() + .unwrap(), + ); let deadline = std::time::Instant::now() + std::time::Duration::from_secs(60); - while !db.ping() { assert!(std::time::Instant::now() < deadline); std::thread::sleep(std::time::Duration::from_millis(200)); } - fsx::atomic_write_json(&root.join(".state/mysql.json"), &crate::process::identity(server.0.id()).unwrap()).unwrap(); + while !db.ping() { + assert!(std::time::Instant::now() < deadline); + std::thread::sleep(std::time::Duration::from_millis(200)); + } + fsx::atomic_write_json( + &root.join(".state/mysql.json"), + &crate::process::identity(server.0.id()).unwrap(), + ) + .unwrap(); server }; let mut server = start(); db.query("CREATE DATABASE acore_characters; CREATE TABLE acore_characters.shutdown_probe(id INT PRIMARY KEY); INSERT INTO acore_characters.shutdown_probe VALUES(73);").unwrap(); db.query("CREATE DATABASE acore_auth; CREATE DATABASE acore_world; CREATE VIEW acore_characters.shutdown_view AS SELECT id FROM acore_characters.shutdown_probe;").unwrap(); let copied_configuration = serde_json::json!({"root":temp.path().join("original-installation"),"ports":{"mysqlPort":ports[0],"authPort":ports[1],"worldPort":ports[2],"raPort":ports[3]}}); - fsx::atomic_write_json(&root.join(".state/configuration.json"), &copied_configuration).unwrap(); + fsx::atomic_write_json( + &root.join(".state/configuration.json"), + &copied_configuration, + ) + .unwrap(); let meta = crate::registry::metadata_dir_for(&root).unwrap(); - crate::registry::MetaDir::create(&root, &crate::registry::InstallMeta::new(crate::registry::InstallKind::New, &root)).unwrap(); - let point = crate::backup::create(&root, &meta, crate::backup::Kind::Full, crate::backup::Trigger::BeforeRepair, None, &|_| {}).unwrap(); + crate::registry::MetaDir::create( + &root, + &crate::registry::InstallMeta::new(crate::registry::InstallKind::New, &root), + ) + .unwrap(); + let point = crate::backup::create( + &root, + &meta, + crate::backup::Kind::Full, + crate::backup::Trigger::BeforeRepair, + None, + &|_| {}, + ) + .unwrap(); assert!(point.mysql_snapshot.is_some()); assert!(crate::backup::verify(&meta, &point.id).unwrap().ok); - crate::update::RepackEnv { root: &root, meta_dir: &meta }.verify_recovery_point(&point).unwrap(); + crate::update::RepackEnv { + root: &root, + meta_dir: &meta, + } + .verify_recovery_point(&point) + .unwrap(); assert!(server.0.wait().unwrap().success()); - assert_eq!(fs::read(root.join("Settings/worldserver.conf.template")).unwrap(), original); - assert_eq!(fsx::read_json::(&root.join(".state/configuration.json")).unwrap(), copied_configuration); + assert_eq!( + fs::read(root.join("Settings/worldserver.conf.template")).unwrap(), + original + ); + assert_eq!( + fsx::read_json::(&root.join(".state/configuration.json")).unwrap(), + copied_configuration + ); fs::remove_file(root.join(".state/configuration.json")).unwrap(); let mut restarted = start(); - assert_eq!(db.query("SELECT id FROM acore_characters.shutdown_probe;").unwrap(), "73"); - fsx::atomic_write_json(&root.join(".state/mysql.json"), &crate::process::identity(std::process::id()).unwrap()).unwrap(); - assert!(stop(&root).unwrap_err().to_string().contains("different live process")); - assert_eq!(db.query("SELECT id FROM acore_characters.shutdown_probe;").unwrap(), "73"); + assert_eq!( + db.query("SELECT id FROM acore_characters.shutdown_probe;") + .unwrap(), + "73" + ); + fsx::atomic_write_json( + &root.join(".state/mysql.json"), + &crate::process::identity(std::process::id()).unwrap(), + ) + .unwrap(); + assert!(stop(&root) + .unwrap_err() + .to_string() + .contains("different live process")); + assert_eq!( + db.query("SELECT id FROM acore_characters.shutdown_probe;") + .unwrap(), + "73" + ); fs::remove_file(root.join("Settings/worldserver.conf.template")).unwrap(); fs::remove_file(root.join(".state/mysql.json")).unwrap(); let observed = crate::process::observe(&root, &crate::layout::read_ports(&root)); @@ -347,31 +701,76 @@ mod tests { stop(&root).unwrap(); assert!(restarted.0.wait().unwrap().success()); let mut third = start(); - assert_eq!(db.query("SELECT id FROM acore_characters.shutdown_view;").unwrap(), "73"); - db.query("UPDATE acore_characters.shutdown_probe SET id=74;").unwrap(); + assert_eq!( + db.query("SELECT id FROM acore_characters.shutdown_view;") + .unwrap(), + "73" + ); + db.query("UPDATE acore_characters.shutdown_probe SET id=74;") + .unwrap(); fsx::atomic_write(&root.join(".state/mysql.json"), b"{truncated").unwrap(); stop(&root).unwrap(); assert!(third.0.wait().unwrap().success()); - assert_eq!(fs::read(root.join(".state/mysql-before-shutdown-recovery.json")).unwrap(), b"{truncated"); - let point_dir = crate::backup::point_json(&meta, &point.id).unwrap().parent().unwrap().to_path_buf(); - let retained = swap(&root, &meta, &point_dir, point.mysql_snapshot.as_ref().unwrap(), false).unwrap(); + assert_eq!( + fs::read(root.join(".state/mysql-before-shutdown-recovery.json")).unwrap(), + b"{truncated" + ); + let point_dir = crate::backup::point_json(&meta, &point.id) + .unwrap() + .parent() + .unwrap() + .to_path_buf(); + let retained = swap( + &root, + &meta, + &point_dir, + point.mysql_snapshot.as_ref().unwrap(), + false, + ) + .unwrap(); assert!(retained.is_dir()); let mut recovered = start(); - assert_eq!(db.query("SELECT id FROM acore_characters.shutdown_view;").unwrap(), "73"); + assert_eq!( + db.query("SELECT id FROM acore_characters.shutdown_view;") + .unwrap(), + "73" + ); stop(&root).unwrap(); assert!(recovered.0.wait().unwrap().success()); // Exercise the public Repair pipeline with real signed packages and SQL, // rather than only the snapshot and journal helpers. let mut package_server = start(); db.query("CREATE TABLE acore_auth.account(id INT PRIMARY KEY, username VARCHAR(40)); INSERT INTO acore_auth.account VALUES(73,'FIXTURE'); CREATE TABLE acore_auth.realmlist(id INT PRIMARY KEY, name VARCHAR(40), address VARCHAR(40), localAddress VARCHAR(40), port INT, flag INT); INSERT INTO acore_auth.realmlist VALUES(1,'AzerothCore','127.0.0.1','127.0.0.1',18085,0); CREATE TABLE acore_characters.characters(guid INT PRIMARY KEY, account INT, name VARCHAR(40), race INT, class INT); INSERT INTO acore_characters.characters VALUES(73,73,'Fixture',7,14); CREATE TABLE acore_world.playercreateinfo(race INT, class INT, PRIMARY KEY(race,class));").unwrap(); - let starts = [1,2,3,4,5,6,7,8,10,11].into_iter().flat_map(|race| (12..=32).map(move |class| format!("({race},{class})"))).collect::>().join(","); - db.query(&format!("INSERT INTO acore_world.playercreateinfo VALUES {starts};")).unwrap(); + let starts = [1, 2, 3, 4, 5, 6, 7, 8, 10, 11] + .into_iter() + .flat_map(|race| (12..=32).map(move |class| format!("({race},{class})"))) + .collect::>() + .join(","); + db.query(&format!( + "INSERT INTO acore_world.playercreateinfo VALUES {starts};" + )) + .unwrap(); let password = "a".repeat(48); - db.query(&format!("ALTER USER 'root'@'localhost' IDENTIFIED BY '{password}';")).unwrap(); - fsx::atomic_write_json(&root.join("Settings/database.json"), &serde_json::json!({"rootPassword":password,"appPassword":"b".repeat(48)})).unwrap(); + db.query(&format!( + "ALTER USER 'root'@'localhost' IDENTIFIED BY '{password}';" + )) + .unwrap(); + fsx::atomic_write_json( + &root.join("Settings/database.json"), + &serde_json::json!({"rootPassword":password,"appPassword":"b".repeat(48)}), + ) + .unwrap(); fsx::atomic_write(&root.join("Settings/worldserver.conf.template"), b"WorldDatabaseInfo = @WorldDatabaseInfo@\nCharacterDatabaseInfo = @CharacterDatabaseInfo@\nLoginDatabaseInfo = @LoginDatabaseInfo@\n").unwrap(); - fsx::atomic_write(&root.join("Settings/authserver.conf.template"), b"LoginDatabaseInfo = @LoginDatabaseInfo@\n").unwrap(); - fsx::atomic_write(&root.join("Settings/mod_ascension_compat.conf.template"), b"Ascension.DbcPath = @ASCENSION_DBC@\n").unwrap(); + fsx::atomic_write( + &root.join("Settings/authserver.conf.template"), + b"LoginDatabaseInfo = @LoginDatabaseInfo@\n", + ) + .unwrap(); + fsx::atomic_write( + &root.join("Settings/mod_ascension_compat.conf.template"), + b"Ascension.DbcPath = @ASCENSION_DBC@\n", + ) + .unwrap(); let startup = crate::driver::run(&root, crate::driver::Verb::StartMysql).unwrap(); assert!(startup.ok, "{}", crate::diag::redact(&startup.output)); let db = crate::db::Db::from_repack(&root, crate::db::Account::Admin).unwrap(); @@ -380,19 +779,45 @@ mod tests { stop(&root).unwrap(); assert!(package_server.0.wait().unwrap().success()); struct StopFixture(PathBuf); - impl Drop for StopFixture { fn drop(&mut self) { let _ = stop(&self.0); } } + impl Drop for StopFixture { + fn drop(&mut self) { + let _ = stop(&self.0); + } + } let _stop_fixture = StopFixture(root.clone()); use base64::{engine::general_purpose::STANDARD, Engine}; use ed25519_dalek::{Signer, SigningKey}; - let key = SigningKey::from_bytes(&[7;32]); + let key = SigningKey::from_bytes(&[7; 32]); let trusted = STANDARD.encode(key.verifying_key().to_bytes()); let source = temp.path().join("repair-package-source"); fsx::atomic_write(&source.join("Core/reference/repair-probe.dll"), b"official").unwrap(); - fsx::atomic_write(&source.join(crate::schema_check::CONTRACT), &fs::read(root.join(crate::schema_check::CONTRACT)).unwrap()).unwrap(); + fsx::atomic_write( + &source.join(crate::schema_check::CONTRACT), + &fs::read(root.join(crate::schema_check::CONTRACT)).unwrap(), + ) + .unwrap(); let build = |kind, version: &str, destination: &Path, migrations| { - let manifest = crate::package::build(&source, destination, &crate::package::BuildOptions { kind, version: version.into(), core_commit: None, built_at: "fixture".into(), part_size: 1024*1024, bots_commit: None, migrations }, &|_| {}).unwrap(); + let manifest = crate::package::build( + &source, + destination, + &crate::package::BuildOptions { + kind, + version: version.into(), + core_commit: None, + built_at: "fixture".into(), + part_size: 1024 * 1024, + bots_commit: None, + migrations, + }, + &|_| {}, + ) + .unwrap(); let bytes = fs::read(destination.join("manifest.json")).unwrap(); - fsx::atomic_write(&destination.join("manifest.json.sig"), STANDARD.encode(key.sign(&bytes).to_bytes()).as_bytes()).unwrap(); + fsx::atomic_write( + &destination.join("manifest.json.sig"), + STANDARD.encode(key.sign(&bytes).to_bytes()).as_bytes(), + ) + .unwrap(); manifest }; let base = temp.path().join("repair-base"); @@ -400,34 +825,97 @@ mod tests { let update = temp.path().join("repair-update"); let update_manifest = build(crate::manifest::Kind::Update, "2.0.0", &update, vec![]); fsx::atomic_write_json(&meta.join("manifests/base.json"), &base_manifest).unwrap(); - fsx::atomic_write_json(&meta.join("manifests/update-2.0.0.json"), &update_manifest).unwrap(); + fsx::atomic_write_json(&meta.join("manifests/update-2.0.0.json"), &update_manifest) + .unwrap(); let (_, mut installed) = crate::registry::MetaDir::open(&meta).unwrap(); installed.core.version = Some("2.0.0".into()); fsx::atomic_write_json(&meta.join("install.json"), &installed).unwrap(); fsx::atomic_write(&root.join("Core/reference/repair-probe.dll"), b"broken").unwrap(); let base_source = crate::pkgsource::Source::Dir(base); let update_source = crate::pkgsource::Source::Dir(update); - let report = crate::repair::run(&root, &meta, &base_source, &update_source, &trusted, &|_,_| {}).unwrap(); + let report = crate::repair::run( + &root, + &meta, + &base_source, + &update_source, + &trusted, + &|_, _| {}, + ) + .unwrap(); assert!(report.error.is_none()); - assert!(report.database.iter().all(|check| check.problems.is_empty())); - assert_eq!(fs::read(root.join("Core/reference/repair-probe.dll")).unwrap(), b"official"); + assert!(report + .database + .iter() + .all(|check| check.problems.is_empty())); + assert_eq!( + fs::read(root.join("Core/reference/repair-probe.dll")).unwrap(), + b"official" + ); crate::update::ensure_recovered(&meta).unwrap(); - fsx::atomic_write(&root.join("Core/reference/repair-probe.dll"), b"before verification failure").unwrap(); - let error = crate::repair::run(&root, &meta, &base_source, &update_source, &trusted, &|phase,_| { - if phase == "Checking database after repair" { fs::remove_file(root.join("Core/reference/repair-probe.dll")).unwrap(); } - }).unwrap_err(); + fsx::atomic_write( + &root.join("Core/reference/repair-probe.dll"), + b"before verification failure", + ) + .unwrap(); + let error = crate::repair::run( + &root, + &meta, + &base_source, + &update_source, + &trusted, + &|phase, _| { + if phase == "Checking database after repair" { + fs::remove_file(root.join("Core/reference/repair-probe.dll")).unwrap(); + } + }, + ) + .unwrap_err(); assert!(error.to_string().contains("repair")); - assert_eq!(fs::read(root.join("Core/reference/repair-probe.dll")).unwrap(), b"before verification failure"); + assert_eq!( + fs::read(root.join("Core/reference/repair-probe.dll")).unwrap(), + b"before verification failure" + ); crate::update::ensure_recovered(&meta).unwrap(); - let failed_sql = "UPDATE shutdown_probe SET id=75; CREATE TABLE repair_partial(id INT); INVALID SQL;"; - fsx::atomic_write(&source.join("_migrations/characters/repair-failure.sql"), failed_sql.as_bytes()).unwrap(); + let failed_sql = + "UPDATE shutdown_probe SET id=75; CREATE TABLE repair_partial(id INT); INVALID SQL;"; + fsx::atomic_write( + &source.join("_migrations/characters/repair-failure.sql"), + failed_sql.as_bytes(), + ) + .unwrap(); let failing = temp.path().join("repair-failing-update"); - let manifest = build(crate::manifest::Kind::Update, "2.0.0", &failing, vec![crate::manifest::Migration { id:"repair-failure".into(), db:"characters".into(), sha256:fsx::sha256_bytes(failed_sql.as_bytes()), compatible_sha256:vec![], destructive:false }]); + let manifest = build( + crate::manifest::Kind::Update, + "2.0.0", + &failing, + vec![crate::manifest::Migration { + id: "repair-failure".into(), + db: "characters".into(), + sha256: fsx::sha256_bytes(failed_sql.as_bytes()), + compatible_sha256: vec![], + destructive: false, + }], + ); fsx::atomic_write_json(&meta.join("manifests/update-2.0.0.json"), &manifest).unwrap(); - fsx::atomic_write(&root.join("Core/reference/repair-probe.dll"), b"before failed repair").unwrap(); - let report = crate::repair::run(&root, &meta, &base_source, &crate::pkgsource::Source::Dir(failing), &trusted, &|_,_| {}).unwrap(); + fsx::atomic_write( + &root.join("Core/reference/repair-probe.dll"), + b"before failed repair", + ) + .unwrap(); + let report = crate::repair::run( + &root, + &meta, + &base_source, + &crate::pkgsource::Source::Dir(failing), + &trusted, + &|_, _| {}, + ) + .unwrap(); assert!(report.error.is_some()); - assert_eq!(fs::read(root.join("Core/reference/repair-probe.dll")).unwrap(), b"before failed repair"); + assert_eq!( + fs::read(root.join("Core/reference/repair-probe.dll")).unwrap(), + b"before failed repair" + ); crate::update::ensure_recovered(&meta).unwrap(); crate::backup::with_database(&root, |db| { assert_eq!(db.query("SELECT id FROM acore_characters.shutdown_view;")?, "73"); @@ -441,10 +929,15 @@ mod tests { #[test] #[ignore = "requires COA_MYSQL_TEST_BIN pointing to the bundled MySQL tools"] fn real_mysql_restores_objects_users_rows_and_missing_defaults() { - use std::process::{Child, Command, Stdio}; use std::os::windows::process::CommandExt; + use std::process::{Child, Command, Stdio}; struct Server(Child); - impl Drop for Server { fn drop(&mut self) { let _ = self.0.kill(); let _ = self.0.wait(); } } + impl Drop for Server { + fn drop(&mut self) { + let _ = self.0.kill(); + let _ = self.0.wait(); + } + } let bin = PathBuf::from(std::env::var("COA_MYSQL_TEST_BIN").unwrap()); let temp = tempfile::tempdir().unwrap(); let root = temp.path().join("server"); @@ -453,20 +946,59 @@ mod tests { copy_verified(&bin, &root.join("mysql/bin"), &inventory(&bin).unwrap()).unwrap(); let data = root.join("mysql/data"); let executable = root.join("mysql/bin/mysqld.exe"); - let initialized = Command::new(&executable).args(["--no-defaults", "--initialize-insecure"]) - .arg(format!("--datadir={}", data.display())).creation_flags(0x0800_0000).output().unwrap(); - assert!(initialized.status.success(), "{}", String::from_utf8_lossy(&initialized.stderr)); + let initialized = Command::new(&executable) + .args(["--no-defaults", "--initialize-insecure"]) + .arg(format!("--datadir={}", data.display())) + .creation_flags(0x0800_0000) + .output() + .unwrap(); + assert!( + initialized.status.success(), + "{}", + String::from_utf8_lossy(&initialized.stderr) + ); let port = crate::install::free_port().unwrap(); - fsx::atomic_write_json(&root.join("Settings/repack.json"), &serde_json::json!({"mysqlPort":port})).unwrap(); - fsx::atomic_write_json(&root.join("Settings/database.json"), &serde_json::json!({"rootPassword":"","appPassword":""})).unwrap(); + fsx::atomic_write_json( + &root.join("Settings/repack.json"), + &serde_json::json!({"mysqlPort":port}), + ) + .unwrap(); + fsx::atomic_write_json( + &root.join("Settings/database.json"), + &serde_json::json!({"rootPassword":"","appPassword":""}), + ) + .unwrap(); let db = crate::db::Db::from_repack(&root, crate::db::Account::Admin).unwrap(); let start = || { - let server = Server(Command::new(&executable).args(["--no-defaults", "--bind-address=127.0.0.1", "--mysqlx=0", "--skip-log-bin"]) - .arg(format!("--datadir={}", data.display())).arg(format!("--port={port}")) - .arg(format!("--log-error={}", root.join("mysql-test.log").display())) - .stdout(Stdio::null()).stderr(Stdio::null()).creation_flags(0x0800_0000).spawn().unwrap()); + let server = Server( + Command::new(&executable) + .args([ + "--no-defaults", + "--bind-address=127.0.0.1", + "--mysqlx=0", + "--skip-log-bin", + ]) + .arg(format!("--datadir={}", data.display())) + .arg(format!("--port={port}")) + .arg(format!( + "--log-error={}", + root.join("mysql-test.log").display() + )) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .creation_flags(0x0800_0000) + .spawn() + .unwrap(), + ); let deadline = std::time::Instant::now() + std::time::Duration::from_secs(60); - while !db.ping() { assert!(std::time::Instant::now() < deadline, "{}", fs::read_to_string(root.join("mysql-test.log")).unwrap_or_default()); std::thread::sleep(std::time::Duration::from_millis(200)); } + while !db.ping() { + assert!( + std::time::Instant::now() < deadline, + "{}", + fs::read_to_string(root.join("mysql-test.log")).unwrap_or_default() + ); + std::thread::sleep(std::time::Duration::from_millis(200)); + } server }; let mut server = start(); @@ -479,73 +1011,184 @@ mod tests { fs::create_dir_all(migration_dir.join("world")).unwrap(); let auth_sql = b"INSERT INTO acore_auth.probe VALUES(45);"; fs::write(migration_dir.join("auth/shared_once.sql"), auth_sql).unwrap(); - let auth_list = vec![crate::manifest::Migration { id:"shared_once".into(), db:"auth".into(), sha256:fsx::sha256_bytes(auth_sql), destructive:false, compatible_sha256:vec![] }]; - assert_eq!(crate::migrations::apply_pending(&db, &auth_list, &migration_dir, &|| Ok("fixture".into())).unwrap().applied.len(), 1); + let auth_list = vec![crate::manifest::Migration { + id: "shared_once".into(), + db: "auth".into(), + sha256: fsx::sha256_bytes(auth_sql), + destructive: false, + compatible_sha256: vec![], + }]; + assert_eq!( + crate::migrations::apply_pending(&db, &auth_list, &migration_dir, &|| Ok( + "fixture".into() + )) + .unwrap() + .applied + .len(), + 1 + ); let wildcard = db.clone().for_realm(crate::realms::Mode::Wildcard); - assert_eq!(crate::migrations::pending_count(&wildcard, &auth_list).unwrap(), 0, "auth is shared by both realms"); - assert!(crate::migrations::apply_pending(&wildcard, &auth_list, &migration_dir, &|| Ok("fixture".into())).unwrap().applied.is_empty()); - assert_eq!(db.query("SELECT COUNT(*) FROM acore_auth.probe WHERE id=45;").unwrap(), "1"); - let mut failed = crate::migrations::LedgerRow { db:"auth".into(), id:"shared_once".into(), sha256:auth_list[0].sha256.clone(), status:crate::migrations::Status::Failed, error:Some("interrupted fixture".into()), baseline:false }; + assert_eq!( + crate::migrations::pending_count(&wildcard, &auth_list).unwrap(), + 0, + "auth is shared by both realms" + ); + assert!( + crate::migrations::apply_pending(&wildcard, &auth_list, &migration_dir, &|| Ok( + "fixture".into() + )) + .unwrap() + .applied + .is_empty() + ); + assert_eq!( + db.query("SELECT COUNT(*) FROM acore_auth.probe WHERE id=45;") + .unwrap(), + "1" + ); + let mut failed = crate::migrations::LedgerRow { + db: "auth".into(), + id: "shared_once".into(), + sha256: auth_list[0].sha256.clone(), + status: crate::migrations::Status::Failed, + error: Some("interrupted fixture".into()), + baseline: false, + }; db.put(&failed).unwrap(); assert!(crate::migrations::pending_count(&wildcard, &auth_list).is_err()); - failed.status = crate::migrations::Status::Applied; failed.error = None; db.put(&failed).unwrap(); - + failed.status = crate::migrations::Status::Applied; + failed.error = None; + db.put(&failed).unwrap(); // Legacy per-world auth records are adopted without replaying their SQL. let legacy_sql = b"INSERT INTO acore_auth.probe VALUES(46);"; fs::write(migration_dir.join("auth/legacy_auth.sql"), legacy_sql).unwrap(); db.query(&format!("INSERT INTO acore_auth.probe VALUES(46); REPLACE INTO acore_world.coa_manager_migrations VALUES('auth','legacy_auth','{}','applied',NOW(),NULL,0);", fsx::sha256_bytes(legacy_sql))).unwrap(); - let legacy_auth = vec![crate::manifest::Migration { id:"legacy_auth".into(), db:"auth".into(), sha256:fsx::sha256_bytes(legacy_sql), destructive:false, compatible_sha256:vec![] }]; - assert_eq!(crate::migrations::pending_count(&wildcard, &legacy_auth).unwrap(), 0); - assert!(crate::migrations::apply_pending(&wildcard, &legacy_auth, &migration_dir, &|| Ok("fixture".into())).unwrap().applied.is_empty()); - assert_eq!(db.query("SELECT COUNT(*) FROM acore_auth.probe WHERE id=46;").unwrap(), "1"); + let legacy_auth = vec![crate::manifest::Migration { + id: "legacy_auth".into(), + db: "auth".into(), + sha256: fsx::sha256_bytes(legacy_sql), + destructive: false, + compatible_sha256: vec![], + }]; + assert_eq!( + crate::migrations::pending_count(&wildcard, &legacy_auth).unwrap(), + 0 + ); + assert!( + crate::migrations::apply_pending(&wildcard, &legacy_auth, &migration_dir, &|| Ok( + "fixture".into() + )) + .unwrap() + .applied + .is_empty() + ); + assert_eq!( + db.query("SELECT COUNT(*) FROM acore_auth.probe WHERE id=46;") + .unwrap(), + "1" + ); // A core history cleanup cannot make previously recorded SQL pending again. db.query("CREATE TABLE acore_world.updates(name VARCHAR(150) PRIMARY KEY) DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; INSERT INTO acore_world.updates VALUES('LEGACY_WORLD.sql'); INSERT INTO acore_world.probe VALUES(99);").unwrap(); db.load().unwrap(); db.query("DROP TABLE acore_world.updates;").unwrap(); let legacy_world_sql = b"INSERT INTO acore_world.probe VALUES(99);"; - fs::write(migration_dir.join("world/legacy_world.sql"), legacy_world_sql).unwrap(); - let legacy_world = vec![crate::manifest::Migration { id:"legacy_world".into(), db:"world".into(), sha256:fsx::sha256_bytes(legacy_world_sql), destructive:false, compatible_sha256:vec![] }]; - assert_eq!(crate::migrations::pending_count(&db, &legacy_world).unwrap(), 0); - assert!(crate::migrations::apply_pending(&db, &legacy_world, &migration_dir, &|| Ok("fixture".into())).unwrap().applied.is_empty()); - assert_eq!(db.query("SELECT COUNT(*) FROM acore_world.probe WHERE id=99;").unwrap(), "1"); - db.query("DELETE FROM acore_world.probe WHERE id=99;").unwrap(); + fs::write( + migration_dir.join("world/legacy_world.sql"), + legacy_world_sql, + ) + .unwrap(); + let legacy_world = vec![crate::manifest::Migration { + id: "legacy_world".into(), + db: "world".into(), + sha256: fsx::sha256_bytes(legacy_world_sql), + destructive: false, + compatible_sha256: vec![], + }]; + assert_eq!( + crate::migrations::pending_count(&db, &legacy_world).unwrap(), + 0 + ); + assert!( + crate::migrations::apply_pending(&db, &legacy_world, &migration_dir, &|| Ok( + "fixture".into() + )) + .unwrap() + .applied + .is_empty() + ); + assert_eq!( + db.query("SELECT COUNT(*) FROM acore_world.probe WHERE id=99;") + .unwrap(), + "1" + ); + db.query("DELETE FROM acore_world.probe WHERE id=99;") + .unwrap(); assert_eq!(db.recovery_objects("acore_characters").unwrap().len(), 4); db.query("CREATE TABLE acore_characters.coa_squid_pending(path VARCHAR(255), sha256 CHAR(64)); INSERT INTO acore_characters.coa_squid_pending VALUES('playerbots/base/ai_playerbot_texts.sql', REPEAT('a',64));").unwrap(); - let squid_problems = crate::squid::database_problems(&root, crate::realms::Mode::Coa, &|sql| { - assert!(sql.starts_with("SELECT ")); - db.query(sql) - }).unwrap(); + let squid_problems = + crate::squid::database_problems(&root, crate::realms::Mode::Coa, &|sql| { + assert!(sql.starts_with("SELECT ")); + db.query(sql) + }) + .unwrap(); assert_eq!(squid_problems.len(), 1); assert!(squid_problems[0].detail.contains("interrupted")); - assert_eq!(db.query("SELECT COUNT(*) FROM acore_characters.coa_squid_pending;").unwrap(), "1"); + assert_eq!( + db.query("SELECT COUNT(*) FROM acore_characters.coa_squid_pending;") + .unwrap(), + "1" + ); crate::schema_check::capture(&db, &root).unwrap(); let hash = fsx::sha256_file(&root.join(crate::schema_check::CONTRACT)).unwrap(); - db.query("ALTER TABLE acore_world.probe ALTER COLUMN id DROP DEFAULT;").unwrap(); + db.query("ALTER TABLE acore_world.probe ALTER COLUMN id DROP DEFAULT;") + .unwrap(); crate::schema_check::repair_missing_defaults(&db, &root, Some(&hash)).unwrap(); assert_eq!(db.query("SELECT COLUMN_DEFAULT FROM information_schema.COLUMNS WHERE TABLE_SCHEMA='acore_world' AND TABLE_NAME='probe' AND COLUMN_NAME='id';").unwrap(), "0"); assert_eq!(db.query("SELECT id FROM acore_world.probe;").unwrap(), "43"); - db.query("ALTER TABLE acore_world.probe ALTER COLUMN id SET DEFAULT 99;").unwrap(); + db.query("ALTER TABLE acore_world.probe ALTER COLUMN id SET DEFAULT 99;") + .unwrap(); crate::schema_check::repair_missing_defaults(&db, &root, Some(&hash)).unwrap(); assert_eq!(db.query("SELECT COLUMN_DEFAULT FROM information_schema.COLUMNS WHERE TABLE_SCHEMA='acore_world' AND TABLE_NAME='probe' AND COLUMN_NAME='id';").unwrap(), "99"); - db.query("SHUTDOWN;").unwrap(); server.0.wait().unwrap(); + db.query("SHUTDOWN;").unwrap(); + server.0.wait().unwrap(); let files = inventory(&data).unwrap(); copy_verified(&data, &point.join("mysql-data"), &files).unwrap(); - let expanded_bytes = files.keys().map(|name| fs::metadata(data.join(name)).unwrap().len()).sum(); - let mut snapshot = Snapshot {path:"mysql-data".into(), files, directories:directories(&data).unwrap(), server_sha256:fsx::sha256_file(&executable).unwrap(), bytes:0, expanded_bytes, archive_sha256:None}; - for directory in &snapshot.directories { fs::create_dir_all(point.join("mysql-data").join(directory)).unwrap(); } + let expanded_bytes = files + .keys() + .map(|name| fs::metadata(data.join(name)).unwrap().len()) + .sum(); + let mut snapshot = Snapshot { + path: "mysql-data".into(), + files, + directories: directories(&data).unwrap(), + server_sha256: fsx::sha256_file(&executable).unwrap(), + bytes: 0, + expanded_bytes, + archive_sha256: None, + }; + for directory in &snapshot.directories { + fs::create_dir_all(point.join("mysql-data").join(directory)).unwrap(); + } compress(&data, &point, &mut snapshot).unwrap(); let mut changed = start(); db.query("DROP VIEW acore_characters.probe_view; DROP TRIGGER acore_characters.probe_insert; DROP PROCEDURE acore_characters.probe_proc; DROP FUNCTION acore_characters.probe_func; DELETE FROM acore_characters.probe; DROP USER 'fixture_user'@'localhost';").unwrap(); - db.query("SHUTDOWN;").unwrap(); changed.0.wait().unwrap(); + db.query("SHUTDOWN;").unwrap(); + changed.0.wait().unwrap(); swap(&root, &meta, &point, &snapshot, false).unwrap(); let mut restored = start(); assert_eq!(db.recovery_objects("acore_characters").unwrap().len(), 4); assert_eq!(db.query("SELECT * FROM acore_characters.probe_view; CALL acore_characters.probe_proc(); SELECT acore_characters.probe_func(); SELECT COUNT(*) FROM mysql.user WHERE user='fixture_user';").unwrap().replace("\r\n", "\n"), "42\t43\n42\n73\n1"); - db.query("INSERT INTO acore_characters.probe VALUES(45,'check');").unwrap(); - assert_eq!(db.query("SELECT note FROM acore_characters.probe WHERE id=45;").unwrap(), "triggered"); - db.query("SHUTDOWN;").unwrap(); restored.0.wait().unwrap(); + db.query("INSERT INTO acore_characters.probe VALUES(45,'check');") + .unwrap(); + assert_eq!( + db.query("SELECT note FROM acore_characters.probe WHERE id=45;") + .unwrap(), + "triggered" + ); + db.query("SHUTDOWN;").unwrap(); + restored.0.wait().unwrap(); } fn fixture() -> (tempfile::TempDir, PathBuf, PathBuf, PathBuf, Snapshot) { let temp = tempfile::tempdir().unwrap(); @@ -556,7 +1199,15 @@ mod tests { fsx::atomic_write(&root.join("mysql/data/characters.ibd"), b"live").unwrap(); fsx::atomic_write(&point.join("mysql-data/characters.ibd"), b"saved").unwrap(); fs::create_dir_all(point.join("mysql-data/empty_schema")).unwrap(); - let snapshot = Snapshot { path:"mysql-data".into(), files:inventory(&point.join("mysql-data")).unwrap(), directories:directories(&point.join("mysql-data")).unwrap(), server_sha256:fsx::sha256_file(&root.join("mysql/bin/mysqld.exe")).unwrap(), bytes:5, expanded_bytes:5, archive_sha256:None }; + let snapshot = Snapshot { + path: "mysql-data".into(), + files: inventory(&point.join("mysql-data")).unwrap(), + directories: directories(&point.join("mysql-data")).unwrap(), + server_sha256: fsx::sha256_file(&root.join("mysql/bin/mysqld.exe")).unwrap(), + bytes: 5, + expanded_bytes: 5, + archive_sha256: None, + }; (temp, root, meta, point, snapshot) } #[test] @@ -564,10 +1215,18 @@ mod tests { let (_temp, root, meta, point, snapshot) = fixture(); assert!(swap(&root, &meta, &point, &snapshot, true).is_err()); assert!(!root.join("mysql/data").exists()); - let old = fs::read_dir(root.join("mysql")).unwrap().flatten().find(|e| e.file_name().to_string_lossy().starts_with("data-before-")).unwrap().path(); + let old = fs::read_dir(root.join("mysql")) + .unwrap() + .flatten() + .find(|e| e.file_name().to_string_lossy().starts_with("data-before-")) + .unwrap() + .path(); assert_eq!(fs::read(old.join("characters.ibd")).unwrap(), b"live"); swap(&root, &meta, &point, &snapshot, false).unwrap(); - assert_eq!(fs::read(root.join("mysql/data/characters.ibd")).unwrap(), b"saved"); + assert_eq!( + fs::read(root.join("mysql/data/characters.ibd")).unwrap(), + b"saved" + ); assert!(root.join("mysql/data/empty_schema").is_dir()); } #[test] @@ -575,11 +1234,17 @@ mod tests { let (_temp, root, meta, point, snapshot) = fixture(); fsx::atomic_write(&point.join("mysql-data/characters.ibd"), b"corrupt").unwrap(); assert!(swap(&root, &meta, &point, &snapshot, false).is_err()); - assert_eq!(fs::read(root.join("mysql/data/characters.ibd")).unwrap(), b"live"); + assert_eq!( + fs::read(root.join("mysql/data/characters.ibd")).unwrap(), + b"live" + ); fsx::atomic_write(&point.join("mysql-data/characters.ibd"), b"saved").unwrap(); fsx::atomic_write(&root.join("mysql/bin/mysqld.exe"), b"new-engine").unwrap(); assert!(swap(&root, &meta, &point, &snapshot, false).is_err()); - assert_eq!(fs::read(root.join("mysql/data/characters.ibd")).unwrap(), b"live"); + assert_eq!( + fs::read(root.join("mysql/data/characters.ibd")).unwrap(), + b"live" + ); } #[test] fn compressed_snapshots_verify_every_file_and_reject_unlisted_entries() { @@ -588,23 +1253,28 @@ mod tests { compress(&source, &point, &mut snapshot).unwrap(); assert!(snapshot.archive_sha256.is_some()); swap(&root, &meta, &point, &snapshot, false).unwrap(); - assert_eq!(fs::read(root.join("mysql/data/characters.ibd")).unwrap(), b"saved"); + assert_eq!( + fs::read(root.join("mysql/data/characters.ibd")).unwrap(), + b"saved" + ); fsx::atomic_write(&root.join("mysql/data/characters.ibd"), b"preserve").unwrap(); let archive_path = point.join(&snapshot.path); let encoder = zstd::Encoder::new(fs::File::create(&archive_path).unwrap(), 3).unwrap(); let mut archive = tar::Builder::new(encoder); - archive.append_file("unlisted.ibd", &mut fs::File::open(source.join("characters.ibd")).unwrap()).unwrap(); + archive + .append_file( + "unlisted.ibd", + &mut fs::File::open(source.join("characters.ibd")).unwrap(), + ) + .unwrap(); archive.into_inner().unwrap().finish().unwrap(); snapshot.archive_sha256 = Some(fsx::sha256_file(&archive_path).unwrap()); assert!(swap(&root, &meta, &point, &snapshot, false).is_err()); - assert_eq!(fs::read(root.join("mysql/data/characters.ibd")).unwrap(), b"preserve"); + assert_eq!( + fs::read(root.join("mysql/data/characters.ibd")).unwrap(), + b"preserve" + ); fsx::atomic_write(&archive_path, b"damaged").unwrap(); assert!(verify(&point, &snapshot).is_err()); } - - - - - - } diff --git a/crates/coa-core/src/portable/compat.rs b/crates/coa-core/src/portable/compat.rs index 0c756c9..e1e8859 100644 --- a/crates/coa-core/src/portable/compat.rs +++ b/crates/coa-core/src/portable/compat.rs @@ -456,8 +456,9 @@ mod tests { ruleset: Ruleset::Coa, character_formats: ContentProfile::manager_formats(), online_import_job_formats: jobs.to_vec(), - session_protocol: 2, - collection_protocol: 2, + session_protocol: crate::portable::session::protocol::SESSION_PROTOCOL_VERSION, + collection_protocol: + crate::portable::session::protocol::COLLECTION_PROTOCOL_VERSION, features: features.iter().copied().collect(), collection_kinds: ["coa:appearance".to_string(), "coa:vanity".to_string()] .into_iter() diff --git a/crates/coa-core/src/portable/migrations/001_init.sql b/crates/coa-core/src/portable/migrations/001_init.sql index 332e90f..fda742a 100644 --- a/crates/coa-core/src/portable/migrations/001_init.sql +++ b/crates/coa-core/src/portable/migrations/001_init.sql @@ -9,7 +9,7 @@ CREATE TABLE profile ( CREATE TABLE character ( character_id TEXT PRIMARY KEY, profile_id TEXT NOT NULL REFERENCES profile(profile_id), - ruleset TEXT NOT NULL CHECK (ruleset IN ('coa', 'wildcard', 'reborn')), + ruleset TEXT NOT NULL CHECK (ruleset IN ('coa', 'wildcard')), name TEXT NOT NULL, race TEXT NOT NULL, class TEXT NOT NULL, diff --git a/crates/coa-core/src/portable/migrations/009_multiruleset.sql b/crates/coa-core/src/portable/migrations/009_multiruleset.sql index 5f2681c..42be124 100644 --- a/crates/coa-core/src/portable/migrations/009_multiruleset.sql +++ b/crates/coa-core/src/portable/migrations/009_multiruleset.sql @@ -20,4 +20,29 @@ FROM collection; DROP TABLE collection; ALTER TABLE collection_new RENAME TO collection; -CREATE INDEX IF NOT EXISTS character_profile_ruleset ON character(profile_id, ruleset); +-- 2. Upgrade character table to allow 'reborn' in CHECK (ruleset IN ('coa', 'wildcard', 'reborn')) +-- Foreign keys are off during migration runner, but legacy child tables remain valid because primary keys are untouched. +CREATE TABLE character_new ( + character_id TEXT PRIMARY KEY, + profile_id TEXT NOT NULL REFERENCES profile(profile_id), + ruleset TEXT NOT NULL CHECK (ruleset IN ('coa', 'wildcard', 'reborn')), + name TEXT NOT NULL, + race TEXT NOT NULL, + class TEXT NOT NULL, + gender INTEGER NOT NULL, + level INTEGER NOT NULL, + revision INTEGER NOT NULL CHECK (revision >= 1), + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL, + archived INTEGER NOT NULL DEFAULT 0 CHECK (archived IN (0, 1)) +) STRICT; + +INSERT INTO character_new (character_id, profile_id, ruleset, name, race, class, gender, level, revision, created_at, updated_at, archived) +SELECT character_id, profile_id, ruleset, name, race, class, gender, level, revision, created_at, updated_at, archived +FROM character; + +DROP TABLE character; +ALTER TABLE character_new RENAME TO character; + +CREATE INDEX character_profile ON character(profile_id); +CREATE INDEX character_profile_ruleset ON character(profile_id, ruleset); diff --git a/crates/coa-core/src/portable/model.rs b/crates/coa-core/src/portable/model.rs index 4bbe8ac..f99d554 100644 --- a/crates/coa-core/src/portable/model.rs +++ b/crates/coa-core/src/portable/model.rs @@ -90,17 +90,10 @@ impl Ruleset { Ruleset::Reborn => 3, } } - pub fn schema(self, kind: &str) -> &'static str { - match (self, kind) { - (_, "auth") => "acore_auth", - (Self::Coa, "characters") => "acore_characters", - (Self::Coa, "world") => "acore_world", - (Self::Wildcard, "characters") => "acore_characters_wildcard", - (Self::Wildcard, "world") => "acore_world_wildcard", - (Self::Reborn, "characters") => "acore_characters_reborn", - (Self::Reborn, "world") => "acore_world_reborn", - _ => "acore_characters", - } + pub fn schema(self, kind: &str) -> Result<&'static str> { + let mode: crate::realms::Mode = self.into(); + mode.schema(kind) + .map_err(|e| PortableError::Invalid(e.to_string())) } pub fn collection_namespace(self) -> &'static str { match self { @@ -882,3 +875,21 @@ impl PortableCharacter { Ok(()) } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn schema_mapping_never_falls_back_on_unknown_database_kind() { + for ruleset in [Ruleset::Coa, Ruleset::Wildcard, Ruleset::Reborn] { + assert!(ruleset.schema("auth").is_ok()); + assert!(ruleset.schema("characters").is_ok()); + assert!(ruleset.schema("world").is_ok()); + assert!(ruleset.schema("characters_extra").is_err()); + assert!(ruleset.schema("unknown").is_err()); + assert!(ruleset.schema("").is_err()); + assert!(ruleset.schema("acore_characters").is_err()); + } + } +} diff --git a/crates/coa-core/src/portable/realm/collections.rs b/crates/coa-core/src/portable/realm/collections.rs index 0873a14..b5a45bc 100644 --- a/crates/coa-core/src/portable/realm/collections.rs +++ b/crates/coa-core/src/portable/realm/collections.rs @@ -39,7 +39,7 @@ fn realm_error(e: crate::Error) -> PortableError { fn check_ruleset(db: &Db, kind: &str) -> Result<()> { let r = ruleset_of(db)?; - if !kind.starts_with(r.as_str()) { + if !crate::portable::session::protocol::carried_kind_for(kind, r) { return Err(PortableError::Invalid(format!( "collection kind {kind:?} does not belong to realm ruleset {r:?}" ))); @@ -95,7 +95,9 @@ pub fn read_set(db: &Db, account: u32, kind: &str) -> Result { .trim() .parse() .map_err(|_| PortableError::CorruptSnapshot(format!("{line:?} is not an id")))?; - if (kind == "coa:vanity" || kind == "wildcard:vanity" || kind == "reborn:vanity") && is_bank_vanity_item(id) { + if (kind == "coa:vanity" || kind == "wildcard:vanity" || kind == "reborn:vanity") + && is_bank_vanity_item(id) + { continue; } ids.push(id); @@ -124,18 +126,18 @@ pub fn apply_set( check_ruleset(db, kind)?; let (table, column, has_source) = layout(kind)?; let known = |id: u32| match kind { - "coa:appearance" | "wildcard:appearance" | "reborn:appearance" => knowledge.knows_appearance(id), + "coa:appearance" | "wildcard:appearance" | "reborn:appearance" => { + knowledge.knows_appearance(id) + } _ => knowledge.knows_vanity(id) && !is_bank_vanity_item(id), }; let held = read_set(db, account, kind)?; let mut applied = Applied::default(); let mut wanted = Vec::new(); - for id in canonical - .ids() - .iter() - .copied() - .filter(|id| !((kind == "coa:vanity" || kind == "wildcard:vanity" || kind == "reborn:vanity") && is_bank_vanity_item(*id))) - { + for id in canonical.ids().iter().copied().filter(|id| { + !((kind == "coa:vanity" || kind == "wildcard:vanity" || kind == "reborn:vanity") + && is_bank_vanity_item(*id)) + }) { if !known(id) { applied.unknown += 1; } else if held.contains(id) { diff --git a/crates/coa-core/src/portable/realm/live_wardrobe.rs b/crates/coa-core/src/portable/realm/live_wardrobe.rs index b61a2e2..0c3344b 100644 --- a/crates/coa-core/src/portable/realm/live_wardrobe.rs +++ b/crates/coa-core/src/portable/realm/live_wardrobe.rs @@ -170,7 +170,9 @@ fn account_collections_are_read_cheaply_unioned_and_written_without_duplicates_o store .merge_collection(profile, Ruleset::Coa, APPEARANCE, &wardrobe) .unwrap(); - store.merge_collection(profile, Ruleset::Coa, VANITY, &vanity).unwrap(); + store + .merge_collection(profile, Ruleset::Coa, VANITY, &vanity) + .unwrap(); let fingerprint_a = fingerprint(&r.a, 5001, APPEARANCE).unwrap(); assert_eq!( fingerprint(&r.a, 5001, APPEARANCE).unwrap(), @@ -331,10 +333,20 @@ fn the_result_comes_back_to_realm_a_unchanged_gameplay_and_complete_collections( reconcile_session(&r.b, &mut store, id, B, true, None).unwrap(); for kind in [APPEARANCE, VANITY] { store - .merge_collection(profile, Ruleset::Coa, kind, &read_set(&r.b, ACCOUNT, kind).unwrap()) + .merge_collection( + profile, + Ruleset::Coa, + kind, + &read_set(&r.b, ACCOUNT, kind).unwrap(), + ) .unwrap(); store - .merge_collection(profile, Ruleset::Coa, kind, &read_set(&r.a, 5001, kind).unwrap()) + .merge_collection( + profile, + Ruleset::Coa, + kind, + &read_set(&r.a, 5001, kind).unwrap(), + ) .unwrap(); } @@ -343,7 +355,10 @@ fn the_result_comes_back_to_realm_a_unchanged_gameplay_and_complete_collections( let updated = update_realm_character(&r.a, &mut store, id, "realm-a", &options(a_known.clone())).unwrap(); assert!(updated.updated, "{updated:?}"); - let (_, canonical_wardrobe) = store.collection(profile, Ruleset::Coa, APPEARANCE).unwrap().unwrap(); + let (_, canonical_wardrobe) = store + .collection(profile, Ruleset::Coa, APPEARANCE) + .unwrap() + .unwrap(); let applied = apply_set(&r.a, 5001, APPEARANCE, &canonical_wardrobe, &a_known).unwrap(); assert_eq!(applied.inserted, 1, "only 1300 is new to A"); assert_eq!( diff --git a/crates/coa-core/src/portable/realm/profile.rs b/crates/coa-core/src/portable/realm/profile.rs index d754e9d..d13e6b1 100644 --- a/crates/coa-core/src/portable/realm/profile.rs +++ b/crates/coa-core/src/portable/realm/profile.rs @@ -14,7 +14,9 @@ use super::super::extension::{ }; use super::super::ids::CharacterId; use super::super::model::PortableCharacter; -use super::super::session::protocol::{collection_kinds, PROTOCOL_VERSION}; +use super::super::session::protocol::{ + collection_kinds, COLLECTION_PROTOCOL_VERSION, SESSION_PROTOCOL_VERSION, +}; use super::super::store::Store; use super::import::ImportOptions; use super::script::SchemaProbe; @@ -97,8 +99,8 @@ pub fn assemble( online_import_job_formats: core .map(|c| c.portable.job_formats.clone()) .unwrap_or_default(), - session_protocol: PROTOCOL_VERSION, - collection_protocol: PROTOCOL_VERSION, + session_protocol: SESSION_PROTOCOL_VERSION, + collection_protocol: COLLECTION_PROTOCOL_VERSION, features, collection_kinds: if probe.has("account_appearance_collection") && probe.has("account_vanity_collection") diff --git a/crates/coa-core/src/portable/service/engine.rs b/crates/coa-core/src/portable/service/engine.rs index 2d22fc7..2a5da21 100644 --- a/crates/coa-core/src/portable/service/engine.rs +++ b/crates/coa-core/src/portable/service/engine.rs @@ -1501,7 +1501,10 @@ impl PortableService { let encoded = super::super::snapshot::encode(&model)?; let mut collections = BTreeMap::new(); for kind in super::super::session::protocol::collection_kinds(model.ruleset) { - if let Ok(Some((_, set))) = self.owner.collection(self.owner_profile, model.ruleset, kind) { + if let Ok(Some((_, set))) = + self.owner + .collection(self.owner_profile, model.ruleset, kind) + { collections.insert(kind.to_string(), set.ids().to_vec()); } } @@ -1600,7 +1603,7 @@ impl PortableService { "Character ruleset does not match realm database ruleset.", )); } - let caps_ruleset: crate::portable::model::Ruleset = caps.content.ruleset.into(); + let caps_ruleset: crate::portable::model::Ruleset = caps.content.ruleset; if model.ruleset != caps_ruleset { return Err(fail( "incompatible", @@ -1625,7 +1628,9 @@ impl PortableService { for (kind, ids) in ¶ms.collections { if kind.starts_with(model.ruleset.as_str()) { if let Ok(set) = super::super::collection::IdSet::from_ids(ids.iter().copied()) { - let _ = self.host.merge_collection(self.host_profile, model.ruleset, kind, &set); + let _ = + self.host + .merge_collection(self.host_profile, model.ruleset, kind, &set); } } } diff --git a/crates/coa-core/src/portable/session/collection_tests.rs b/crates/coa-core/src/portable/session/collection_tests.rs index 99fd30e..2d572bb 100644 --- a/crates/coa-core/src/portable/session/collection_tests.rs +++ b/crates/coa-core/src/portable/session/collection_tests.rs @@ -344,7 +344,11 @@ fn a_realm_that_lacks_an_unlock_never_removes_it_and_gets_what_it_knows_back() { // the Owner unioned the realm's ids (700 included: the realm showed it) and kept everything else let appearance_ack = acks.iter().find(|a| a.kind == APPEARANCE).unwrap(); assert_eq!(appearance_ack.outcome, CollectionOutcome::Applied); - let (_, canonical) = o.store().collection(profile, Ruleset::Coa, APPEARANCE).unwrap().unwrap(); + let (_, canonical) = o + .store() + .collection(profile, Ruleset::Coa, APPEARANCE) + .unwrap() + .unwrap(); assert_eq!(canonical.len(), 501); assert!( canonical.contains(700) && canonical.contains(1) && canonical.contains(500), @@ -376,7 +380,9 @@ fn an_account_with_unlocks_arrives_on_a_second_realm_from_the_owners_state_alone owner .merge_collection(profile, Ruleset::Coa, VANITY, &ids(50..=60)) .unwrap(); - let states = OwnerService::new(&mut owner).collection_states(Ruleset::Coa).unwrap(); + let states = OwnerService::new(&mut owner) + .collection_states(Ruleset::Coa) + .unwrap(); assert_eq!(states.len(), 2); let mut host = Store::open_in_memory().unwrap(); @@ -415,9 +421,10 @@ fn hostile_or_broken_collection_messages_change_nothing() { let mut owner = Store::open_in_memory().unwrap(); let profile = owner.default_profile().unwrap(); let mut o = OwnerService::new(&mut owner); - let good = - collection_to_json(&CollectionObserved::new(SERVER, Ruleset::Coa, APPEARANCE, &ids(1..=10)).unwrap()) - .unwrap(); + let good = collection_to_json( + &CollectionObserved::new(SERVER, Ruleset::Coa, APPEARANCE, &ids(1..=10)).unwrap(), + ) + .unwrap(); assert_eq!( o.handle_collection(&good).unwrap().outcome, CollectionOutcome::Applied @@ -487,13 +494,39 @@ fn hostile_or_broken_collection_messages_change_nothing() { // a set that decodes to more ids than the cap allows is refused before it is built let mut huge = vec![1u8]; huge.extend([0xFF, 0xFF, 0xFF, 0xFF, 0x0F]); - let message = serde_json::json!({"protocol_version": PROTOCOL_VERSION, "server_id": SERVER, "kind": APPEARANCE, "set": {"hash": "00".repeat(32), "count": 1, "ids": base64::Engine::encode(&base64::engine::general_purpose::STANDARD, huge)}}); + let message = serde_json::json!({"protocol_version": COLLECTION_PROTOCOL_VERSION, "ruleset": "coa", "server_id": SERVER, "kind": APPEARANCE, "set": {"hash": "00".repeat(32), "count": 1, "ids": base64::Engine::encode(&base64::engine::general_purpose::STANDARD, huge)}}); assert!(matches!( o.handle_collection(&serde_json::to_vec(&message).unwrap()) .unwrap() .outcome, CollectionOutcome::Rejected(_) )); + + // attack test: prefix-confusion collection kinds are strictly rejected with zero state change + for evil_kind in [ + "coax:appearance", + "coaevil:vanity", + "wildcard2:appearance", + "reborn-extra:vanity", + "coa:", + "unknown", + "coa:appearance:extra", + ] { + let mut v: serde_json::Value = serde_json::from_slice(&good).unwrap(); + v["kind"] = evil_kind.into(); + let ack = o + .handle_collection(&serde_json::to_vec(&v).unwrap()) + .unwrap(); + assert!( + matches!(ack.outcome, CollectionOutcome::Rejected(_)), + "evil kind {evil_kind} must be rejected" + ); + } + assert_eq!( + state_of(&o), + before, + "prefix confusion attacks must mutate nothing" + ); } #[test] diff --git a/crates/coa-core/src/portable/session/host.rs b/crates/coa-core/src/portable/session/host.rs index fb0a81f..46f9f30 100644 --- a/crates/coa-core/src/portable/session/host.rs +++ b/crates/coa-core/src/portable/session/host.rs @@ -614,7 +614,14 @@ impl<'a> HostService<'a> { }; let character = self.store.character(s.character_id)?; for kind in collection_kinds(character.ruleset) { - self.observe_collection(bridge, account, character.ruleset, kind, now_secs, events)?; + self.observe_collection( + bridge, + account, + character.ruleset, + kind, + now_secs, + events, + )?; } } Ok(()) @@ -652,7 +659,12 @@ impl<'a> HostService<'a> { )?; return Ok(()); } - let bytes = collection_to_json(&CollectionObserved::new(&self.server_id, ruleset, kind, &set)?)?; + let bytes = collection_to_json(&CollectionObserved::new( + &self.server_id, + ruleset, + kind, + &set, + )?)?; self.store.host_collection_observe( &self.server_id, account, diff --git a/crates/coa-core/src/portable/session/owner.rs b/crates/coa-core/src/portable/session/owner.rs index 69783d0..6f722cd 100644 --- a/crates/coa-core/src/portable/session/owner.rs +++ b/crates/coa-core/src/portable/session/owner.rs @@ -51,9 +51,12 @@ impl<'a> OwnerService<'a> { let profile = self.store.default_profile()?; let ruleset = msg.ruleset; let rejected = |store: &Store, reason: &str| -> Result { - let info = store.collection_info(profile, ruleset, &msg.kind).ok().flatten(); + let info = store + .collection_info(profile, ruleset, &msg.kind) + .ok() + .flatten(); Ok(CollectionAck { - protocol_version: PROTOCOL_VERSION, + protocol_version: crate::portable::session::protocol::COLLECTION_PROTOCOL_VERSION, ruleset, kind: msg.kind.clone(), outcome: CollectionOutcome::Rejected(reason.to_string()), @@ -63,13 +66,18 @@ impl<'a> OwnerService<'a> { }) }; if !carried_kind_for(&msg.kind, ruleset) { - return rejected(self.store, "this collection kind is not carried for this ruleset"); + return rejected( + self.store, + "this collection kind is not carried for this ruleset", + ); } let observed = match msg.set.open(&msg.kind) { Ok(set) => set, Err(e) => return rejected(self.store, &e.to_string()), }; - let merge = self.store.merge_collection(profile, ruleset, &msg.kind, &observed)?; + let merge = self + .store + .merge_collection(profile, ruleset, &msg.kind, &observed)?; let (info, canonical) = self .store .collection(profile, ruleset, &msg.kind)? @@ -79,13 +87,16 @@ impl<'a> OwnerService<'a> { &info, observed.count_new(&canonical) == 0 && canonical.count_new(&observed) == 0, ) { - (Some(info), false) => { - Some(CollectionState::new(ruleset, &msg.kind, info.revision, &canonical)?) - } + (Some(info), false) => Some(CollectionState::new( + ruleset, + &msg.kind, + info.revision, + &canonical, + )?), _ => None, }; Ok(CollectionAck { - protocol_version: PROTOCOL_VERSION, + protocol_version: crate::portable::session::protocol::COLLECTION_PROTOCOL_VERSION, ruleset, kind: msg.kind, outcome: if merge.changed { @@ -100,7 +111,10 @@ impl<'a> OwnerService<'a> { } /// The canonical collections as messages (for a realm that has none of them yet, or a new one). - pub fn collection_states(&mut self, ruleset: crate::portable::model::Ruleset) -> Result> { + pub fn collection_states( + &mut self, + ruleset: crate::portable::model::Ruleset, + ) -> Result> { let profile = self.store.default_profile()?; let mut out = Vec::new(); for kind in collection_kinds(ruleset) { diff --git a/crates/coa-core/src/portable/session/projection_tests.rs b/crates/coa-core/src/portable/session/projection_tests.rs index 969f07c..8c785e5 100644 --- a/crates/coa-core/src/portable/session/projection_tests.rs +++ b/crates/coa-core/src/portable/session/projection_tests.rs @@ -371,9 +371,10 @@ fn a_session_started_without_its_projection_or_with_a_wrong_one_is_not_opened() ); // an older protocol is not understood at all - let old = String::from_utf8(genuine.clone()) - .unwrap() - .replace("\"protocol_version\":2", "\"protocol_version\":1"); + let old = String::from_utf8(genuine.clone()).unwrap().replace( + &format!("\"protocol_version\":{PROTOCOL_VERSION}"), + "\"protocol_version\":1", + ); assert!(o.handle_started(old.as_bytes()).is_err()); assert_eq!( o.handle_started(&genuine).unwrap().outcome, diff --git a/crates/coa-core/src/portable/session/protocol.rs b/crates/coa-core/src/portable/session/protocol.rs index 2453385..588611b 100644 --- a/crates/coa-core/src/portable/session/protocol.rs +++ b/crates/coa-core/src/portable/session/protocol.rs @@ -13,10 +13,13 @@ use super::super::model::{limits::MAX_COMPRESSED_BYTES, PortableCharacter}; use super::super::projection::{ProgressionPin, ProjectionContext}; use super::super::snapshot; -/// Version 2 (Phase 8): `PortableSessionStarted` carries the progression the session runs under, every `PortableCheckpoint` and `OwnerAck` its pin. -/// A version 1 peer and a version 2 peer read each other's messages as unsupported, and the realm's capability profile (`session_protocol`) -/// says so before any character is armed. -pub const PROTOCOL_VERSION: u32 = 2; +/// Version 3: `SessionOffer`, `PortableSessionStarted`, `PortableCheckpoint`, and `OwnerAck` require explicit `ruleset`. +/// Version 2 (Phase 8): `PortableSessionStarted` carried progression and pins. +pub const SESSION_PROTOCOL_VERSION: u32 = 3; +/// Protocol version for collection synchronization (`CollectionObserved`, `CollectionState`, `CollectionAck`). +pub const COLLECTION_PROTOCOL_VERSION: u32 = 2; +/// Backward-compatibility alias for session protocol version. +pub const PROTOCOL_VERSION: u32 = SESSION_PROTOCOL_VERSION; /// A message carries at most one compressed snapshot (base64: 4/3) plus a little structure. pub const MAX_MESSAGE_BYTES: usize = MAX_COMPRESSED_BYTES * 4 / 3 + 64 * 1024; /// The most item/pet ids an acknowledgement lists. @@ -24,10 +27,6 @@ pub const MAX_ACK_IDS: usize = 20_000; /// The largest serialized collection message accepted. pub const MAX_COLLECTION_MESSAGE_BYTES: usize = 1024 * 1024; -fn default_session_ruleset() -> super::super::model::Ruleset { - super::super::model::Ruleset::Coa -} - /// A sealed snapshot: the hash of the canonical JSON and the compressed bytes. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] @@ -85,7 +84,6 @@ impl Envelope { #[serde(deny_unknown_fields)] pub struct SessionOffer { pub protocol_version: u32, - #[serde(default = "default_session_ruleset")] pub ruleset: super::super::model::Ruleset, pub session_id: SessionId, pub character_id: CharacterId, @@ -131,7 +129,6 @@ impl SessionProgression { #[serde(deny_unknown_fields)] pub struct PortableSessionStarted { pub protocol_version: u32, - #[serde(default = "default_session_ruleset")] pub ruleset: super::super::model::Ruleset, pub session_id: SessionId, pub character_id: CharacterId, @@ -149,7 +146,6 @@ pub struct PortableSessionStarted { #[serde(deny_unknown_fields)] pub struct PortableCheckpoint { pub protocol_version: u32, - #[serde(default = "default_session_ruleset")] pub ruleset: super::super::model::Ruleset, pub session_id: SessionId, pub character_id: CharacterId, @@ -200,7 +196,6 @@ pub struct NextSession { #[serde(deny_unknown_fields)] pub struct OwnerAck { pub protocol_version: u32, - #[serde(default = "default_session_ruleset")] pub ruleset: super::super::model::Ruleset, pub session_id: SessionId, /// 0 acknowledges `PortableSessionStarted`. @@ -398,7 +393,6 @@ impl CompactSet { #[serde(deny_unknown_fields)] pub struct CollectionObserved { pub protocol_version: u32, - #[serde(default = "default_session_ruleset")] pub ruleset: super::super::model::Ruleset, pub server_id: String, pub kind: String, @@ -410,7 +404,6 @@ pub struct CollectionObserved { #[serde(deny_unknown_fields)] pub struct CollectionState { pub protocol_version: u32, - #[serde(default = "default_session_ruleset")] pub ruleset: super::super::model::Ruleset, pub kind: String, pub collection_revision: u64, @@ -437,7 +430,6 @@ pub enum CollectionOutcome { #[serde(deny_unknown_fields)] pub struct CollectionAck { pub protocol_version: u32, - #[serde(default = "default_session_ruleset")] pub ruleset: super::super::model::Ruleset, pub kind: String, pub outcome: CollectionOutcome, @@ -469,24 +461,29 @@ pub fn collection_from_json(bytes: &[u8]) -> Result { .get("protocol_version") .and_then(|v| v.as_u64()) .ok_or_else(|| PortableError::Invalid("the message has no protocol version".into()))?; - if version != PROTOCOL_VERSION as u64 { + if version != COLLECTION_PROTOCOL_VERSION as u64 { return Err(PortableError::UnsupportedFormat { found: version.min(u32::MAX as u64) as u32, - supported: PROTOCOL_VERSION, + supported: COLLECTION_PROTOCOL_VERSION, }); } Ok(serde_json::from_value(value)?) } impl CollectionObserved { - pub fn new(server_id: &str, ruleset: super::super::model::Ruleset, kind: &str, set: &IdSet) -> Result { + pub fn new( + server_id: &str, + ruleset: super::super::model::Ruleset, + kind: &str, + set: &IdSet, + ) -> Result { if !carried_kind_for(kind, ruleset) { return Err(PortableError::Invalid(format!( "collection kind {kind:?} is not carried for {ruleset:?}" ))); } Ok(Self { - protocol_version: PROTOCOL_VERSION, + protocol_version: COLLECTION_PROTOCOL_VERSION, ruleset, server_id: server_id.to_string(), kind: kind.to_string(), @@ -496,9 +493,14 @@ impl CollectionObserved { } impl CollectionState { - pub fn new(ruleset: super::super::model::Ruleset, kind: &str, revision: u64, set: &IdSet) -> Result { + pub fn new( + ruleset: super::super::model::Ruleset, + kind: &str, + revision: u64, + set: &IdSet, + ) -> Result { Ok(Self { - protocol_version: PROTOCOL_VERSION, + protocol_version: COLLECTION_PROTOCOL_VERSION, ruleset, kind: kind.to_string(), collection_revision: revision, @@ -506,3 +508,126 @@ impl CollectionState { }) } } + +/// Legacy Session Protocol v2 representation (Phase 8), where absence of ruleset is defined to mean CoA. +#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct LegacyV2SessionOffer { + pub protocol_version: u32, + pub session_id: SessionId, + pub character_id: CharacterId, + pub server_id: String, + pub canonical_revision: u64, + pub snapshot: Envelope, +} + +impl LegacyV2SessionOffer { + pub fn into_session_offer(self) -> SessionOffer { + SessionOffer { + protocol_version: SESSION_PROTOCOL_VERSION, + ruleset: super::super::model::Ruleset::Coa, + session_id: self.session_id, + character_id: self.character_id, + server_id: self.server_id, + canonical_revision: self.canonical_revision, + snapshot: self.snapshot, + } + } +} + +#[cfg(test)] +mod protocol_tests { + use super::*; + use crate::portable::Ruleset; + + #[test] + fn session_protocol_v3_requires_ruleset_and_rejects_missing_or_unknown() { + let envelope = Envelope { + content_hash: "00".repeat(32), + payload: "AA==".to_string(), + }; + + // 1. Valid v3 SessionOffer with explicit ruleset (CoA, Wildcard, Reborn) + for r in [Ruleset::Coa, Ruleset::Wildcard, Ruleset::Reborn] { + let offer = SessionOffer { + protocol_version: SESSION_PROTOCOL_VERSION, + ruleset: r, + session_id: SessionId::new(), + character_id: CharacterId::new(), + server_id: "realm-1".to_string(), + canonical_revision: 1, + snapshot: envelope.clone(), + }; + let bytes = to_json(&offer).unwrap(); + let parsed: SessionOffer = from_json(&bytes).unwrap(); + assert_eq!(parsed.ruleset, r); + } + + // 2. Missing ruleset in v3 JSON is rejected (never silently defaults to CoA) + let missing_ruleset_v3 = serde_json::json!({ + "protocol_version": SESSION_PROTOCOL_VERSION, + "session_id": SessionId::new().to_string(), + "character_id": CharacterId::new().to_string(), + "server_id": "realm-1", + "canonical_revision": 1, + "snapshot": { + "content_hash": "00".repeat(32), + "payload": "AA==" + } + }); + let bytes = serde_json::to_vec(&missing_ruleset_v3).unwrap(); + let err: std::result::Result = from_json(&bytes); + assert!( + err.is_err(), + "missing ruleset must be rejected in protocol v3" + ); + + // 3. Unknown ruleset in v3 JSON is rejected + let unknown_ruleset_v3 = serde_json::json!({ + "protocol_version": SESSION_PROTOCOL_VERSION, + "ruleset": "cyberpunk", + "session_id": SessionId::new().to_string(), + "character_id": CharacterId::new().to_string(), + "server_id": "realm-1", + "canonical_revision": 1, + "snapshot": { + "content_hash": "00".repeat(32), + "payload": "AA==" + } + }); + let bytes = serde_json::to_vec(&unknown_ruleset_v3).unwrap(); + let err: std::result::Result = from_json(&bytes); + assert!(err.is_err(), "unknown ruleset must be rejected"); + + // 4. Old v2 peer message (protocol_version 2) is rejected by current v3 parser + let legacy_v2_json = serde_json::json!({ + "protocol_version": 2, + "session_id": SessionId::new().to_string(), + "character_id": CharacterId::new().to_string(), + "server_id": "realm-1", + "canonical_revision": 1, + "snapshot": { + "content_hash": "00".repeat(32), + "payload": "AA==" + } + }); + let bytes = serde_json::to_vec(&legacy_v2_json).unwrap(); + let err: std::result::Result = from_json(&bytes); + assert!( + matches!( + err, + Err(PortableError::UnsupportedFormat { + found: 2, + supported: 3 + }) + ), + "v2 peer must be rejected with UnsupportedFormat" + ); + + // 5. Explicit LegacyV2SessionOffer decode correctly interprets absence of ruleset as CoA + let v2_parsed: LegacyV2SessionOffer = serde_json::from_slice(&bytes).unwrap(); + let upgraded = v2_parsed.into_session_offer(); + assert_eq!(upgraded.ruleset, Ruleset::Coa); + assert_eq!(upgraded.protocol_version, SESSION_PROTOCOL_VERSION); + } +} diff --git a/crates/coa-core/src/portable/store.rs b/crates/coa-core/src/portable/store.rs index 38e160a..8b29a51 100644 --- a/crates/coa-core/src/portable/store.rs +++ b/crates/coa-core/src/portable/store.rs @@ -206,11 +206,13 @@ impl Store { }); } for next in version..supported { + self.conn.pragma_update(None, "foreign_keys", false)?; let tx = self.conn.transaction()?; tx.execute_batch(MIGRATIONS[next as usize])?; tx.pragma_update(None, "application_id", APPLICATION_ID)?; tx.pragma_update(None, "user_version", next + 1)?; tx.commit()?; + self.conn.pragma_update(None, "foreign_keys", true)?; } Ok(()) } diff --git a/crates/coa-core/src/portable/store/owner.rs b/crates/coa-core/src/portable/store/owner.rs index 713eb35..7e06862 100644 --- a/crates/coa-core/src/portable/store/owner.rs +++ b/crates/coa-core/src/portable/store/owner.rs @@ -338,12 +338,22 @@ impl Store { }; let record = read_character(&tx, row.character_id)?; let seen_hash = head_hash(&tx, row.character_id, record.revision)?; - let outcome = - |o: AckOutcome| ack(record.ruleset, msg.session_id, msg.sequence, o, record.revision, seen_hash); + let outcome = |o: AckOutcome| { + ack( + record.ruleset, + msg.session_id, + msg.sequence, + o, + record.revision, + seen_hash, + ) + }; let reject = |why: &str| outcome(AckOutcome::Rejected(why.into())); if msg.ruleset != record.ruleset { - return Ok(reject("the checkpoint ruleset does not match the character")); + return Ok(reject( + "the checkpoint ruleset does not match the character", + )); } if msg.character_id != row.character_id || msg.server_id != row.server_id { return Ok(reject("the message does not belong to this session")); diff --git a/crates/coa-core/src/portable/store/tests.rs b/crates/coa-core/src/portable/store/tests.rs index 0f6dcb2..2f08d00 100644 --- a/crates/coa-core/src/portable/store/tests.rs +++ b/crates/coa-core/src/portable/store/tests.rs @@ -928,7 +928,12 @@ fn collection_union_never_removes_and_unchanged_means_no_revision() { assert!(!empty.changed && empty.info.is_none()); let first = store - .merge_collection(profile, ruleset, kind, &IdSet::from_ids([10, 20, 30]).unwrap()) + .merge_collection( + profile, + ruleset, + kind, + &IdSet::from_ids([10, 20, 30]).unwrap(), + ) .unwrap(); assert!(first.changed); assert_eq!(first.added, 3); @@ -946,13 +951,23 @@ fn collection_union_never_removes_and_unchanged_means_no_revision() { "same revision, same hash" ); let same = store - .merge_collection(profile, ruleset, kind, &IdSet::from_ids([10, 20, 30]).unwrap()) + .merge_collection( + profile, + ruleset, + kind, + &IdSet::from_ids([10, 20, 30]).unwrap(), + ) .unwrap(); assert!(!same.changed); // a realm with new unlocks (and without the old ones) only adds let more = store - .merge_collection(profile, ruleset, kind, &IdSet::from_ids([30, 40, 5]).unwrap()) + .merge_collection( + profile, + ruleset, + kind, + &IdSet::from_ids([30, 40, 5]).unwrap(), + ) .unwrap(); assert!(more.changed); assert_eq!(more.added, 2); @@ -964,7 +979,10 @@ fn collection_union_never_removes_and_unchanged_means_no_revision() { assert_eq!(set.ids(), &[5, 10, 20, 30, 40]); assert_eq!(info, info2); assert_eq!( - store.collection_info(profile, ruleset, kind).unwrap().unwrap(), + store + .collection_info(profile, ruleset, kind) + .unwrap() + .unwrap(), info2 ); @@ -991,7 +1009,9 @@ fn collections_hold_tens_of_thousands_of_ids_compactly() { ] { let ids: Vec = (0..count).map(|n| n * 7 + (n % 5)).collect(); let set = IdSet::from_ids(ids).unwrap(); - let merge = store.merge_collection(profile, Ruleset::Coa, kind, &set).unwrap(); + let merge = store + .merge_collection(profile, Ruleset::Coa, kind, &set) + .unwrap(); assert_eq!(merge.added, count as usize); let stored_bytes: i64 = store .conn @@ -1005,7 +1025,10 @@ fn collections_hold_tens_of_thousands_of_ids_compactly() { stored_bytes < count as i64 * 2 + 16, "{kind}: {count} ids took {stored_bytes} bytes" ); - let (_, back) = store.collection(profile, Ruleset::Coa, kind).unwrap().unwrap(); + let (_, back) = store + .collection(profile, Ruleset::Coa, kind) + .unwrap() + .unwrap(); assert_eq!(back, set); } } @@ -1014,7 +1037,12 @@ fn collections_hold_tens_of_thousands_of_ids_compactly() { fn a_tampered_collection_is_detected() { let (mut store, profile) = fresh(); store - .merge_collection(profile, Ruleset::Coa, "coa:vanity", &IdSet::from_ids([1, 2, 3]).unwrap()) + .merge_collection( + profile, + Ruleset::Coa, + "coa:vanity", + &IdSet::from_ids([1, 2, 3]).unwrap(), + ) .unwrap(); let forged = IdSet::from_ids([1, 2, 3, 4]).unwrap().encode(); store @@ -1940,3 +1968,149 @@ fn a_store_that_holds_format_1_snapshots_reads_them_and_compares_them_by_what_th ); assert_eq!(owner.load_current(id).unwrap(), other); } + +#[test] +fn released_v0_7_x_database_upgrades_transactionally_through_migration_009_and_accepts_reborn() { + let dir = tempfile::tempdir().unwrap(); + let file = Store::path_of(dir.path()); + let profile = ProfileId::new(); + let char_coa = CharacterId::new(); + let char_wc = CharacterId::new(); + let item_coa = PortableItemId::new(); + let now = "2026-10-22T12:00:00Z"; + + // Build realistic pre-multiruleset v0.7.x database (migrations 0..8) + { + let conn = Connection::open(&file).unwrap(); + conn.pragma_update(None, "foreign_keys", true).unwrap(); + for m in &MIGRATIONS[..8] { + conn.execute_batch(m).unwrap(); + } + conn.pragma_update(None, "application_id", APPLICATION_ID) + .unwrap(); + conn.pragma_update(None, "user_version", 8).unwrap(); + + // 1. Profile + conn.execute( + "INSERT INTO profile (profile_id, created_at, format_version) VALUES (?1, ?2, 1)", + params![profile.to_string(), now], + ) + .unwrap(); + + // 2. Characters (CoA and Wildcard allowed in pre-009 schema) + conn.execute( + "INSERT INTO character (character_id, profile_id, ruleset, name, race, class, gender, level, revision, created_at, updated_at, archived) + VALUES (?1, ?2, 'coa', 'Varian', 'coa:race:1', 'coa:class:1', 0, 80, 1, ?3, ?3, 0)", + params![char_coa.to_string(), profile.to_string(), now], + ).unwrap(); + + conn.execute( + "INSERT INTO character (character_id, profile_id, ruleset, name, race, class, gender, level, revision, created_at, updated_at, archived) + VALUES (?1, ?2, 'wildcard', 'RogueMage', 'coa:race:1', 'coa:class:4', 1, 60, 2, ?3, ?3, 0)", + params![char_wc.to_string(), profile.to_string(), now], + ).unwrap(); + + // Verify pre-009 CHECK constraint rejects 'reborn' + let err = conn.execute( + "INSERT INTO character (character_id, profile_id, ruleset, name, race, class, gender, level, revision, created_at, updated_at, archived) + VALUES (?1, ?2, 'reborn', 'Paladin', 'coa:race:1', 'coa:class:2', 0, 70, 1, ?3, ?3, 0)", + params![CharacterId::new().to_string(), profile.to_string(), now], + ); + assert!(err.is_err(), "pre-009 schema must reject reborn"); + + // 3. Snapshots and revisions + conn.execute( + "INSERT INTO snapshot (character_id, revision, snapshot_format_version, created_at, source_server_id, content_hash, uncompressed_size, payload, note) + VALUES (?1, 1, 2, ?2, 'realm-a', ?3, 4, X'01020304', 'genesis')", + params![char_coa.to_string(), now, [0x42u8; 32]], + ).unwrap(); + + // 4. Mappings and server bindings + conn.execute( + "INSERT INTO character_server_mapping (character_id, server_id, local_guid, last_revision, state, updated_at) + VALUES (?1, 'realm-a', 101, 1, 'active', ?2)", + params![char_coa.to_string(), now], + ).unwrap(); + + conn.execute( + "INSERT INTO item_mapping (character_id, server_id, portable_item_id, local_item_guid, entry, identity, state, created_revision, confirmed_revision, created_at, updated_at) + VALUES (?1, 'realm-a', ?2, 202, 'item_entry', 'ident', 'active', 1, 1, ?3, ?3)", + params![char_coa.to_string(), item_coa.to_string(), now], + ).unwrap(); + + // 5. Baseline session (realm_baseline) + conn.execute( + "INSERT INTO realm_baseline (character_id, server_id, c0_revision, head_revision, state, c0_hash, c0_payload, b0_hash, b0_payload, created_at, updated_at) + VALUES (?1, 'realm-a', 1, 1, 'open', ?2, X'AA', ?2, X'BB', ?3, ?3)", + params![char_coa.to_string(), [0x42u8; 32], now], + ).unwrap(); + + // 6. Pre-009 Collection (single profile_id, kind PK) + conn.execute( + "INSERT INTO collection (profile_id, kind, collection_revision, collection_hash, format_version, item_count, updated_at, payload) + VALUES (?1, 'coa:appearance', 1, ?2, 1, 0, ?3, X'00')", + params![profile.to_string(), [0x42u8; 32], now], + ).unwrap(); + } + + // Upgrade through Store::open_file (applies migration 009) + let store = Store::open_file(&file).unwrap(); + assert_eq!(store.schema_version().unwrap(), 9); + + // Verify all original rows and fields survived byte-for-byte and constraint-wise + let coa_rec = store.character(char_coa).unwrap(); + assert_eq!(coa_rec.ruleset, Ruleset::Coa); + assert_eq!(coa_rec.name, "Varian"); + assert_eq!(coa_rec.revision, 1); + assert_eq!(coa_rec.level, 80); + assert_eq!(coa_rec.created_at, now); + + let wc_rec = store.character(char_wc).unwrap(); + assert_eq!(wc_rec.ruleset, Ruleset::Wildcard); + assert_eq!(wc_rec.name, "RogueMage"); + assert_eq!(wc_rec.revision, 2); + + // Verify child tables survived without cascading drop + let server_maps = store.server_mappings(char_coa).unwrap(); + assert_eq!(server_maps.len(), 1); + assert_eq!(server_maps[0].local_guid, 101); + + let item_maps = store.item_mappings(char_coa, "realm-a").unwrap(); + assert_eq!(item_maps.len(), 1); + assert_eq!(item_maps[0].portable_item_id, item_coa); + assert_eq!(item_maps[0].local_item_guid, 202); + + // Verify collection migrated to composite key (profile_id, ruleset, kind) + let coll_info = store + .collection_info(profile, Ruleset::Coa, "coa:appearance") + .unwrap() + .unwrap(); + assert_eq!(coll_info.revision, 1); + + // Verify insertion of Reborn character succeeds now on migrated DB + let char_rb = CharacterId::new(); + let rb_rec = store.conn.execute( + "INSERT INTO character (character_id, profile_id, ruleset, name, race, class, gender, level, revision, created_at, updated_at, archived) + VALUES (?1, ?2, 'reborn', 'Mograine', 'coa:race:1', 'coa:class:2', 0, 70, 1, ?3, ?3, 0)", + params![char_rb.to_string(), profile.to_string(), now], + ); + assert!( + rb_rec.is_ok(), + "migrated database must accept reborn ruleset" + ); + + let loaded_rb = store.character(char_rb).unwrap(); + assert_eq!(loaded_rb.ruleset, Ruleset::Reborn); + assert_eq!(loaded_rb.name, "Mograine"); + + // Verify invalid ruleset is still rejected by CHECK constraint + let err = store.conn.execute( + "INSERT INTO character (character_id, profile_id, ruleset, name, race, class, gender, level, revision, created_at, updated_at, archived) + VALUES (?1, ?2, 'invalid_ruleset', 'Bad', 'coa:race:1', 'coa:class:1', 0, 1, 1, ?3, ?3, 0)", + params![CharacterId::new().to_string(), profile.to_string(), now], + ); + assert!( + err.is_err(), + "migrated database must reject invalid ruleset" + ); +} diff --git a/crates/coa-core/src/realms.rs b/crates/coa-core/src/realms.rs index a408cfd..d0d0b00 100644 --- a/crates/coa-core/src/realms.rs +++ b/crates/coa-core/src/realms.rs @@ -23,10 +23,26 @@ pub enum Mode { impl Mode { pub fn name(self) -> &'static str { - match self { Self::Coa => "coa", Self::Wildcard => "wildcard", Self::Reborn => "reborn" } + match self { + Self::Coa => "coa", + Self::Wildcard => "wildcard", + Self::Reborn => "reborn", + } + } + pub fn realm_id(self) -> u32 { + match self { + Self::Coa => 1, + Self::Wildcard => 2, + Self::Reborn => 3, + } + } + pub fn label(self) -> &'static str { + match self { + Self::Coa => "Conquest of Azeroth", + Self::Wildcard => "Wildcard", + Self::Reborn => "Warcraft Reborn", + } } - pub fn realm_id(self) -> u32 { match self { Self::Coa => 1, Self::Wildcard => 2, Self::Reborn => 3 } } - pub fn label(self) -> &'static str { match self { Self::Coa => "Conquest of Azeroth", Self::Wildcard => "Wildcard", Self::Reborn => "Warcraft Reborn" } } pub fn schema(self, kind: &str) -> Result<&'static str> { match (self, kind) { (_, "auth") => Ok("acore_auth"), @@ -56,10 +72,20 @@ pub struct RealmState { } impl RealmState { - pub fn created(&self, mode: Mode) -> bool { match mode { Mode::Coa => true, Mode::Wildcard => self.wildcard_created, Mode::Reborn => self.reborn_created } } + pub fn created(&self, mode: Mode) -> bool { + match mode { + Mode::Coa => true, + Mode::Wildcard => self.wildcard_created, + Mode::Reborn => self.reborn_created, + } + } pub fn modes(&self) -> Vec { let mut modes = vec![self.active]; - modes.extend([Mode::Coa, Mode::Wildcard, Mode::Reborn].into_iter().filter(|m| *m != self.active && self.created(*m))); + modes.extend( + [Mode::Coa, Mode::Wildcard, Mode::Reborn] + .into_iter() + .filter(|m| *m != self.active && self.created(*m)), + ); modes } } @@ -98,9 +124,23 @@ pub fn view(root: &Path) -> Result { let s = state(root)?; // Inspect the binary itself; templates or an old log cannot prove installed support. let binary = fs::read(world_binary(root))?; - let reborn_supported = binary.windows(b"Warcraft Reborn class spells are unavailable".len()).any(|w| w == b"Warcraft Reborn class spells are unavailable"); - let supported = binary.windows(b"Wildcard synergy settings".len()).any(|w| w == b"Wildcard synergy settings"); - Ok(View { active: s.active, wildcard_created: s.wildcard_created, reborn_created: s.reborn_created, reborn_supported, supported, recovery_pending: root.join(JOURNAL).exists(), simultaneous: s.simultaneous, secondary_world_port: s.secondary_world_port, secondary_running: crate::multiworld::is_running(root) }) + let reborn_supported = binary + .windows(b"Warcraft Reborn class spells are unavailable".len()) + .any(|w| w == b"Warcraft Reborn class spells are unavailable"); + let supported = binary + .windows(b"Wildcard synergy settings".len()) + .any(|w| w == b"Wildcard synergy settings"); + Ok(View { + active: s.active, + wildcard_created: s.wildcard_created, + reborn_created: s.reborn_created, + reborn_supported, + supported, + recovery_pending: root.join(JOURNAL).exists(), + simultaneous: s.simultaneous, + secondary_world_port: s.secondary_world_port, + secondary_running: crate::multiworld::is_running(root), + }) } pub fn guard_module(root: &Path, id: &str) -> Result<()> { @@ -223,24 +263,53 @@ fn wildcard_configs(mut files: Files) -> Result { value, )?; } - set(&mut files, "Core/configs/modules/playerbots.conf", "AiPlayerbot.Enabled", "0")?; + set( + &mut files, + "Core/configs/modules/playerbots.conf", + "AiPlayerbot.Enabled", + "0", + )?; Ok(files) } fn reborn_configs(mut files: Files) -> Result { for (key, value) in [ - ("CoA.ClassModel", "\"wcr\""), ("CoA.GameModeMask", "0"), - ("CoA.MapClass10ToWarrior", "0"), ("CoA.RealmType", "\"live\""), + ("CoA.ClassModel", "\"wcr\""), + ("CoA.GameModeMask", "0"), + ("CoA.MapClass10ToWarrior", "0"), + ("CoA.RealmType", "\"live\""), ("CoA.ClientBooleanConfigs", "\"\""), - ] { set(&mut files, "Core/configs/modules/coa.conf", key, value)?; } - set(&mut files, "Core/configs/modules/mod-coa-challenges.conf", "CoAChallenges.GameModes.Realm", "\"\"")?; - for path in ["Settings/worldserver.conf.template", "Core/configs/worldserver.conf"] { - if files.contains_key(path) { set(&mut files, path, "RealmID", "3")?; } + ] { + set(&mut files, "Core/configs/modules/coa.conf", key, value)?; + } + set( + &mut files, + "Core/configs/modules/mod-coa-challenges.conf", + "CoAChallenges.GameModes.Realm", + "\"\"", + )?; + for path in [ + "Settings/worldserver.conf.template", + "Core/configs/worldserver.conf", + ] { + if files.contains_key(path) { + set(&mut files, path, "RealmID", "3")?; + } } for (key, value) in [("CoaBots.Enable", "0"), ("CoaBots.AutoLoginOnStartup", "0")] { - set(&mut files, "Core/configs/modules/mod_coa_playerbots.conf", key, value)?; + set( + &mut files, + "Core/configs/modules/mod_coa_playerbots.conf", + key, + value, + )?; } - set(&mut files, "Core/configs/modules/playerbots.conf", "AiPlayerbot.Enabled", "0")?; + set( + &mut files, + "Core/configs/modules/playerbots.conf", + "AiPlayerbot.Enabled", + "0", + )?; Ok(files) } @@ -278,8 +347,15 @@ pub fn recover(root: &Path) -> Result<()> { fn create_databases(root: &Path, mode: Mode) -> Result<()> { crate::backup::with_database(root, |_| { let db = Db::from_repack(root, Account::Admin)?.for_realm(Mode::Coa); - if db.query(&format!("SELECT COUNT(*) FROM acore_auth.realmlist WHERE id={};", mode.realm_id()))? != "0" { - return Err(Error::Invalid(format!("Realm ID {} is already in use. Its settings were left intact.", mode.realm_id()))); + if db.query(&format!( + "SELECT COUNT(*) FROM acore_auth.realmlist WHERE id={};", + mode.realm_id() + ))? != "0" + { + return Err(Error::Invalid(format!( + "Realm ID {} is already in use. Its settings were left intact.", + mode.realm_id() + ))); } for kind in ["world", "characters"] { let source = Mode::Coa.schema(kind)?; @@ -294,7 +370,10 @@ fn create_databases(root: &Path, mode: Mode) -> Result<()> { )); } } - for (kind, tables) in crate::schema_check::WILDCARD_TABLES.iter().filter(|_| mode == Mode::Wildcard) { + for (kind, tables) in crate::schema_check::WILDCARD_TABLES + .iter() + .filter(|_| mode == Mode::Wildcard) + { let schema = crate::db::schema_of(kind)?; let present = db.tables(schema)?; let missing: Vec<_> = tables @@ -384,21 +463,37 @@ pub fn select(root: &Path, mode: Mode) -> Result { )); } if mode == Mode::Reborn && !view(root)?.reborn_supported { - return Err(Error::Invalid("Update the server to a build with Warcraft Reborn support first.".into())); + return Err(Error::Invalid( + "Update the server to a build with Warcraft Reborn support first.".into(), + )); } if s.simultaneous && mode != s.active { - return Err(Error::Invalid("Disable simultaneous startup before switching realms.".into())); + return Err(Error::Invalid( + "Disable simultaneous startup before switching realms.".into(), + )); } // Verify launcher support before creating databases or changing the selected realm. prepare_launcher(root)?; let before = configs(root)?; fsx::atomic_write_json(&snapshot(root, s.active), &before)?; if !s.created(mode) { - let base = if s.active == Mode::Coa { before.clone() } else { fsx::read_json(&snapshot(root, Mode::Coa))? }; - let files = match mode { Mode::Wildcard => wildcard_configs(base)?, Mode::Reborn => reborn_configs(base)?, Mode::Coa => unreachable!() }; + let base = if s.active == Mode::Coa { + before.clone() + } else { + fsx::read_json(&snapshot(root, Mode::Coa))? + }; + let files = match mode { + Mode::Wildcard => wildcard_configs(base)?, + Mode::Reborn => reborn_configs(base)?, + Mode::Coa => unreachable!(), + }; fsx::atomic_write_json(&snapshot(root, mode), &files)?; create_databases(root, mode)?; - match mode { Mode::Wildcard => s.wildcard_created = true, Mode::Reborn => s.reborn_created = true, Mode::Coa => {} } + match mode { + Mode::Wildcard => s.wildcard_created = true, + Mode::Reborn => s.reborn_created = true, + Mode::Coa => {} + } fsx::atomic_write_json(&root.join(STATE), &s)?; } let target: Files = fsx::read_json(&snapshot(root, mode))?; @@ -481,9 +576,16 @@ const LAUNCHER_REALM_REPLACEMENTS: &[(&str, &str)] = &[ const LAUNCHER_REALM_INSERT: &str = "# coa-manager-realm-profiles-v1\ndef coa_realm():\n path = ROOT / 'Settings/realm-profile.json'\n return json.loads(path.read_text(encoding='utf-8')).get('active', 'coa') if path.exists() else 'coa'\n\ndef coa_realm_id():\n return 2 if coa_realm() == 'wildcard' else 1\n\ndef coa_realm_name():\n return 'Wildcard' if coa_realm() == 'wildcard' else 'Conquest of Azeroth'\n\n"; fn launcher_insert() -> String { - LAUNCHER_REALM_INSERT.replace("profiles-v1", "profiles-v2") - .replace("return 2 if", "return 3 if coa_realm() == 'reborn' else 2 if") - .replace("return 'Wildcard' if", "return 'Warcraft Reborn' if coa_realm() == 'reborn' else 'Wildcard' if") + LAUNCHER_REALM_INSERT + .replace("profiles-v1", "profiles-v2") + .replace( + "return 2 if", + "return 3 if coa_realm() == 'reborn' else 2 if", + ) + .replace( + "return 'Wildcard' if", + "return 'Warcraft Reborn' if coa_realm() == 'reborn' else 'Wildcard' if", + ) } fn launcher_replacements() -> Vec<(&'static str, String)> { @@ -493,19 +595,31 @@ fn launcher_replacements() -> Vec<(&'static str, String)> { } pub(crate) fn patch_launcher(source: &str) -> Result { - if source.contains("# coa-manager-realm-profiles-v2") { return Ok(source.into()); } + if source.contains("# coa-manager-realm-profiles-v2") { + return Ok(source.into()); + } if source.contains("# coa-manager-realm-profiles-v1") { - let original = unpatch_launcher(source).ok_or_else(|| Error::Invalid("Unrecognised realm launcher patch.".into()))?; + let original = unpatch_launcher(source) + .ok_or_else(|| Error::Invalid("Unrecognised realm launcher patch.".into()))?; return patch_launcher(&original); } let mut out = source.to_string(); for (from, to) in launcher_replacements() { - if !out.contains(from) { return Err(Error::Invalid("This launcher does not support realm profiles. Update the server package first.".into())); } + if !out.contains(from) { + return Err(Error::Invalid( + "This launcher does not support realm profiles. Update the server package first." + .into(), + )); + } out = out.replace(from, &to); } // Insert before the entry point so ROOT, json and functions are all defined when called. let marker = "if __name__ == \"__main__\":"; - if !out.contains(marker) { return Err(Error::Invalid("Unrecognised server launcher entry point.".into())); } + if !out.contains(marker) { + return Err(Error::Invalid( + "Unrecognised server launcher entry point.".into(), + )); + } Ok(out.replace(marker, &format!("{}{marker}", launcher_insert()))) } @@ -514,13 +628,28 @@ pub(crate) fn unpatch_launcher(source: &str) -> Option { let (insert, replacements) = if source.contains(&launcher_insert()) { (launcher_insert(), launcher_replacements()) } else if source.contains(LAUNCHER_REALM_INSERT) { - (LAUNCHER_REALM_INSERT.into(), LAUNCHER_REALM_REPLACEMENTS.iter().map(|(a,b)| (*a, b.to_string())).collect()) - } else { return None; }; + ( + LAUNCHER_REALM_INSERT.into(), + LAUNCHER_REALM_REPLACEMENTS + .iter() + .map(|(a, b)| (*a, b.to_string())) + .collect(), + ) + } else { + return None; + }; let mut original = source.replacen(&insert, "", 1); - for (from, to) in &replacements { original = original.replace(to, from); } + for (from, to) in &replacements { + original = original.replace(to, from); + } let mut check = original.clone(); - for (from, to) in &replacements { check = check.replace(from, to); } - check = check.replace("if __name__ == \"__main__\":", &format!("{insert}if __name__ == \"__main__\":")); + for (from, to) in &replacements { + check = check.replace(from, to); + } + check = check.replace( + "if __name__ == \"__main__\":", + &format!("{insert}if __name__ == \"__main__\":"), + ); (check == source).then_some(original) } @@ -531,18 +660,40 @@ pub fn before_start(root: &Path) -> Result<()> { return Ok(()); } prepare_launcher(root)?; - if s.simultaneous && !view(root)?.supported { return Err(Error::Invalid("The installed server build does not support simultaneous Wildcard startup.".into())); } - if s.simultaneous && s.active == Mode::Reborn { return Err(Error::Invalid("Simultaneous startup supports CoA and Wildcard only.".into())); } - if s.simultaneous { fsx::atomic_write_json(&snapshot(root, s.active), &configs(root)?)?; } - if s.active == Mode::Reborn && !view(root)?.reborn_supported { return Err(Error::Invalid("The installed server build does not support Warcraft Reborn.".into())); } + if s.simultaneous && !view(root)?.supported { + return Err(Error::Invalid( + "The installed server build does not support simultaneous Wildcard startup.".into(), + )); + } + if s.simultaneous && s.active == Mode::Reborn { + return Err(Error::Invalid( + "Simultaneous startup supports CoA and Wildcard only.".into(), + )); + } + if s.simultaneous { + fsx::atomic_write_json(&snapshot(root, s.active), &configs(root)?)?; + } + if s.active == Mode::Reborn && !view(root)?.reborn_supported { + return Err(Error::Invalid( + "The installed server build does not support Warcraft Reborn.".into(), + )); + } if s.active != Mode::Coa { - if s.active == Mode::Wildcard && !view(root)?.supported { return Err(Error::Invalid("The installed server build does not support Wildcard.".into())); } + if s.active == Mode::Wildcard && !view(root)?.supported { + return Err(Error::Invalid( + "The installed server build does not support Wildcard.".into(), + )); + } let path = root.join("Core/configs/modules/mod_coa_playerbots.conf"); let mut conf = ConfFile::parse_bytes(&fs::read(&path)?)?; conf.set("CoaBots.Enable", "0", &[]); fsx::atomic_write(&path, conf.to_text().as_bytes())?; let path = root.join("Core/configs/modules/playerbots.conf"); - let bytes = if path.exists() { fs::read(&path)? } else { b"[worldserver]\n".to_vec() }; + let bytes = if path.exists() { + fs::read(&path)? + } else { + b"[worldserver]\n".to_vec() + }; let mut conf = ConfFile::parse_bytes(&bytes)?; conf.set("AiPlayerbot.Enabled", "0", &[]); fsx::atomic_write(&path, conf.to_text().as_bytes())?; @@ -552,7 +703,9 @@ pub fn before_start(root: &Path) -> Result<()> { pub fn setup_realmlist(root: &Path) -> Result<()> { let s = state(root)?; - if !root.join(STATE).exists() { return Ok(()); } + if !root.join(STATE).exists() { + return Ok(()); + } let db = Db::from_repack(root, Account::Admin)?.for_realm(Mode::Coa); let port = layout::read_ports(root).world; for mode in s.modes().into_iter().filter(|m| *m != Mode::Coa) { @@ -560,8 +713,16 @@ pub fn setup_realmlist(root: &Path) -> Result<()> { let name = mode.label(); db.query(&format!("INSERT INTO acore_auth.realmlist (id,name,address,localAddress,localSubnetMask,port,icon,flag,timezone,gamebuild) SELECT {id},'{name}',address,localAddress,localSubnetMask,{port},icon,2,timezone,gamebuild FROM acore_auth.realmlist WHERE id=1 ON DUPLICATE KEY UPDATE port={port};"))?; } - let ids = s.modes().iter().map(|m| m.realm_id().to_string()).collect::>().join(","); - db.query(&format!("UPDATE acore_auth.realmlist SET flag=2 WHERE id IN ({ids}) AND id<>{};", s.active.realm_id()))?; + let ids = s + .modes() + .iter() + .map(|m| m.realm_id().to_string()) + .collect::>() + .join(","); + db.query(&format!( + "UPDATE acore_auth.realmlist SET flag=2 WHERE id IN ({ids}) AND id<>{};", + s.active.realm_id() + ))?; if s.simultaneous { let second = s .secondary_world_port @@ -582,10 +743,16 @@ mod tests { #[test] fn legacy_states_and_all_created_realms_are_enumerated_once() { - let legacy: RealmState = serde_json::from_str(r#"{"active":"wildcard","wildcard_created":true}"#).unwrap(); + let legacy: RealmState = + serde_json::from_str(r#"{"active":"wildcard","wildcard_created":true}"#).unwrap(); assert!(!legacy.reborn_created); assert_eq!(legacy.modes(), [Mode::Wildcard, Mode::Coa]); - let all = RealmState { active: Mode::Reborn, wildcard_created: true, reborn_created: true, ..Default::default() }; + let all = RealmState { + active: Mode::Reborn, + wildcard_created: true, + reborn_created: true, + ..Default::default() + }; assert_eq!(all.modes(), [Mode::Reborn, Mode::Coa, Mode::Wildcard]); assert_eq!(serde_json::to_string(&Mode::Reborn).unwrap(), "\"reborn\""); assert_eq!(Mode::Reborn.realm_id(), 3); @@ -596,19 +763,46 @@ mod tests { fn reborn_has_its_own_settings_and_restores_the_coa_profile() { let t = tempfile::tempdir().unwrap(); let mut coa = Files::new(); - coa.insert("Core/configs/modules/coa.conf".into(), b"[worldserver]\nCoA.ClassModel = coa\nCoA.GameModeMask = 0\n".to_vec()); - coa.insert("Settings/worldserver.conf.template".into(), b"[worldserver]\nRealmID = 1\n".to_vec()); - coa.insert("Core/configs/modules/playerbots.conf".into(), b"[worldserver]\nAiPlayerbot.Enabled = 1\n".to_vec()); + coa.insert( + "Core/configs/modules/coa.conf".into(), + b"[worldserver]\nCoA.ClassModel = coa\nCoA.GameModeMask = 0\n".to_vec(), + ); + coa.insert( + "Settings/worldserver.conf.template".into(), + b"[worldserver]\nRealmID = 1\n".to_vec(), + ); + coa.insert( + "Core/configs/modules/playerbots.conf".into(), + b"[worldserver]\nAiPlayerbot.Enabled = 1\n".to_vec(), + ); let reborn = reborn_configs(coa.clone()).unwrap(); let conf = ConfFile::parse_bytes(&reborn["Core/configs/modules/coa.conf"]).unwrap(); assert_eq!(conf.get("CoA.ClassModel"), Some("\"wcr\"")); assert_eq!(conf.get("CoA.GameModeMask"), Some("0")); - assert_eq!(ConfFile::parse_bytes(&reborn["Settings/worldserver.conf.template"]).unwrap().get("RealmID"), Some("3")); - assert_eq!(ConfFile::parse_bytes(&reborn["Core/configs/modules/playerbots.conf"]).unwrap().get("AiPlayerbot.Enabled"), Some("0")); + assert_eq!( + ConfFile::parse_bytes(&reborn["Settings/worldserver.conf.template"]) + .unwrap() + .get("RealmID"), + Some("3") + ); + assert_eq!( + ConfFile::parse_bytes(&reborn["Core/configs/modules/playerbots.conf"]) + .unwrap() + .get("AiPlayerbot.Enabled"), + Some("0") + ); write_configs(t.path(), &reborn).unwrap(); write_configs(t.path(), &coa).unwrap(); assert_eq!(configs(t.path()).unwrap(), coa); - fsx::atomic_write_json(&t.path().join(STATE), &RealmState { active: Mode::Reborn, reborn_created: true, ..Default::default() }).unwrap(); + fsx::atomic_write_json( + &t.path().join(STATE), + &RealmState { + active: Mode::Reborn, + reborn_created: true, + ..Default::default() + }, + ) + .unwrap(); assert!(guard_module(t.path(), "companions").is_err()); assert!(guard_module(t.path(), "playerbots").is_err()); assert!(guard_module(t.path(), "content-scaling").is_ok()); @@ -617,9 +811,17 @@ mod tests { #[test] fn reborn_support_requires_the_new_code_in_the_installed_binary() { let t = tempfile::tempdir().unwrap(); - fsx::atomic_write(&t.path().join("Core/worldserver.exe"), b"Wildcard synergy settings").unwrap(); + fsx::atomic_write( + &t.path().join("Core/worldserver.exe"), + b"Wildcard synergy settings", + ) + .unwrap(); assert!(!view(t.path()).unwrap().reborn_supported); - fsx::atomic_write(&t.path().join("Core/worldserver.exe"), b"Warcraft Reborn class spells are unavailable").unwrap(); + fsx::atomic_write( + &t.path().join("Core/worldserver.exe"), + b"Warcraft Reborn class spells are unavailable", + ) + .unwrap(); let v = view(t.path()).unwrap(); assert!(v.reborn_supported); assert!(!v.supported); @@ -629,8 +831,13 @@ mod tests { fn old_launcher_upgrades_and_both_patch_versions_are_reversible() { let original = "(\"WorldDatabaseInfo\", \"acore_world\")\n(\"CharacterDatabaseInfo\", \"acore_characters\")\nSET name='AzerothCore',address=\nWHERE id=1;\nmysql(\"UPDATE acore_auth.realmlist SET flag=0\nif __name__ == \"__main__\":\n"; let mut old = original.to_string(); - for (from, to) in LAUNCHER_REALM_REPLACEMENTS { old = old.replace(from, to); } - old = old.replace("if __name__ == \"__main__\":", &format!("{LAUNCHER_REALM_INSERT}if __name__ == \"__main__\":")); + for (from, to) in LAUNCHER_REALM_REPLACEMENTS { + old = old.replace(from, to); + } + old = old.replace( + "if __name__ == \"__main__\":", + &format!("{LAUNCHER_REALM_INSERT}if __name__ == \"__main__\":"), + ); assert_eq!(unpatch_launcher(&old).as_deref(), Some(original)); let new = patch_launcher(&old).unwrap(); assert!(new.contains("acore_world_reborn")); diff --git a/crates/coa-core/src/squid.rs b/crates/coa-core/src/squid.rs index f6cbb6d..8f42e3a 100644 --- a/crates/coa-core/src/squid.rs +++ b/crates/coa-core/src/squid.rs @@ -4,23 +4,57 @@ use std::path::Path; /// SQUID has its own import ledger, outside the signed package migration ledger. /// Keep this read-only: a pending base import can contain player data and must not /// be replayed or cleared merely because the normal schema contract passes. -pub(crate) fn database_problems(root: &Path, mode: crate::realms::Mode, query: &impl Fn(&str) -> crate::Result) -> crate::Result> { +pub(crate) fn database_problems( + root: &Path, + mode: crate::realms::Mode, + query: &impl Fn(&str) -> crate::Result, +) -> crate::Result> { let active = root.join("Core/configs/modules/playerbots.conf"); - let config = if active.is_file() { active } else { root.join("Core/configs/modules/playerbots.conf.dist") }; + let config = if active.is_file() { + active + } else { + root.join("Core/configs/modules/playerbots.conf.dist") + }; let enabled = if config.is_file() { let conf = crate::config::parser::ConfFile::parse_bytes(&std::fs::read(config)?)?; - !matches!(conf.get("AiPlayerbot.Enabled").unwrap_or("1").trim().trim_matches('"').to_ascii_lowercase().as_str(), "0" | "false" | "no" | "off") - } else { false }; + !matches!( + conf.get("AiPlayerbot.Enabled") + .unwrap_or("1") + .trim() + .trim_matches('"') + .to_ascii_lowercase() + .as_str(), + "0" | "false" | "no" | "off" + ) + } else { + false + }; let mut problems = Vec::new(); - for schema in [mode.schema("characters")?, mode.schema("world")?, "acore_playerbots"] { - let tables: std::collections::BTreeSet<_> = query(&format!("SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_SCHEMA='{schema}';"))?.lines().map(str::to_owned).collect(); + for schema in [ + mode.schema("characters")?, + mode.schema("world")?, + "acore_playerbots", + ] { + let tables: std::collections::BTreeSet<_> = query(&format!( + "SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_SCHEMA='{schema}';" + ))? + .lines() + .map(str::to_owned) + .collect(); if tables.contains("coa_squid_pending") { - for pending in query(&format!("SELECT path FROM `{schema}`.coa_squid_pending;"))?.lines().filter(|path| !path.is_empty()) { + for pending in query(&format!("SELECT path FROM `{schema}`.coa_squid_pending;"))? + .lines() + .filter(|path| !path.is_empty()) + { problems.push(crate::schema_check::Problem { database: schema.into(), table: "coa_squid_pending".into(), column: String::new(), detail: format!("SQUID base import was interrupted: {pending}. File repair and package SQL updates cannot complete this import. Restore a verified database backup from before the import; do not delete the pending record or replay base SQL.") }); } } if enabled && schema == mode.schema("characters")? { - for table in ["playerbots_names", "playerbots_guild_names", "playerbots_arena_team_names"] { + for table in [ + "playerbots_names", + "playerbots_guild_names", + "playerbots_arena_team_names", + ] { if !tables.contains(table) { problems.push(crate::schema_check::Problem { database: schema.into(), table: table.into(), column: String::new(), detail: "Required SQUID character table is missing. A normal server start provisions it when no interrupted import is present; an interrupted import requires database recovery first.".into() }); } @@ -237,9 +271,13 @@ mod tests { for mode in [crate::realms::Mode::Coa, crate::realms::Mode::Wildcard] { let problems = database_problems(root.path(), mode, &|sql| { assert!(sql.starts_with("SELECT ")); - if sql.contains("information_schema.TABLES") { Ok("coa_squid_pending".into()) } - else { Ok("playerbots/base/ai_playerbot_texts.sql".into()) } - }).unwrap(); + if sql.contains("information_schema.TABLES") { + Ok("coa_squid_pending".into()) + } else { + Ok("playerbots/base/ai_playerbot_texts.sql".into()) + } + }) + .unwrap(); assert_eq!(problems.len(), 3); assert_eq!(problems[0].database, mode.schema("characters").unwrap()); assert!(problems.iter().all(|p| p.detail.contains("interrupted"))); @@ -252,11 +290,26 @@ mod tests { let config = root.path().join("Core/configs/modules/playerbots.conf"); crate::fsx::atomic_write(&config, b"AiPlayerbot.Enabled = 1\n").unwrap(); let query = |_: &str| Ok(String::new()); - assert_eq!(database_problems(root.path(), crate::realms::Mode::Wildcard, &query).unwrap().len(), 3); + assert_eq!( + database_problems(root.path(), crate::realms::Mode::Wildcard, &query) + .unwrap() + .len(), + 3 + ); crate::fsx::atomic_write(&config, b"AiPlayerbot.Enabled = 0\n").unwrap(); - assert!(database_problems(root.path(), crate::realms::Mode::Wildcard, &query).unwrap().is_empty()); + assert!( + database_problems(root.path(), crate::realms::Mode::Wildcard, &query) + .unwrap() + .is_empty() + ); crate::fsx::atomic_write(&config, b"AiPlayerbot.Enabled = 1\n").unwrap(); - assert!(database_problems(root.path(), crate::realms::Mode::Coa, &|_| Ok("playerbots_names\nplayerbots_guild_names\nplayerbots_arena_team_names".into())).unwrap().is_empty()); + assert!( + database_problems(root.path(), crate::realms::Mode::Coa, &|_| Ok( + "playerbots_names\nplayerbots_guild_names\nplayerbots_arena_team_names".into() + )) + .unwrap() + .is_empty() + ); } #[test] fn a_setting_with_choices_only_accepts_one_of_them() { diff --git a/crates/coa-core/src/update.rs b/crates/coa-core/src/update.rs index 32e8d8f..9da99ed 100644 --- a/crates/coa-core/src/update.rs +++ b/crates/coa-core/src/update.rs @@ -1961,8 +1961,16 @@ fn database_identities( let mut identities = BTreeMap::new(); for (schema, table, columns) in [ ("acore_characters", "characters", "guid,account,HEX(name)"), - ("acore_characters_wildcard", "characters", "guid,account,HEX(name)"), - ("acore_characters_reborn", "characters", "guid,account,HEX(name)"), + ( + "acore_characters_wildcard", + "characters", + "guid,account,HEX(name)", + ), + ( + "acore_characters_reborn", + "characters", + "guid,account,HEX(name)", + ), ("acore_auth", "account", "id,HEX(username)"), ] { if !db.schema_exists(schema)? || !db.tables(schema)?.iter().any(|name| name == table) { diff --git a/crates/coa-core/src/update_isolation.rs b/crates/coa-core/src/update_isolation.rs index e0d38af..3e839d9 100644 --- a/crates/coa-core/src/update_isolation.rs +++ b/crates/coa-core/src/update_isolation.rs @@ -1,41 +1,71 @@ -use std::{collections::BTreeMap, fs, path::Path}; -use serde::{Deserialize, Serialize}; use crate::{config::parser::ConfFile, fsx, Error, Result}; +use serde::{Deserialize, Serialize}; +use std::{collections::BTreeMap, fs, path::Path}; const FILES: &[&str] = &[ - "Settings/repack.json", "Settings/realm-profile.json", - "Settings/worldserver.conf.template", "Settings/authserver.conf.template", - "Core/configs/worldserver.conf", "Core/configs/authserver.conf", - "Settings/realm-profiles/coa.json", "Settings/realm-profiles/wildcard.json", - ".realms/secondary/Settings/repack.json", ".realms/secondary/Settings/realm-profile.json", - ".realms/secondary/Settings/worldserver.conf.template", ".realms/secondary/Settings/authserver.conf.template", - ".realms/secondary/Core/configs/worldserver.conf", ".realms/secondary/Core/configs/authserver.conf", + "Settings/repack.json", + "Settings/realm-profile.json", + "Settings/worldserver.conf.template", + "Settings/authserver.conf.template", + "Core/configs/worldserver.conf", + "Core/configs/authserver.conf", + "Settings/realm-profiles/coa.json", + "Settings/realm-profiles/wildcard.json", + ".realms/secondary/Settings/repack.json", + ".realms/secondary/Settings/realm-profile.json", + ".realms/secondary/Settings/worldserver.conf.template", + ".realms/secondary/Settings/authserver.conf.template", + ".realms/secondary/Core/configs/worldserver.conf", + ".realms/secondary/Core/configs/authserver.conf", "Settings/realm-profiles/reborn.json", ]; #[derive(Serialize, Deserialize)] #[serde(deny_unknown_fields)] -struct Saved { bytes: Option>, sha256: Option } +struct Saved { + bytes: Option>, + sha256: Option, +} -pub(crate) fn pending(meta: &Path) -> bool { meta.join("validation-configs.json").exists() } +pub(crate) fn pending(meta: &Path) -> bool { + meta.join("validation-configs.json").exists() +} pub(crate) fn begin(root: &Path, meta: &Path) -> Result<()> { - if pending(meta) { return Err(Error::Invalid("Interrupted isolated validation must be recovered first.".into())); } + if pending(meta) { + return Err(Error::Invalid( + "Interrupted isolated validation must be recovered first.".into(), + )); + } let mut saved = BTreeMap::new(); for rel in FILES { let path = fsx::ensure_within(root, &fsx::safe_join(root, rel)?)?; - let bytes = if path.exists() { Some(fs::read(path)?) } else { None }; + let bytes = if path.exists() { + Some(fs::read(path)?) + } else { + None + }; let sha256 = bytes.as_ref().map(|b| fsx::sha256_bytes(b)); saved.insert(*rel, Saved { bytes, sha256 }); } let mut settings: serde_json::Value = fsx::read_json(&root.join("Settings/repack.json"))?; - let mut realm: Option = if root.join("Settings/realm-profile.json").exists() { + let mut realm: Option = if root.join("Settings/realm-profile.json").exists() + { Some(fsx::read_json(&root.join("Settings/realm-profile.json"))?) - } else { None }; - let mut excluded: std::collections::BTreeSet = ["mysqlPort", "authPort", "worldPort", "raPort"].iter() - .filter_map(|key| settings[*key].as_u64()).collect(); + } else { + None + }; + let mut excluded: std::collections::BTreeSet = + ["mysqlPort", "authPort", "worldPort", "raPort"] + .iter() + .filter_map(|key| settings[*key].as_u64()) + .collect(); if let Some(state) = &realm { - excluded.extend(["secondary_world_port", "secondary_ra_port"].iter().filter_map(|key| state[*key].as_u64())); + excluded.extend( + ["secondary_world_port", "secondary_ra_port"] + .iter() + .filter_map(|key| state[*key].as_u64()), + ); } let mut sockets = Vec::new(); let mut reserve = || -> Result { @@ -48,29 +78,84 @@ pub(crate) fn begin(root: &Path, meta: &Path) -> Result<()> { } } }; - for key in ["authPort", "worldPort", "raPort"] { settings[key] = reserve()?.into(); } + for key in ["authPort", "worldPort", "raPort"] { + settings[key] = reserve()?.into(); + } if let Some(state) = &mut realm { for key in ["secondary_world_port", "secondary_ra_port"] { state[key] = reserve()?.into(); } } let mut configs = Vec::new(); - for rel in ["Settings/worldserver.conf.template", "Settings/authserver.conf.template", "Core/configs/worldserver.conf", "Core/configs/authserver.conf"] { + for rel in [ + "Settings/worldserver.conf.template", + "Settings/authserver.conf.template", + "Core/configs/worldserver.conf", + "Core/configs/authserver.conf", + ] { let path = root.join(rel); if !path.exists() && rel.ends_with(".template") { - return Err(Error::Invalid(format!("Cannot isolate validation without {rel}."))); + return Err(Error::Invalid(format!( + "Cannot isolate validation without {rel}." + ))); } if path.exists() { let mut conf = ConfFile::parse_bytes(&fs::read(&path)?)?; conf.set("BindIP", "\"127.0.0.1\"", &[]); - if rel.contains("worldserver") { conf.set("Ra.IP", "\"127.0.0.1\"", &[]); } + if rel.contains("worldserver") { + conf.set("Ra.IP", "\"127.0.0.1\"", &[]); + } configs.push((path, conf.to_text())); } } fsx::atomic_write_json(&meta.join("validation-configs.json"), &saved)?; fsx::atomic_write_json(&root.join("Settings/repack.json"), &settings)?; - if let Some(state) = realm { fsx::atomic_write_json(&root.join("Settings/realm-profile.json"), &state)?; } - for (path, text) in configs { fsx::atomic_write(&path, text.as_bytes())?; } + if let Some(state) = realm { + fsx::atomic_write_json(&root.join("Settings/realm-profile.json"), &state)?; + } + for (path, text) in configs { + fsx::atomic_write(&path, text.as_bytes())?; + } + Ok(()) +} + +pub(crate) fn restore(root: &Path, meta: &Path) -> Result<()> { + if !pending(meta) { + return Ok(()); + } + let journal = meta.join("validation-configs.json"); + let saved: BTreeMap = fsx::read_json(&journal)?; + // Previous managers could journal only the first two profiles. Recover those + // journals too, while continuing to reject missing or unknown legacy entries. + let legacy = saved.len() == FILES.len() - 1 + && !saved.contains_key("Settings/realm-profiles/reborn.json"); + let required = if legacy { + &FILES[..FILES.len() - 1] + } else { + FILES + }; + if saved.len() != required.len() || required.iter().any(|rel| !saved.contains_key(*rel)) { + return Err(Error::Invalid( + "Isolated validation configuration journal is incomplete.".into(), + )); + } + for (rel, file) in &saved { + fsx::ensure_within(root, &fsx::safe_join(root, rel)?)?; + if file.bytes.as_ref().map(|b| fsx::sha256_bytes(b)) != file.sha256 { + return Err(Error::Invalid(format!( + "Isolated validation recovery copy {rel} is damaged." + ))); + } + } + for (rel, file) in saved { + let path = fsx::ensure_within(root, &fsx::safe_join(root, &rel)?)?; + match file.bytes { + Some(bytes) => fsx::atomic_write(&path, &bytes)?, + None if path.exists() => fs::remove_file(path)?, + None => {} + } + } + fs::remove_file(journal)?; Ok(()) } @@ -84,10 +169,18 @@ mod tests { let meta = dir.path().join("metadata"); fs::create_dir_all(root.join("Settings")).unwrap(); fs::create_dir_all(&meta).unwrap(); - fsx::atomic_write_json(&root.join(FILES[0]), &serde_json::json!({"mysqlPort":3306,"authPort":3724,"worldPort":8085,"raPort":3443})).unwrap(); + fsx::atomic_write_json( + &root.join(FILES[0]), + &serde_json::json!({"mysqlPort":3306,"authPort":3724,"worldPort":8085,"raPort":3443}), + ) + .unwrap(); fsx::atomic_write_json(&root.join(FILES[1]), &serde_json::json!({"simultaneous":true,"secondary_world_port":8086,"secondary_ra_port":3444})).unwrap(); for rel in [FILES[2], FILES[3]] { - fsx::atomic_write(&root.join(rel), b"BindIP = \"0.0.0.0\"\r\nRa.IP = \"0.0.0.0\"\r\n").unwrap(); + fsx::atomic_write( + &root.join(rel), + b"BindIP = \"0.0.0.0\"\r\nRa.IP = \"0.0.0.0\"\r\n", + ) + .unwrap(); } (dir, root, meta) } @@ -95,7 +188,11 @@ mod tests { #[test] fn interrupted_validation_restores_original_bytes_and_absent_files() { let (_dir, root, meta) = fixture(); - fsx::atomic_write(&root.join("Settings/realm-profiles/reborn.json"), b"saved reborn profile").unwrap(); + fsx::atomic_write( + &root.join("Settings/realm-profiles/reborn.json"), + b"saved reborn profile", + ) + .unwrap(); let original: Vec<_> = FILES.iter().map(|p| fs::read(root.join(p)).ok()).collect(); begin(&root, &meta).unwrap(); assert!(crate::update::ensure_recovered(&meta).is_err()); @@ -103,14 +200,28 @@ mod tests { let settings: serde_json::Value = fsx::read_json(&root.join(FILES[0])).unwrap(); assert_eq!(settings["mysqlPort"], 3306); let realm: serde_json::Value = fsx::read_json(&root.join(FILES[1])).unwrap(); - let ports: std::collections::BTreeSet<_> = [settings["authPort"].as_u64(), settings["worldPort"].as_u64(), settings["raPort"].as_u64(), realm["secondary_world_port"].as_u64(), realm["secondary_ra_port"].as_u64()].into_iter().collect(); + let ports: std::collections::BTreeSet<_> = [ + settings["authPort"].as_u64(), + settings["worldPort"].as_u64(), + settings["raPort"].as_u64(), + realm["secondary_world_port"].as_u64(), + realm["secondary_ra_port"].as_u64(), + ] + .into_iter() + .collect(); assert_eq!(ports.len(), 5); let config = ConfFile::parse_bytes(&fs::read(root.join(FILES[2])).unwrap()).unwrap(); assert_eq!(config.get("BindIP"), Some("\"127.0.0.1\"")); fsx::atomic_write(&root.join(FILES[4]), b"rendered temporary configuration").unwrap(); - fsx::atomic_write(&root.join("Settings/realm-profiles/reborn.json"), b"temporary reborn profile").unwrap(); + fsx::atomic_write( + &root.join("Settings/realm-profiles/reborn.json"), + b"temporary reborn profile", + ) + .unwrap(); restore(&root, &meta).unwrap(); - for (rel, bytes) in FILES.iter().zip(original) { assert_eq!(fs::read(root.join(rel)).ok(), bytes); } + for (rel, bytes) in FILES.iter().zip(original) { + assert_eq!(fs::read(root.join(rel)).ok(), bytes); + } assert!(!pending(&meta)); restore(&root, &meta).unwrap(); } @@ -139,32 +250,3 @@ mod tests { assert_eq!(fs::read(root.join(FILES[0])).unwrap(), before); } } - -pub(crate) fn restore(root: &Path, meta: &Path) -> Result<()> { - if !pending(meta) { return Ok(()); } - let journal = meta.join("validation-configs.json"); - let saved: BTreeMap = fsx::read_json(&journal)?; - // Previous managers could journal only the first two profiles. Recover those - // journals too, while continuing to reject missing or unknown legacy entries. - let legacy = saved.len() == FILES.len() - 1 && !saved.contains_key("Settings/realm-profiles/reborn.json"); - let required = if legacy { &FILES[..FILES.len() - 1] } else { FILES }; - if saved.len() != required.len() || required.iter().any(|rel| !saved.contains_key(*rel)) { - return Err(Error::Invalid("Isolated validation configuration journal is incomplete.".into())); - } - for (rel, file) in &saved { - fsx::ensure_within(root, &fsx::safe_join(root, rel)?)?; - if file.bytes.as_ref().map(|b| fsx::sha256_bytes(b)) != file.sha256 { - return Err(Error::Invalid(format!("Isolated validation recovery copy {rel} is damaged."))); - } - } - for (rel, file) in saved { - let path = fsx::ensure_within(root, &fsx::safe_join(root, &rel)?)?; - match file.bytes { - Some(bytes) => fsx::atomic_write(&path, &bytes)?, - None if path.exists() => fs::remove_file(path)?, - None => {}, - } - } - fs::remove_file(journal)?; - Ok(()) -} diff --git a/crates/coa-core/src/update_route.rs b/crates/coa-core/src/update_route.rs index 5cabaac..f0b712a 100644 --- a/crates/coa-core/src/update_route.rs +++ b/crates/coa-core/src/update_route.rs @@ -1,4 +1,9 @@ -use crate::{manifest::Manifest, pkgsource::{self, Source}, registry::InstallMeta, update, Result}; +use crate::{ + manifest::Manifest, + pkgsource::{self, Source}, + registry::InstallMeta, + update, Result, +}; #[derive(Debug)] pub struct Selection { @@ -8,13 +13,22 @@ pub struct Selection { } pub fn select(meta: &InstallMeta, source: Source, key: &str) -> Result { - select_with(meta, source, &mut |source| pkgsource::fetch_manifest(source, key)) + select_with(meta, source, &mut |source| { + pkgsource::fetch_manifest(source, key) + }) } -fn select_with(meta: &InstallMeta, source: Source, fetch: &mut impl FnMut(&Source) -> Result<(Manifest, Vec)>) -> Result { +fn select_with( + meta: &InstallMeta, + source: Source, + fetch: &mut impl FnMut(&Source) -> Result<(Manifest, Vec)>, +) -> Result { let (manifest, _) = fetch(&source)?; update::validate_candidate(meta, &manifest)?; - Ok(Selection { source, latest_version: None }) + Ok(Selection { + source, + latest_version: None, + }) } #[cfg(test)] @@ -42,23 +56,51 @@ mod tests { let folder = tempfile::tempdir().unwrap(); let signing = SigningKey::from_bytes(&[37; 32]); let bytes = serde_json::to_vec(value).unwrap(); - fs::write(folder.path().join("manifest.json.sig"), STANDARD.encode(signing.sign(&bytes).to_bytes())).unwrap(); - fs::write(folder.path().join("manifest.json"), if tamper { b"tampered".as_slice() } else { &bytes }).unwrap(); + fs::write( + folder.path().join("manifest.json.sig"), + STANDARD.encode(signing.sign(&bytes).to_bytes()), + ) + .unwrap(); + fs::write( + folder.path().join("manifest.json"), + if tamper { + b"tampered".as_slice() + } else { + &bytes + }, + ) + .unwrap(); (folder, STANDARD.encode(signing.verifying_key().to_bytes())) } #[test] fn every_known_older_version_selects_the_latest_signed_package_once() { - for installed in ["0.2.0", "0.261004.20", "0.261005.0", "0.261007.24", "0.261011.800006", "0.261013.54", "0.261015.58"] { + for installed in [ + "0.2.0", + "0.261004.20", + "0.261005.0", + "0.261007.24", + "0.261011.800006", + "0.261013.54", + "0.261015.58", + ] { let (folder, key) = fixture(&package(), false); - for kind in [crate::registry::InstallKind::New, crate::registry::InstallKind::Imported] { + for kind in [ + crate::registry::InstallKind::New, + crate::registry::InstallKind::Imported, + ] { let mut installation = meta(installed); installation.kind = kind; let mut calls = 0; - let selected = select_with(&installation, Source::Dir(folder.path().into()), &mut |source| { - calls += 1; - pkgsource::fetch_manifest(source, &key) - }).unwrap(); + let selected = select_with( + &installation, + Source::Dir(folder.path().into()), + &mut |source| { + calls += 1; + pkgsource::fetch_manifest(source, &key) + }, + ) + .unwrap(); assert!(matches!(selected.source, Source::Dir(path) if path == folder.path())); assert!(selected.latest_version.is_none()); assert_eq!(calls, 1, "no intermediate package fetches for {installed}"); @@ -77,17 +119,33 @@ mod tests { #[test] fn signed_target_is_required_even_for_unlisted_old_versions() { let (folder, key) = fixture(&package(), true); - assert!(select(&meta("0.261004.20"), Source::Dir(folder.path().into()), &key).is_err()); + assert!(select( + &meta("0.261004.20"), + Source::Dir(folder.path().into()), + &key + ) + .is_err()); } #[test] fn platform_and_manager_requirements_are_still_enforced() { - for (field, value) in [("minManagerVersion", "99.0.0"), ("platform", "other-platform")] { + for (field, value) in [ + ("minManagerVersion", "99.0.0"), + ("platform", "other-platform"), + ] { let mut target = package(); - if field == "platform" { target["compatibility"][field] = value.into(); } - else { target[field] = value.into(); } + if field == "platform" { + target["compatibility"][field] = value.into(); + } else { + target[field] = value.into(); + } let (folder, key) = fixture(&target, false); - assert!(select(&meta("0.261004.20"), Source::Dir(folder.path().into()), &key).is_err()); + assert!(select( + &meta("0.261004.20"), + Source::Dir(folder.path().into()), + &key + ) + .is_err()); } } } diff --git a/crates/coa-release/src/main.rs b/crates/coa-release/src/main.rs index 922958f..38f5ec9 100644 --- a/crates/coa-release/src/main.rs +++ b/crates/coa-release/src/main.rs @@ -56,58 +56,104 @@ fn run() -> Result<(), String> { .unwrap_or(DEFAULT_PART_SIZE); match cmd.as_str() { "plan-update" => { - let mut meta = coa_core::registry::InstallMeta::new(coa_core::registry::InstallKind::New, std::path::Path::new("unused")); + let mut meta = coa_core::registry::InstallMeta::new( + coa_core::registry::InstallKind::New, + std::path::Path::new("unused"), + ); meta.core.version = Some(need(&a, "from")?.clone()); - let selection = coa_core::update_route::select(&meta, coa_core::pkgsource::Source::Url(need(&a, "source")?.clone()), coa_core::signing::EMBEDDED_PUBLIC_KEY).map_err(e)?; - let (manifest, _) = coa_core::pkgsource::fetch_manifest(&selection.source, coa_core::signing::EMBEDDED_PUBLIC_KEY).map_err(e)?; - println!("{}", serde_json::json!({"from":meta.core.version,"next":manifest.version,"latest":selection.latest_version})); + let selection = coa_core::update_route::select( + &meta, + coa_core::pkgsource::Source::Url(need(&a, "source")?.clone()), + coa_core::signing::EMBEDDED_PUBLIC_KEY, + ) + .map_err(e)?; + let (manifest, _) = coa_core::pkgsource::fetch_manifest( + &selection.source, + coa_core::signing::EMBEDDED_PUBLIC_KEY, + ) + .map_err(e)?; + println!( + "{}", + serde_json::json!({"from":meta.core.version,"next":manifest.version,"latest":selection.latest_version}) + ); } "verify-install" => { coa_core::release_schema::verify_install_package( - &PathBuf::from(need(&a, "dir")?), coa_core::signing::EMBEDDED_PUBLIC_KEY, - ).map_err(e)?; + &PathBuf::from(need(&a, "dir")?), + coa_core::signing::EMBEDDED_PUBLIC_KEY, + ) + .map_err(e)?; } "compose-install" => { coa_core::release_schema::compose_install( - &PathBuf::from(need(&a, "base")?), &PathBuf::from(need(&a, "candidate")?), - &PathBuf::from(need(&a, "fixture")?), coa_core::signing::EMBEDDED_PUBLIC_KEY, - ).map_err(e)?; + &PathBuf::from(need(&a, "base")?), + &PathBuf::from(need(&a, "candidate")?), + &PathBuf::from(need(&a, "fixture")?), + coa_core::signing::EMBEDDED_PUBLIC_KEY, + ) + .map_err(e)?; } "qualify-install" => { let report = coa_core::release_schema::qualify_install( - &PathBuf::from(need(&a, "package")?), &PathBuf::from(need(&a, "fixture")?), + &PathBuf::from(need(&a, "package")?), + &PathBuf::from(need(&a, "fixture")?), coa_core::signing::EMBEDDED_PUBLIC_KEY, - ).map_err(e)?; - coa_core::fsx::atomic_write_json(&PathBuf::from(need(&a, "report")?), &report).map_err(e)?; + ) + .map_err(e)?; + coa_core::fsx::atomic_write_json(&PathBuf::from(need(&a, "report")?), &report) + .map_err(e)?; } "qualify-upgrade" => { let report = coa_core::release_schema::qualify_upgrade( - &PathBuf::from(need(&a, "base")?), &PathBuf::from(need(&a, "source")?), - &PathBuf::from(need(&a, "candidate")?), &PathBuf::from(need(&a, "fixture")?), + &PathBuf::from(need(&a, "base")?), + &PathBuf::from(need(&a, "source")?), + &PathBuf::from(need(&a, "candidate")?), + &PathBuf::from(need(&a, "fixture")?), coa_core::signing::EMBEDDED_PUBLIC_KEY, - ).map_err(e)?; - coa_core::fsx::atomic_write_json(&PathBuf::from(need(&a, "report")?), &report).map_err(e)?; + ) + .map_err(e)?; + coa_core::fsx::atomic_write_json(&PathBuf::from(need(&a, "report")?), &report) + .map_err(e)?; println!("Manager upgrade transaction passed isolated qualification"); } "qualify-startup" => { coa_core::release_schema::validate_startup( - &PathBuf::from(need(&a, "fixture")?), &PathBuf::from(need(&a, "tree")?), - &PathBuf::from(need(&a, "base")?), coa_core::signing::EMBEDDED_PUBLIC_KEY, - ).map_err(e)?; + &PathBuf::from(need(&a, "fixture")?), + &PathBuf::from(need(&a, "tree")?), + &PathBuf::from(need(&a, "base")?), + coa_core::signing::EMBEDDED_PUBLIC_KEY, + ) + .map_err(e)?; println!("authserver and worldserver passed isolated startup qualification"); } "verify-channel" => { let bytes = std::fs::read(need(&a, "file")?).map_err(|x| x.to_string())?; - let pointer = coa_core::channels::verify(&bytes, need(&a, "channel")?, coa_core::signing::EMBEDDED_PUBLIC_KEY).map_err(e)?; - println!("{}", serde_json::to_string(&pointer).map_err(|x| x.to_string())?); + let pointer = coa_core::channels::verify( + &bytes, + need(&a, "channel")?, + coa_core::signing::EMBEDDED_PUBLIC_KEY, + ) + .map_err(e)?; + println!( + "{}", + serde_json::to_string(&pointer).map_err(|x| x.to_string())? + ); } "verify-manifest" => { let source = coa_core::pkgsource::Source::Dir(PathBuf::from(need(&a, "dir")?)); - let (manifest, _) = coa_core::pkgsource::fetch_manifest(&source, coa_core::signing::EMBEDDED_PUBLIC_KEY).map_err(e)?; + let (manifest, _) = coa_core::pkgsource::fetch_manifest( + &source, + coa_core::signing::EMBEDDED_PUBLIC_KEY, + ) + .map_err(e)?; println!("verified signed manifest {}", manifest.version); } "verify-upgrade-fixture" => { - coa_core::release_schema::verify_upgrade_fixture(&PathBuf::from(need(&a, "dir")?), coa_core::signing::EMBEDDED_PUBLIC_KEY).map_err(e)?; + coa_core::release_schema::verify_upgrade_fixture( + &PathBuf::from(need(&a, "dir")?), + coa_core::signing::EMBEDDED_PUBLIC_KEY, + ) + .map_err(e)?; println!("verified signed upgrade fixture and every archive file"); } "extract-schema-base" => { @@ -252,7 +298,8 @@ fn run() -> Result<(), String> { } "sign-channel" => { let pointer = coa_core::channels::Pointer { - schema: 1, channel: need(&a, "channel")?.clone(), + schema: 1, + channel: need(&a, "channel")?.clone(), version: need(&a, "version")?.clone(), release_tag: format!("server-{}", need(&a, "version")?), snapshot: need(&a, "snapshot")?.clone(), diff --git a/docs/MULTIRULESET_PORTABLE_AUDIT.md b/docs/MULTIRULESET_PORTABLE_AUDIT.md index 5c4567e..9af393d 100644 --- a/docs/MULTIRULESET_PORTABLE_AUDIT.md +++ b/docs/MULTIRULESET_PORTABLE_AUDIT.md @@ -1,25 +1,41 @@ # Multi-Ruleset Realms & Portable Characters: Architectural Audit -This audit evaluates the released **CoA Server Manager v0.7.0/v0.7.1** architecture to support three independent, strictly isolated gameplay rulesets: +This audit evaluates the architecture to support three independent, strictly isolated gameplay rulesets: 1. **Conquest of Azeroth (`coa`)** 2. **Wildcard (`wildcard`)** 3. **Warcraft Reborn (`reborn`)** Date: October 2026 -Status: Pre-Implementation Audit Baseline +Status: Updated for MR1.1 Gate (Post-Foundation Fixes) --- -## 1. Executive Summary & Existing Representation +## 1. Executive Summary: Baseline vs Implemented vs Planned -Current codebase inspection reveals that while `realms::Mode` already defines `Coa`, `Wildcard`, and `Reborn` for local realm profiles and database switching, the **Portable Characters and Public Realm Registry subsystems** were designed almost entirely around `coa`, with experimental/preliminary partial awareness of `wildcard`, and an explicit blocking error for `reborn` (`ruleset_of`: *"Portable characters are not supported on Warcraft Reborn realms yet"*). +### 1.1 Baseline Discovered Before Implementation (v0.7.0 Master) +- `realms::Mode` defined `Coa`, `Wildcard`, and `Reborn` for local realm profiles and database switching (`acore_characters`, `acore_characters_wildcard`, `acore_characters_reborn`). +- The **Portable Characters and Public Realm Registry subsystems** were designed almost entirely around `coa`, with experimental/preliminary partial awareness of `wildcard`, and an explicit blocking error for `reborn` (`ruleset_of`: *"Portable characters are not supported on Warcraft Reborn realms yet"*). +- SQLite `character` table had `CHECK (ruleset IN ('coa', 'wildcard'))`, which hard-failed on any `reborn` row. +- SQLite `collection` table was keyed by `(profile_id, kind)` without `ruleset`, causing cross-ruleset collision. +- `Request::TransferOffer`, `PortableSessionStarted`, `PortableCheckpoint`, `OwnerAck`, `CollectionObserved`, `CollectionState`, and `CollectionAck` lacked explicit protocol-level `ruleset` fields or version negotiation. +- Collection validation used unsafe prefix checks (`kind.starts_with(ruleset)`), permitting prefix confusion attacks. +- `Ruleset::schema(kind)` contained a fallback `_ => "acore_characters"`, routing unknown database kinds to CoA. -Furthermore, several critical isolation gaps exist across the stack: -- **Registry & Host Identity Conflation:** Local realm publication keys by `srv-` rather than by `(installation_id, ruleset)`. A host running multiple modes (or switching modes) risks mutating or conflating public realm identity. -- **Collection Bucket Shared per Profile:** Canonical collection storage (`collection` table) is keyed by `(profile_id, kind)` with fixed strings like `coa:appearance` and `coa:vanity`. Wildcard and Reborn collections cannot safely share these keys or numeric id sets without risking collision and cross-ruleset leakage. -- **Store Schema Constraints:** SQLite `character` table and PostgreSQL Registry `realm` table enforce `CHECK (ruleset IN ('coa', 'wildcard'))`, which rejects `reborn`. -- **Remote Control & Session Protocols:** `TransferOffer`, `PortableSessionStarted`, `PortableCheckpoint`, and `OwnerAck` messages do not bind `ruleset` in their envelopes, relying solely on character snapshot payload validation or local mapping lookups. -- **Capability Profiles:** `RealmCapabilities` reports and negotiation hardcode expectations around `coa`, blocking other rulesets. +### 1.2 Implemented in 58a99f0+ and MR1.1 +- **Authoritative Ruleset Enum:** `Ruleset` (`Coa`, `Wildcard`, `Reborn`) unified across `coa-core`, `coa-registry-proto`, `coa-control-proto`, and frontend models. +- **Transactional SQLite Migration 009:** Migrates released v0.7.x databases by recreating both `collection` (composite key `profile_id, ruleset, kind`) and `character` (CHECK constraint allowing `'coa', 'wildcard', 'reborn'`) with FK toggles ensuring zero child row loss. +- **Protocol Versioning & Negotiation:** + - Control protocol bumped to `CONTROL_PROTOCOL_VERSION = 2`. `Request::TransferOffer` requires `ruleset: String` (no default). + - Session protocol bumped to `SESSION_PROTOCOL_VERSION = 3`. `SessionOffer`, `PortableSessionStarted`, `PortableCheckpoint`, and `OwnerAck` require explicit `ruleset` (no serde defaults). Old v2 messages require explicit legacy translation. + - Collection protocol set to `COLLECTION_PROTOCOL_VERSION = 2`. `CollectionObserved`, `CollectionState`, and `CollectionAck` require explicit `ruleset`. +- **Schema Safety:** Unsafe fallback in `Ruleset::schema(kind)` removed; unknown database kinds return a hard error. +- **Exact Collection Namespace Validation:** `carried_kind_for(kind, ruleset)` strictly validates allowed collection kinds; prefix confusion attacks (`coax:appearance`, etc.) are rejected with zero mutation. +- **Multi-Realm Local Key Resolution:** `find_access` resolves composite keys `srv-:` while retaining `srv-` for existing single-realm publication until MR4. + +### 1.3 Still Planned (Subsequent Milestones) +- **MR2 (Wildcard Vertical Slice):** Full end-to-end import/export, session runtime, and live verification of Wildcard gameplay. +- **MR3 (Warcraft Reborn Vertical Slice):** Unlocking `ruleset_of` for Reborn, import/export adapters, and live verification. +- **MR4 (Multi-Realm Publication UI & Registry):** Simultaneous publication of multiple RealmIds from a single Manager host under distinct identities and keypairs. --- diff --git a/docs/REBORN_PORTABLE_AUDIT.md b/docs/REBORN_PORTABLE_AUDIT.md index e170dd6..2299968 100644 --- a/docs/REBORN_PORTABLE_AUDIT.md +++ b/docs/REBORN_PORTABLE_AUDIT.md @@ -1,13 +1,26 @@ # Warcraft Reborn Portable Characters Audit -## 1. Overview & Current State -The master branch codebase already contains foundational support for Warcraft Reborn (`Mode::Reborn`, realm ID `3`, characters DB `acore_characters_reborn`, world DB `acore_world_reborn`, shared auth DB `acore_auth`). -In previous releases (v0.7.0), portable character transfers into Warcraft Reborn were temporarily guarded by: +## 1. Overview & Baseline vs Current Implementation + +### 1.1 Baseline Discovered Before Implementation +The released v0.7.0 master branch codebase contained foundational support for local realm execution (`Mode::Reborn`, realm ID `3`, characters DB `acore_characters_reborn`, world DB `acore_world_reborn`, shared auth DB `acore_auth`). +Portable character transfers into Warcraft Reborn were temporarily guarded by: ```rust // crates/coa-core/src/portable/realm/mod.rs Mode::Reborn => Err(PortableError::Invalid("Portable characters are not supported on Warcraft Reborn realms yet.".into())), ``` +### 1.2 Implemented in 58a99f0+ and MR1.1 +- **RulesetId / Ruleset**: `Ruleset::Reborn` is established across `coa-core`, `coa-registry-proto`, `coa-control-proto`, and TypeScript models (`"reborn"` wire value, display name `"Warcraft Reborn"`). +- **SQLite Portable Storage:** Migration `009_multiruleset.sql` upgrades released databases to permit `reborn` characters in the `character` table CHECK constraint without dropping child records. +- **Collections:** `reborn:appearance` and `reborn:vanity` defined and carried under exact allowlist in `carried_kind_for`. Partitioned under `(profile_id, 'reborn', kind)`. +- **Wire Protocols:** Control protocol v2, Session protocol v3, and Collection protocol v2 bind `ruleset: Ruleset` explicitly in all messages. + +### 1.3 Still Planned (MR3 Phase) +- Implement concrete gameplay adapter for Reborn character import/export. +- Flip `ruleset_of(&reborn_db)` from the temporary error to `Ok(Ruleset::Reborn)`. +- End-to-end regression testing of Reborn characters and strict isolation gates. + ## 2. Ruleset Identity & DB Schemas - **RulesetId / Ruleset**: - `Ruleset::Reborn` exists in `crates/coa-core/src/portable/model.rs` and `crates/coa-registry-proto/src/caps.rs`. diff --git a/services/coa-control-e2e/Cargo.lock b/services/coa-control-e2e/Cargo.lock index d335b00..3c0983d 100644 --- a/services/coa-control-e2e/Cargo.lock +++ b/services/coa-control-e2e/Cargo.lock @@ -356,7 +356,7 @@ dependencies = [ [[package]] name = "coa-core" -version = "0.6.7" +version = "0.7.1" dependencies = [ "base64 0.22.1", "chrono", @@ -364,6 +364,7 @@ dependencies = [ "coa-registry-proto", "dunce", "ed25519-dalek", + "flate2", "fs4", "hex", "if-addrs", @@ -743,6 +744,7 @@ checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb" dependencies = [ "crc32fast", "miniz_oxide", + "zlib-rs", ] [[package]] @@ -3079,6 +3081,12 @@ dependencies = [ "zopfli", ] +[[package]] +name = "zlib-rs" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" + [[package]] name = "zmij" version = "1.0.23" diff --git a/services/coa-control-e2e/tests/control.rs b/services/coa-control-e2e/tests/control.rs index 3a912b3..8a1bb72 100644 --- a/services/coa-control-e2e/tests/control.rs +++ b/services/coa-control-e2e/tests/control.rs @@ -377,7 +377,7 @@ fn remote_transfer_over_coordinator_channel_e2e() { let collections = BTreeMap::from([("coa:appearance".to_string(), vec![42, 99])]); // Perform transfer - let outcome = pc.transfer_character(&mut ch, cid, 1, &payload, hash, collections.clone()).unwrap(); + let outcome = pc.transfer_character(&mut ch, cid, "coa", 1, &payload, hash, collections.clone()).unwrap(); assert!(outcome.local_guid > 0); assert_ne!(outcome.session_id, Uuid::nil()); @@ -386,20 +386,20 @@ fn remote_transfer_over_coordinator_channel_e2e() { assert!(!env.wire_contains("Varian"), "account name was encrypted"); // Idempotent retry with same payload discovers existing commit - let retry_outcome = pc.transfer_character(&mut ch, cid, 1, &payload, hash, collections.clone()).unwrap(); + let retry_outcome = pc.transfer_character(&mut ch, cid, "coa", 1, &payload, hash, collections.clone()).unwrap(); assert_eq!(outcome.local_guid, retry_outcome.local_guid); assert_eq!(outcome.session_id, retry_outcome.session_id); // Update with revision 2 updates working copy without duplicate let payload2 = b"SECRET_PORTABLE_CHARACTER_PAYLOAD_VARIAN_REV2".to_vec(); let hash2: [u8; 32] = Sha256::digest(&payload2).into(); - let update_outcome = pc.transfer_character(&mut ch, cid, 2, &payload2, hash2, collections).unwrap(); + let update_outcome = pc.transfer_character(&mut ch, cid, "coa", 2, &payload2, hash2, collections).unwrap(); assert_eq!(outcome.local_guid, update_outcome.local_guid); // Incompatible realm rejects let incomp_id = Uuid::now_v7(); env.fake.incompatible.lock().unwrap().insert(incomp_id); - let err = pc.transfer_character(&mut ch, incomp_id, 1, b"any", [0u8; 32], BTreeMap::new()).unwrap_err(); + let err = pc.transfer_character(&mut ch, incomp_id, "coa", 1, b"any", [0u8; 32], BTreeMap::new()).unwrap_err(); assert_eq!(err.code(), "incompatible"); } @@ -426,13 +426,13 @@ fn remote_transfer_worst_case_large_payload_near_limit() { massive_collections.insert("coa:appearance".to_string(), ids); let cid = Uuid::now_v7(); - let outcome = pc.transfer_character(&mut ch, cid, 1, &large_payload, large_hash, massive_collections).unwrap(); + let outcome = pc.transfer_character(&mut ch, cid, "coa", 1, &large_payload, large_hash, massive_collections).unwrap(); assert!(outcome.local_guid > 0); assert_ne!(outcome.session_id, Uuid::nil()); // 2. Standard request exceeding 4096 bytes is rejected let bloated_hello = coa_control_proto::app::Request::Hello { - protocol: 1, + protocol: coa_control_proto::CONTROL_PROTOCOL_VERSION, client: "A".repeat(5000), }; let encoded = serde_json::to_vec(&bloated_hello).unwrap(); diff --git a/services/coa-control-e2e/tests/live_control.rs b/services/coa-control-e2e/tests/live_control.rs index 7a9a3d0..1edafd1 100644 --- a/services/coa-control-e2e/tests/live_control.rs +++ b/services/coa-control-e2e/tests/live_control.rs @@ -223,13 +223,13 @@ fn gate_phase12_1_live_vps_remote_transfer() { let collections = BTreeMap::from([("coa:appearance".to_string(), vec![101, 202])]); // 1. Remote transfer over Coordinator WSS channel - let outcome = pc.transfer_character(&mut ch, cid, 1, &payload, hash, collections.clone()).expect("transfer_character"); + let outcome = pc.transfer_character(&mut ch, cid, "coa", 1, &payload, hash, collections.clone()).expect("transfer_character"); assert!(outcome.local_guid > 0); assert_ne!(outcome.session_id, Uuid::nil()); println!("GATE 12.1 PASS remote transfer succeeded over WSS: local_guid={}, session_id={}", outcome.local_guid, outcome.session_id); // 2. Idempotent retry with same payload discovers existing commit - let retry_outcome = pc.transfer_character(&mut ch, cid, 1, &payload, hash, collections.clone()).expect("retry transfer"); + let retry_outcome = pc.transfer_character(&mut ch, cid, "coa", 1, &payload, hash, collections.clone()).expect("retry transfer"); assert_eq!(outcome.local_guid, retry_outcome.local_guid, "idempotent retry must return existing guid"); assert_eq!(outcome.session_id, retry_outcome.session_id, "idempotent retry must return existing session"); println!("GATE 12.1 PASS idempotent retry returned existing commit without duplication"); @@ -237,14 +237,14 @@ fn gate_phase12_1_live_vps_remote_transfer() { // 3. Update with newer revision 2 updates working copy without duplicating character let payload2 = b"REMOTE_PORTABLE_CHARACTER_VARIAN_PAYLOAD_V2".to_vec(); let hash2: [u8; 32] = Sha256::digest(&payload2).into(); - let update_outcome = pc.transfer_character(&mut ch, cid, 2, &payload2, hash2, collections).expect("update transfer"); + let update_outcome = pc.transfer_character(&mut ch, cid, "coa", 2, &payload2, hash2, collections).expect("update transfer"); assert_eq!(outcome.local_guid, update_outcome.local_guid, "revision update must preserve guid"); println!("GATE 12.1 PASS revision 2 update succeeded without character duplication"); // 4. Incompatible realm rejects before mutation let incomp_id = Uuid::now_v7(); fake.incompatible.lock().unwrap().insert(incomp_id); - let err = pc.transfer_character(&mut ch, incomp_id, 1, b"incomp", [0u8; 32], BTreeMap::new()).expect_err("should reject"); + let err = pc.transfer_character(&mut ch, incomp_id, "coa", 1, b"incomp", [0u8; 32], BTreeMap::new()).expect_err("should reject"); assert_eq!(err.code(), "incompatible"); println!("GATE 12.1 PASS incompatible character rejected cleanly"); diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index d217268..15eae79 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -1259,7 +1259,7 @@ async fn custom_races_install( }), ); })?; - let enabled = ctx.root.as_ref().map_or(true, |root| { + let enabled = ctx.root.as_ref().is_none_or(|root| { coa_core::modules::list(root) .iter() .any(|module| module.id == "custom-races" && module.enabled)