feat(multiruleset): complete MR1.1 foundation correctness gate

This commit is contained in:
Дмитрий committed 2026-10-22 15:34:37 +05:00
1 parent 58a99f0a6d
commit 9d135765cd
49 files changed
+2790 -700

No files matched your search

+28 -9
View File
@@ -261,7 +261,9 @@ pub fn config_files(root: &Path) -> Vec<String> {
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<Vec<Component>> {
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::<Result<_>>()?;
let mut databases: Vec<(String, &str)> = wanted_databases(kind)
.iter()
.map(|name| Ok((name.to_string(), realm.active.schema(name)?)))
.collect::<Result<_>>()?;
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<VerifyReport> {
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();
+48 -16
View File
@@ -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<Pointer> {
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<Source> {
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<Vec<u8>> {
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());
+61 -14
View File
@@ -417,11 +417,21 @@ pub fn launch(client: &Path) -> Result<u32> {
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<u32>
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<u16> = executable.as_os_str().encode_wide().chain(Some(0)).collect();
let file: Vec<u16> = executable
.as_os_str()
.encode_wide()
.chain(Some(0))
.collect();
let cwd: Vec<u16> = directory.as_os_str().encode_wide().chain(Some(0)).collect();
let verb: Vec<u16> = "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<u32>
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]
+10 -2
View File
@@ -61,8 +61,16 @@ pub fn lines_from_text(text: &str, filter: Option<&str>, max_lines: usize) -> Ve
let out: Vec<Line> = 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()
+23 -5
View File
@@ -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());
+2 -3
View File
@@ -206,10 +206,9 @@ fn patch_files(client: &Path) -> Result<Vec<PatchFile>> {
));
}
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)?;
+42 -17
View File
@@ -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<Vec<serde_json::Value>> {
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<Vec<serde_json::Value>> {
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::*;
+6 -1
View File
@@ -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"));
+20 -5
View File
@@ -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(),
+30 -6
View File
@@ -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<Vec<Line>> {
pub fn database_log_with(
d: &dyn Docker,
root: &Path,
filter: Option<&str>,
max_lines: usize,
) -> Result<Vec<Line>> {
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"));
}
}
+72 -14
View File
@@ -18,7 +18,10 @@ use crate::net::Exposure;
use crate::process::{ServiceState, ServiceStatus};
fn is_open(cfg: &Config) -> bool {
cfg.bind_address.parse::<IpAddr>().map(|ip| !ip.is_loopback()).unwrap_or(false)
cfg.bind_address
.parse::<IpAddr>()
.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<bool> {
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<bool> {
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<Exposure> {
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));
}
+30 -7
View File
@@ -36,7 +36,12 @@ fn key(path: &Path) -> Vec<String> {
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)]
+82 -25
View File
@@ -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::<HashSet<_>>().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::<HashSet<_>>().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;
+23 -3
View File
@@ -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::<Vec<_>>().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`),'')")));
}
+33 -8
View File
@@ -173,7 +173,9 @@ fn installed_module_commits(root: &Path) -> BTreeMap<String, String> {
fn list_in(cat: &[Entry], root: &Path) -> Vec<ModuleView> {
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::<f32>().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::<f32>().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(
+11 -2
View File
@@ -62,8 +62,17 @@ pub fn set_enabled(main: &Path, enabled: bool) -> Result<realms::View> {
));
}
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));
File diff suppressed because it is too large. Load diff
+3 -2
View File
@@ -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()
@@ -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,
@@ -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);
+22 -11
View File
@@ -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());
}
}
}
@@ -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<IdSet> {
.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) {
@@ -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!(
@@ -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")
@@ -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 &params.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);
}
}
}
@@ -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]
+14 -2
View File
@@ -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,
+23 -9
View File
@@ -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<CollectionAck> {
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<Vec<CollectionState>> {
pub fn collection_states(
&mut self,
ruleset: crate::portable::model::Ruleset,
) -> Result<Vec<CollectionState>> {
let profile = self.store.default_profile()?;
let mut out = Vec::new();
for kind in collection_kinds(ruleset) {
@@ -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,
+146 -21
View File
@@ -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<T: DeserializeOwned>(bytes: &[u8]) -> Result<T> {
.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<Self> {
pub fn new(
server_id: &str,
ruleset: super::super::model::Ruleset,
kind: &str,
set: &IdSet,
) -> Result<Self> {
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<Self> {
pub fn new(
ruleset: super::super::model::Ruleset,
kind: &str,
revision: u64,
set: &IdSet,
) -> Result<Self> {
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<SessionOffer, _> = 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<SessionOffer, _> = 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<SessionOffer, _> = 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);
}
}
+2
View File
@@ -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(())
}
+13 -3
View File
@@ -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"));
+181 -7
View File
@@ -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<u32> = (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"
);
}
+265 -58
View File
@@ -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<Mode> {
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<View> {
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<Files> {
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<Files> {
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<View> {
));
}
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<String> {
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<String> {
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::<Vec<_>>().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::<Vec<_>>()
.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"));
+67 -14
View File
@@ -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<String>) -> crate::Result<Vec<crate::schema_check::Problem>> {
pub(crate) fn database_problems(
root: &Path,
mode: crate::realms::Mode,
query: &impl Fn(&str) -> crate::Result<String>,
) -> crate::Result<Vec<crate::schema_check::Problem>> {
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() {
+10 -2
View File
@@ -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) {
+141 -59
View File
@@ -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<Vec<u8>>, sha256: Option<String> }
struct Saved {
bytes: Option<Vec<u8>>,
sha256: Option<String>,
}
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<serde_json::Value> = if root.join("Settings/realm-profile.json").exists() {
let mut realm: Option<serde_json::Value> = 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<u64> = ["mysqlPort", "authPort", "worldPort", "raPort"].iter()
.filter_map(|key| settings[*key].as_u64()).collect();
} else {
None
};
let mut excluded: std::collections::BTreeSet<u64> =
["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<u16> {
@@ -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<String, Saved> = 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<String, Saved> = 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(())
}
+75 -17
View File
@@ -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<Selection> {
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<u8>)>) -> Result<Selection> {
fn select_with(
meta: &InstallMeta,
source: Source,
fetch: &mut impl FnMut(&Source) -> Result<(Manifest, Vec<u8>)>,
) -> Result<Selection> {
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());
}
}
}