mirror of
https://github.com/Corfirean/coa-server-manager.git
synced 2026-11-23 11:25:56 +00:00
Preserve local historical work separately from the release candidate
This commit is contained in:
1 parent
654b7cddd3
commit
ab4bc9fd96
47 files changed
+1711
-204
No files matched your search
@@ -31,7 +31,7 @@ rand_core = { version = "0.6", features = ["getrandom"] }
|
||||
ed25519-dalek = { version = "2", features = ["rand_core"] }
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
windows-sys = { version = "0.60", features = ["Win32_Foundation", "Win32_System_Threading", "Win32_System_SystemInformation", "Win32_System_Diagnostics_ToolHelp", "Win32_NetworkManagement_IpHelper", "Win32_Networking_WinSock"] }
|
||||
windows-sys = { version = "0.60", features = ["Win32_Foundation", "Win32_Storage_FileSystem", "Win32_System_Threading", "Win32_System_SystemInformation", "Win32_System_Diagnostics_ToolHelp", "Win32_NetworkManagement_IpHelper", "Win32_Networking_WinSock"] }
|
||||
|
||||
[features]
|
||||
testkit = []
|
||||
@@ -29,7 +29,7 @@ fn main() {
|
||||
let dst = staging.join(db).join(format!("{id}.sql"));
|
||||
std::fs::create_dir_all(dst.parent().unwrap()).unwrap();
|
||||
std::fs::write(&dst, &bytes).unwrap();
|
||||
list.push(Migration { id, db: db.into(), sha256: fsx::sha256_bytes(&bytes), destructive: false });
|
||||
list.push(Migration { compatible_sha256: vec![], id, db: db.into(), sha256: fsx::sha256_bytes(&bytes), destructive: false });
|
||||
};
|
||||
for (kind, dirs) in [("auth", ["db_auth", "pending_db_auth"]), ("characters", ["db_characters", "pending_db_characters"]), ("world", ["db_world", "pending_db_world"])] {
|
||||
for d in dirs {
|
||||
|
||||
@@ -58,7 +58,7 @@ fn main() -> Result<()> {
|
||||
let path = staged.join(format!("{kind}/manager_realm_fixture.sql"));
|
||||
std::fs::create_dir_all(path.parent().unwrap())?;
|
||||
std::fs::write(&path, sql)?;
|
||||
manifest.migrations.push(Migration { id: "manager_realm_fixture".into(), db: kind.into(), sha256: coa_core::fsx::sha256_file(&path)?, destructive: false });
|
||||
manifest.migrations.push(Migration { compatible_sha256: vec![], id: "manager_realm_fixture".into(), db: kind.into(), sha256: coa_core::fsx::sha256_file(&path)?, destructive: false });
|
||||
}
|
||||
let result = env.migrate(&manifest, &staged)?;
|
||||
assert!(result.failed.is_none());
|
||||
|
||||
@@ -20,7 +20,7 @@ fn main() -> Result<()> {
|
||||
fsx::atomic_write(&update_tree.join(format!("_migrations/world/{id}.sql")), sql.as_bytes())?;
|
||||
let options = |kind, version: &str, migrations| BuildOptions { kind, version: version.into(), core_commit: None, built_at: "fixture".into(), part_size: 1 << 20, bots_commit: None, migrations };
|
||||
let base = package::build(&base_tree, &base_pkg, &options(Kind::Base, "1.0.0", vec![]), &|_| {})?;
|
||||
let update = package::build(&update_tree, &update_pkg, &options(Kind::Update, "1.0.1", vec![Migration { id: id.into(), db: "world".into(), sha256: fsx::sha256_bytes(sql.as_bytes()), destructive: false }]), &|_| {})?;
|
||||
let update = package::build(&update_tree, &update_pkg, &options(Kind::Update, "1.0.1", vec![Migration { compatible_sha256: vec![], id: id.into(), db: "world".into(), sha256: fsx::sha256_bytes(sql.as_bytes()), destructive: false }]), &|_| {})?;
|
||||
// A test-only trust key, unrelated to production signing material.
|
||||
let key = SigningKey::from_bytes(&[23; 32]);
|
||||
let public = STANDARD.encode(key.verifying_key().as_bytes());
|
||||
|
||||
@@ -33,7 +33,7 @@ fn main() {
|
||||
let sql = "CREATE TABLE IF NOT EXISTS coa_manager_update_test (id INT PRIMARY KEY); INSERT IGNORE INTO coa_manager_update_test VALUES (1);";
|
||||
put(&src, "_migrations/world/2026_09_30_00_update_e2e.sql", sql);
|
||||
let mut m = build(&src, &pkg, &BuildOptions { kind: Kind::Update, version: "0.2.0".into(), core_commit: None, built_at: chrono::Utc::now().to_rfc3339(), part_size: 1 << 20, bots_commit: None, migrations: vec![] }, &|_| {}).unwrap();
|
||||
m.migrations.push(Migration { id: "2026_09_30_00_update_e2e".into(), db: "world".into(), sha256: fsx::sha256_bytes(sql.as_bytes()), destructive: false });
|
||||
m.migrations.push(Migration { compatible_sha256: vec![], id: "2026_09_30_00_update_e2e".into(), db: "world".into(), sha256: fsx::sha256_bytes(sql.as_bytes()), destructive: false });
|
||||
std::fs::write(pkg.join("manifest.json"), serde_json::to_vec_pretty(&m).unwrap()).unwrap();
|
||||
let key = format!("{}/.coa-manager/signing/manifest-signing.key", std::env::var("USERPROFILE").unwrap());
|
||||
let seed: [u8; 32] = STANDARD.decode(std::fs::read_to_string(key).unwrap().trim()).unwrap().try_into().unwrap();
|
||||
|
||||
@@ -37,7 +37,7 @@ fn exercise(root: &Path) -> Result<()> {
|
||||
("world", "probe_world", "DROP TABLE manager_recovery_probe; THIS IS INTENTIONALLY INVALID SQL;"),
|
||||
] {
|
||||
fsx::atomic_write(&source.join(format!("_migrations/{db}/{id}.sql")), sql.as_bytes())?;
|
||||
migrations.push(Migration { db: db.into(), id: id.into(), sha256: fsx::sha256_bytes(sql.as_bytes()), destructive: false });
|
||||
migrations.push(Migration { compatible_sha256: vec![], db: db.into(), id: id.into(), sha256: fsx::sha256_bytes(sql.as_bytes()), destructive: false });
|
||||
}
|
||||
let pkg = root.join("fixture-package");
|
||||
let manifest = package::build(&source, &pkg, &BuildOptions {
|
||||
|
||||
@@ -22,7 +22,7 @@ fn main() -> Result<()> {
|
||||
let path = old_sql.join(format!("{name}.sql"));
|
||||
let hash = fsx::sha256_file(&path)?;
|
||||
db.put(&LedgerRow { db: "characters".into(), id: name.into(), sha256: hash.clone(), status: Status::Applied, error: None, baseline: false })?;
|
||||
migrations.push(Migration { db: "characters".into(), id: name.into(), sha256: hash, destructive: false });
|
||||
migrations.push(Migration { compatible_sha256: vec![], db: "characters".into(), id: name.into(), sha256: hash, destructive: false });
|
||||
}
|
||||
for (_, tables) in schema_check::WILDCARD_TABLES.iter().filter(|(kind,_)| *kind == "characters") {
|
||||
for table in *tables { db.query(&format!("DROP TABLE IF EXISTS acore_characters.`{table}`;"))?; }
|
||||
@@ -33,7 +33,7 @@ fn main() -> Result<()> {
|
||||
let files = release_schema::collect(empty_core.path(), None, Some(&repairs))?;
|
||||
assert_eq!(files.len(), 1);
|
||||
let repair = &files[0];
|
||||
migrations.push(Migration { db: repair.db.clone(), id: repair.id.clone(), sha256: repair.sha256.clone(), destructive: false });
|
||||
migrations.push(Migration { compatible_sha256: vec![], db: repair.db.clone(), id: repair.id.clone(), sha256: repair.sha256.clone(), destructive: false });
|
||||
let staged = tree.path().join("sql/characters");
|
||||
fsx::atomic_write(&staged.join(format!("{}.sql", repair.id)), &std::fs::read(&repair.abs)?)?;
|
||||
let report = migrations::apply_pending(&db, &migrations, &tree.path().join("sql"), &|| Ok("disposable fixture".into()))?;
|
||||
|
||||
@@ -51,6 +51,8 @@ pub struct Component {
|
||||
pub sha256: Option<String>,
|
||||
pub tables: Option<usize>,
|
||||
pub files: Option<Vec<String>>,
|
||||
#[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
|
||||
pub file_sha256: std::collections::BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
@@ -91,7 +93,10 @@ pub fn list(meta: &Path) -> Vec<RecoveryPoint> {
|
||||
}
|
||||
|
||||
pub fn get(meta: &Path, id: &str) -> Result<RecoveryPoint> {
|
||||
fsx::read_json(&point_dir(meta, id)?.join("backup.json")).map_err(|_| Error::Invalid(format!("backup {id} was not found")))
|
||||
let path = fsx::ensure_within(meta, &point_dir(meta, id)?.join("backup.json"))?;
|
||||
let point: RecoveryPoint = fsx::read_json(&path).map_err(|_| Error::Invalid(format!("backup {id} was not found or its metadata is damaged")))?;
|
||||
if point.id != id || point.schema != 1 { return Err(Error::Invalid(format!("Backup {id} has inconsistent identity or an unsupported schema."))); }
|
||||
Ok(point)
|
||||
}
|
||||
|
||||
/// Files that make up "configuration": everything a user or the Manager may have changed, minus secrets.
|
||||
@@ -132,6 +137,7 @@ pub fn config_files(root: &Path) -> Vec<String> {
|
||||
walk(root, &root.join("Settings/realm-profiles"), &mut out);
|
||||
if root.join("Settings/realm-profile.json").is_file() { out.push("Settings/realm-profile.json".into()); }
|
||||
out.sort();
|
||||
out.dedup();
|
||||
out
|
||||
}
|
||||
|
||||
@@ -139,13 +145,17 @@ fn copy_configs(root: &Path, dir: &Path) -> Result<Component> {
|
||||
let files = config_files(root);
|
||||
let target = dir.join("files");
|
||||
let mut bytes = 0;
|
||||
let mut file_sha256 = std::collections::BTreeMap::new();
|
||||
for rel in &files {
|
||||
let src = fsx::safe_join(root, rel)?;
|
||||
let dst = fsx::safe_join(&target, rel)?;
|
||||
fs::create_dir_all(dst.parent().unwrap())?;
|
||||
bytes += fs::copy(&src, &dst)?;
|
||||
let contents = fs::read(&src)?;
|
||||
fsx::atomic_write(&dst, &contents)?;
|
||||
bytes += contents.len() as u64;
|
||||
file_sha256.insert(rel.clone(), fsx::sha256_bytes(&contents));
|
||||
}
|
||||
Ok(Component { name: "configs".into(), path: "files".into(), bytes, sha256: None, tables: None, files: Some(files) })
|
||||
Ok(Component { name: "configs".into(), path: "files".into(), bytes, sha256: None, tables: None, files: Some(files), file_sha256 })
|
||||
}
|
||||
|
||||
/// Make sure the database is up for `f`. If we had to start it (and nothing else is running), stop it again.
|
||||
@@ -215,7 +225,7 @@ pub fn create(root: &Path, meta: &Path, kind: Kind, trigger: Trigger, label: Opt
|
||||
let tables = db.tables(schema)?.len();
|
||||
let file = format!("{name}.sql.zst");
|
||||
let (bytes, sha) = db.dump_to(schema, &partial.join(&file))?;
|
||||
Ok(Component { name, path: file, bytes, sha256: Some(sha), tables: Some(tables), files: None })
|
||||
Ok(Component { name, path: file, bytes, sha256: Some(sha), tables: Some(tables), files: None, file_sha256: Default::default() })
|
||||
})?;
|
||||
components.push(component);
|
||||
}
|
||||
@@ -245,7 +255,7 @@ pub fn create(root: &Path, meta: &Path, kind: Kind, trigger: Trigger, label: Opt
|
||||
components,
|
||||
};
|
||||
fsx::atomic_write_json(&partial.join("backup.json"), &point)?;
|
||||
fs::rename(&partial, &final_dir)?;
|
||||
fsx::durable_replace(&partial, &final_dir)?;
|
||||
tracing::info!(%id, ?kind, ?trigger, "recovery point created");
|
||||
if trigger == Trigger::Automatic {
|
||||
prune_automatic(meta, 10);
|
||||
@@ -255,6 +265,7 @@ pub fn create(root: &Path, meta: &Path, kind: Kind, trigger: Trigger, label: Opt
|
||||
|
||||
/// Keep the newest `keep` automatic recovery points; manual and safety ones are never pruned.
|
||||
pub fn prune_automatic(meta: &Path, keep: usize) {
|
||||
if crate::update::ensure_recovered(meta).is_err() { return; }
|
||||
let autos: Vec<_> = list(meta).into_iter().filter(|p| p.trigger == Trigger::Automatic).collect();
|
||||
for p in autos.into_iter().skip(keep) {
|
||||
if let Ok(dir) = point_dir(meta, &p.id) {
|
||||
@@ -274,7 +285,7 @@ pub fn verify(meta: &Path, id: &str) -> Result<VerifyReport> {
|
||||
let dir = point_dir(meta, id)?;
|
||||
let mut problems = Vec::new();
|
||||
for c in &point.components {
|
||||
let path = dir.join(&c.path);
|
||||
let path = fsx::ensure_within(&dir, &fsx::safe_join(&dir, &c.path)?)?;
|
||||
match (&c.sha256, &c.files) {
|
||||
(Some(sha), _) => match fsx::sha256_file(&path) {
|
||||
Ok(actual) if actual.eq_ignore_ascii_case(sha) => {}
|
||||
@@ -285,6 +296,8 @@ pub fn verify(meta: &Path, id: &str) -> Result<VerifyReport> {
|
||||
for f in files {
|
||||
if !fsx::safe_join(&path, f).map(|p| p.is_file()).unwrap_or(false) {
|
||||
problems.push(format!("configuration file {f} is missing"));
|
||||
} else if let Some(expected) = c.file_sha256.get(f) {
|
||||
if fsx::sha256_file(&fsx::safe_join(&path, f)?).ok().as_deref() != Some(expected.as_str()) { problems.push(format!("configuration file {f} is damaged")); }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -296,6 +309,9 @@ pub fn verify(meta: &Path, id: &str) -> Result<VerifyReport> {
|
||||
|
||||
/// Delete one recovery point (its own folder only).
|
||||
pub fn delete(meta: &Path, id: &str) -> Result<()> {
|
||||
// A damaged journal cannot reliably identify which copies recovery needs.
|
||||
// Preserve every available point until the installation is consistent.
|
||||
crate::update::ensure_recovered(meta)?;
|
||||
if crate::update::unfinished(meta).is_some_and(|t| t.recovery_point.as_deref() == Some(id)) {
|
||||
return Err(Error::Invalid("This recovery point is required by an unfinished update and cannot be deleted.".into()));
|
||||
}
|
||||
@@ -324,6 +340,20 @@ pub fn restore_configs(root: &Path, meta: &Path, id: &str) -> Result<RecoveryPoi
|
||||
Ok(safety)
|
||||
}
|
||||
|
||||
/// Transaction recovery has already protected the original state. Do not require a second backup.
|
||||
pub(crate) fn restore_update_configs(root: &Path, meta: &Path, id: &str) -> Result<()> {
|
||||
let point = get(meta, id)?;
|
||||
if !verify(meta, id)?.ok { return Err(Error::Invalid("The update recovery point is damaged.".into())); }
|
||||
let comp = point.components.iter().find(|c| c.name == "configs").ok_or_else(|| Error::Invalid("The update recovery point has no configuration.".into()))?;
|
||||
if comp.files.as_deref().unwrap_or_default().iter().any(|file| !comp.file_sha256.contains_key(file)) {
|
||||
return Err(Error::Invalid("This legacy recovery point has no configuration checksums. Automatic recovery cannot verify the original settings; copies were preserved for inspection.".into()));
|
||||
}
|
||||
for rel in comp.files.as_deref().unwrap_or_default() {
|
||||
fsx::atomic_write(&fsx::ensure_within(root, &fsx::safe_join(root, rel)?)?, &fs::read(fsx::safe_join(&point_dir(meta, id)?.join(&comp.path), rel)?)?)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct DbRestore {
|
||||
/// The database the restore replaced, kept intact under this name.
|
||||
@@ -335,6 +365,14 @@ pub struct DbRestore {
|
||||
/// Restore one database from a recovery point without dropping anything:
|
||||
/// import into a staging schema, sanity-check it, then swap tables atomically and keep the old schema.
|
||||
pub fn restore_database(root: &Path, meta: &Path, id: &str, name: &str) -> Result<DbRestore> {
|
||||
restore_database_inner(root, meta, id, name, true)
|
||||
}
|
||||
|
||||
pub(crate) fn restore_update_database(root: &Path, meta: &Path, id: &str, name: &str) -> Result<DbRestore> {
|
||||
restore_database_inner(root, meta, id, name, false)
|
||||
}
|
||||
|
||||
fn restore_database_inner(root: &Path, meta: &Path, id: &str, name: &str, safety_copy: bool) -> Result<DbRestore> {
|
||||
let point = get(meta, id)?;
|
||||
if point.realm != crate::realms::state(root)?.active {
|
||||
return Err(Error::Invalid("Select the realm this backup belongs to before restoring it.".into()));
|
||||
@@ -350,21 +388,48 @@ pub fn restore_database(root: &Path, meta: &Path, id: &str, name: &str) -> Resul
|
||||
let live = if name.contains('-') || name == "playerbots" { db::schema_of(name)? } else { point.realm.schema(name)? };
|
||||
let expected_tables = comp.tables.unwrap_or(0);
|
||||
let dump = point_dir(meta, id)?.join(&comp.path);
|
||||
let stamp = uuid::Uuid::new_v4().simple().to_string()[..16].to_string();
|
||||
let reconstructed_hash = point_dir(meta, id)?.join(format!("restore-{name}.sha256"));
|
||||
let stamp = if safety_copy { uuid::Uuid::new_v4().simple().to_string()[..16].to_string() }
|
||||
else { fsx::sha256_bytes(format!("update-recovery:{id}:{name}").as_bytes())[..16].to_string() };
|
||||
|
||||
// 1. Safety copy of the current state, so even a wrong restore is reversible.
|
||||
let safety = create(root, meta, Kind::Database, Trigger::BeforeRestore, Some(format!("before restoring {name} from {id}")), &|_| {})?;
|
||||
let safety = if safety_copy { Some(create(root, meta, Kind::Database, Trigger::BeforeRestore, Some(format!("before restoring {name} from {id}")), &|_| {})?.id) } else { None };
|
||||
|
||||
with_database(root, |db| {
|
||||
let db = db.clone().for_realm(crate::realms::Mode::Coa);
|
||||
let staging = format!("{live}_restore_{stamp}");
|
||||
let old = format!("{live}_before_restore_{stamp}");
|
||||
if db.schema_exists(&staging)? || db.schema_exists(&old)? {
|
||||
if safety_copy && (db.schema_exists(&staging)? || db.schema_exists(&old)?) {
|
||||
return Err(Error::Invalid("A previous restore left its work schemas behind; try again in a moment.".into()));
|
||||
}
|
||||
if !safety_copy {
|
||||
if db.schema_exists(&old)? {
|
||||
// RENAME TABLE is atomic. An empty staging schema proves that the old tables
|
||||
// were moved out and the complete restored set was moved into live together.
|
||||
if reconstructed_hash.is_file() && db.schema_exists(&staging)? && db.tables(&staging)?.is_empty() && db.tables(live)?.len() == expected_tables {
|
||||
db.query(&format!("DROP DATABASE `{old}`; DROP DATABASE `{staging}`;"))?;
|
||||
return Ok(DbRestore { previous_schema: old, safety_backup: String::new(), tables_restored: expected_tables });
|
||||
}
|
||||
// A server crash can interrupt a rename involving MyISAM tables.
|
||||
// The original dump was verified above and is authoritative: discard only
|
||||
// this recovery's deterministic work schemas and import a complete set again.
|
||||
db.query(&format!("DROP DATABASE `{old}`;"))?;
|
||||
}
|
||||
if db.schema_exists(&staging)? { db.query(&format!("DROP DATABASE `{staging}`;"))?; }
|
||||
}
|
||||
// 2. Import into staging.
|
||||
db.query(&format!("CREATE DATABASE `{staging}` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;"))?;
|
||||
db.import_from(&staging, &dump)?;
|
||||
if !safety_copy {
|
||||
// SHOW CREATE TABLE can make implicit character sets explicit on import.
|
||||
// Compare live against the independently reconstructed snapshot, keeping all
|
||||
// schema and row bytes rather than accepting a table-count approximation.
|
||||
let check = point_dir(meta, id)?.join(format!("restore-{name}.sql.zst"));
|
||||
let (_, hash) = db.dump_to(&staging, &check)?;
|
||||
fsx::atomic_write(&reconstructed_hash, hash.as_bytes())?;
|
||||
fs::remove_file(check)?;
|
||||
}
|
||||
crate::update_fault::checkpoint(root, &format!("restore-database:{name}:imported"));
|
||||
// 3. Sanity checks.
|
||||
let staged = db.tables(&staging)?;
|
||||
if comp.tables.is_some_and(|expected| staged.len() != expected) || (comp.tables.is_none() && staged.is_empty()) {
|
||||
@@ -384,7 +449,11 @@ pub fn restore_database(root: &Path, meta: &Path, id: &str, name: &str) -> Resul
|
||||
renames.push(format!("`{staging}`.`{t}` TO `{live}`.`{t}`"));
|
||||
}
|
||||
if !renames.is_empty() { db.query(&format!("RENAME TABLE {};", renames.join(", ")))?; }
|
||||
Ok(DbRestore { previous_schema: old, safety_backup: safety.id.clone(), tables_restored: staged.len() })
|
||||
crate::update_fault::checkpoint(root, &format!("restore-database:{name}:swapped"));
|
||||
// For emergency recovery, completed temporary schemas are disposable. A crash before
|
||||
// cleanup leaves the original dump intact, and another recovery can repeat the swap.
|
||||
if !safety_copy { db.query(&format!("DROP DATABASE `{old}`; DROP DATABASE `{staging}`;"))?; }
|
||||
Ok(DbRestore { previous_schema: old, safety_backup: safety.clone().unwrap_or_default(), tables_restored: staged.len() })
|
||||
})
|
||||
}
|
||||
|
||||
@@ -405,6 +474,18 @@ mod tests {
|
||||
(dir, root, meta)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn corrupt_update_journal_preserves_available_backups() {
|
||||
let (_d, root, meta) = setup();
|
||||
let point = create(&root, &meta, Kind::Config, Trigger::Automatic, None, &|_| {}).unwrap();
|
||||
let updates = meta.join("updates").join("interrupted");
|
||||
fs::create_dir_all(&updates).unwrap();
|
||||
fs::write(updates.join("txn.json"), b"{damaged").unwrap();
|
||||
assert!(delete(&meta, &point.id).is_err());
|
||||
prune_automatic(&meta, 0);
|
||||
assert!(get(&meta, &point.id).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn config_backup_excludes_secrets_and_clutter_and_restores_byte_exact() {
|
||||
let (_d, root, meta) = setup();
|
||||
|
||||
@@ -181,7 +181,7 @@ pub fn build(p: &Params, say: &dyn Fn(&str)) -> Result<()> {
|
||||
if let Some(b) = p.bots {
|
||||
sql.extend(collect_bots_sql(b)?);
|
||||
}
|
||||
let migrations: Vec<_> = sql.iter().map(|f| crate::manifest::Migration { id: f.id.clone(), db: f.db.clone(), sha256: f.sha256.clone(), destructive: false }).collect();
|
||||
let migrations: Vec<_> = sql.iter().map(|f| crate::manifest::Migration { compatible_sha256: vec![], id: f.id.clone(), db: f.db.clone(), sha256: f.sha256.clone(), destructive: false }).collect();
|
||||
let staging = std::env::temp_dir().join("coa-cleanbase-sql");
|
||||
let _ = fs::remove_dir_all(&staging);
|
||||
for f in &sql {
|
||||
|
||||
@@ -89,6 +89,9 @@ pub(crate) fn credentials(root: &Path) -> Result<(String, String)> {
|
||||
}
|
||||
|
||||
impl Db {
|
||||
pub(crate) fn native_root(&self) -> Option<PathBuf> {
|
||||
if self.container.is_some() { None } else { self.bin.parent().and_then(|p| p.parent()).map(Path::to_path_buf) }
|
||||
}
|
||||
pub fn from_repack(root: &Path, account: Account) -> Result<Db> {
|
||||
let creds: Credentials = fsx::read_json(&root.join("Settings/database.json"))
|
||||
.map_err(|_| Error::Invalid("The database settings of this server could not be read.".into()))?;
|
||||
@@ -265,7 +268,7 @@ impl Db {
|
||||
let file = File::create(out)?;
|
||||
let mut enc = zstd::Encoder::new(BufWriter::new(file), 3)?;
|
||||
let copy = std::io::copy(&mut stdout, &mut enc);
|
||||
let finish = enc.finish().and_then(|mut w| w.flush());
|
||||
let finish = enc.finish().and_then(|mut w| { w.flush()?; w.get_ref().sync_all() });
|
||||
let status = child.wait()?;
|
||||
let stderr_bytes = err_thread.join().unwrap_or_default();
|
||||
if !status.success() {
|
||||
@@ -280,6 +283,8 @@ impl Db {
|
||||
|
||||
/// Run a plain SQL file against `schema`; the first error aborts and is returned.
|
||||
pub fn run_sql_file(&self, schema: &str, file: &Path) -> Result<()> {
|
||||
let injected = if let Some(root) = self.native_root() { crate::update_fault::failing_sql(&root, file)? } else { None };
|
||||
let file = injected.as_ref().map(|f| f.path()).unwrap_or(file);
|
||||
let schema = self.realm_schema(schema);
|
||||
if !ident_ok(schema) {
|
||||
return Err(Error::Invalid("bad schema name".into()));
|
||||
|
||||
@@ -249,6 +249,14 @@ pub fn export_package(root: &Path, meta_dir: &Path, manager_log: &Path, meta: &I
|
||||
if let Ok(b) = fs::read(meta_dir.join("logs/database-checks.json")) {
|
||||
add("database-checks.json", redact(&String::from_utf8_lossy(&b)).as_bytes())?;
|
||||
}
|
||||
if let Ok(b) = fs::read(meta_dir.join("logs/update-result.json")) {
|
||||
add("update-result.json", redact(&String::from_utf8_lossy(&b)).as_bytes())?;
|
||||
}
|
||||
if let Ok(Some(txn)) = crate::update::latest(meta_dir) {
|
||||
if let Ok(b) = fs::read(meta_dir.join("updates").join(&txn.id).join("diagnostic.json")) {
|
||||
add("update-diagnostic.json", redact(&String::from_utf8_lossy(&b)).as_bytes())?;
|
||||
}
|
||||
}
|
||||
zip.finish().map_err(|e| Error::Invalid(e.to_string()))?;
|
||||
Ok(n)
|
||||
}
|
||||
|
||||
@@ -81,20 +81,41 @@ fn launcher(root: &Path) -> Result<(PathBuf, PathBuf)> {
|
||||
|
||||
/// Run a launcher verb to completion (blocking; call from a worker thread).
|
||||
pub fn run(root: &Path, verb: Verb) -> Result<DriverOutcome> {
|
||||
run_inner(root, verb, false)
|
||||
run_inner(root, verb, false, false)
|
||||
}
|
||||
|
||||
pub(crate) fn validate_update(root: &Path) -> Result<DriverOutcome> {
|
||||
run_inner(root, Verb::StartAll, true)
|
||||
run_inner(root, Verb::StartAll, true, true)
|
||||
}
|
||||
|
||||
fn run_inner(root: &Path, verb: Verb, validating_update: bool) -> Result<DriverOutcome> {
|
||||
pub(crate) fn start_after_update(root: &Path) -> Result<DriverOutcome> {
|
||||
run_inner(root, Verb::StartAll, true, false)
|
||||
}
|
||||
|
||||
pub(crate) fn validate_secondary(root: &Path) -> Result<DriverOutcome> {
|
||||
run_inner(root, Verb::StartWorld, true, true)
|
||||
}
|
||||
|
||||
/// Validate without accepting game connections or submitting reports. Child supervisors inherit the flag.
|
||||
pub(crate) fn offline_launcher(text: &str) -> Result<String> {
|
||||
let normalized = text.replace("\r\n", "\n");
|
||||
let text = normalized.as_str();
|
||||
if text.contains("# coa-offline-validation") { return Ok(text.into()); }
|
||||
if !text.contains("def spawn(name, command, cwd, log):") || !text.contains("def relay_worker():") {
|
||||
return Err(Error::Invalid("This launcher cannot isolate an update validation. Update was not applied.".into()));
|
||||
}
|
||||
let spawn = "def spawn(name, command, cwd, log):\n # coa-offline-validation\n if os.environ.get('COA_UPDATE_VALIDATION') == '1':\n for filename in ('worldserver.conf', 'authserver.conf'):\n path = ROOT / 'Core/configs' / filename\n if path.exists():\n text = path.read_text(encoding='utf-8-sig')\n for key, value in (('BindIP', '\"127.0.0.1\"'), ('Ra.IP', '\"127.0.0.1\"'), ('SOAP.Enabled', '0')):\n text = re.sub(r'(?m)^\\s*' + re.escape(key) + r'\\s*=.*$', '', text)\n text += '\\n' + key + ' = ' + value + '\\n'\n path.write_text(text, encoding='utf-8')\n";
|
||||
let relay = "def relay_worker():\n if os.environ.get('COA_UPDATE_VALIDATION') == '1':\n save_process('relay-ready', os.getpid())\n while not (STATE / 'stop-relay').exists():\n time.sleep(0.5)\n return\n";
|
||||
Ok(text.replacen("def spawn(name, command, cwd, log):\n", spawn, 1).replacen("def relay_worker():\n", relay, 1))
|
||||
}
|
||||
|
||||
fn run_inner(root: &Path, verb: Verb, validating_update: bool, offline: bool) -> Result<DriverOutcome> {
|
||||
let root = fsx::canonicalize_lenient(root)?;
|
||||
let _update_lock = if !validating_update && matches!(verb, Verb::StartAll | Verb::StartWorld) {
|
||||
Some(crate::update::operation_lock(&crate::registry::metadata_dir_for(&root)?)?)
|
||||
} else { None };
|
||||
if !validating_update && matches!(verb, Verb::StartAll | Verb::StartWorld) {
|
||||
crate::update::ensure_recovered(&crate::registry::metadata_dir_for(&root)?)?;
|
||||
crate::update::recover_before_start(&root, &crate::registry::metadata_dir_for(&root)?)?;
|
||||
}
|
||||
if matches!(verb, Verb::StartAll | Verb::StartWorld) { crate::modules::ensure_bot_exclusivity(&root)?; }
|
||||
if crate::docker::is_docker(&root) {
|
||||
@@ -115,7 +136,8 @@ fn run_inner(root: &Path, verb: Verb, validating_update: bool) -> Result<DriverO
|
||||
if matches!(verb, Verb::StartAll | Verb::StartWorld) { crate::modules::ensure_bot_exclusivity(&root)?; }
|
||||
let (python, script) = launcher(&root)?;
|
||||
let original = std::fs::read_to_string(&script)?;
|
||||
let patched = patch_launcher_imports(&original)?;
|
||||
let imported = patch_launcher_imports(&original)?;
|
||||
let patched = if offline { offline_launcher(&imported)? } else { imported };
|
||||
if original != patched {
|
||||
fsx::atomic_write(&script, patched.as_bytes())?;
|
||||
if let Ok(dir) = crate::registry::metadata_dir_for(&root) {
|
||||
@@ -128,8 +150,10 @@ fn run_inner(root: &Path, verb: Verb, validating_update: bool) -> Result<DriverO
|
||||
}
|
||||
}
|
||||
let mut cmd = Command::new(&python);
|
||||
cmd.arg("-B").arg("-c").arg(LAUNCH_SCRIPT).arg(&script).arg(verb.arg())
|
||||
let launch = if offline && crate::update_fault::python_failure(&root) { "raise RuntimeError('Injected disposable-fixture Python failure')" } else { LAUNCH_SCRIPT };
|
||||
cmd.arg("-B").arg("-c").arg(launch).arg(&script).arg(verb.arg())
|
||||
.current_dir(&root).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped());
|
||||
if offline { cmd.env("COA_UPDATE_VALIDATION", "1"); }
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::os::windows::process::CommandExt;
|
||||
@@ -179,7 +203,10 @@ fn run_inner(root: &Path, verb: Verb, validating_update: bool) -> Result<DriverO
|
||||
}
|
||||
};
|
||||
tracing::info!(?verb, ok, ?code, "driver: launcher verb finished");
|
||||
if ok && verb == Verb::StartAll { crate::multiworld::start(&root)?; }
|
||||
if ok && verb == Verb::StartAll {
|
||||
if offline { crate::multiworld::start_validation(&root)?; }
|
||||
else { crate::multiworld::start(&root)?; }
|
||||
}
|
||||
Ok(DriverOutcome { ok, exit_code, code, human: code.map(ErrorCode::human), output })
|
||||
}
|
||||
|
||||
@@ -198,6 +225,7 @@ pub(crate) fn patch_launcher_imports(text: &str) -> Result<String> {
|
||||
pub(crate) fn launcher_matches(signed: &str, actual: &[u8]) -> bool {
|
||||
if signed.as_bytes() == actual { return true; }
|
||||
if patch_launcher_imports(signed).is_ok_and(|s| s.as_bytes() == actual) { return true; }
|
||||
if patch_launcher_imports(signed).and_then(|s| offline_launcher(&s)).is_ok_and(|s| s.as_bytes() == actual) { return true; }
|
||||
crate::realms::patch_launcher(signed).is_ok_and(|s| s.as_bytes() == actual
|
||||
|| patch_launcher_imports(&s).is_ok_and(|p| p.as_bytes() == actual))
|
||||
}
|
||||
|
||||
@@ -123,7 +123,7 @@ pub fn atomic_write(path: &Path, bytes: &[u8]) -> Result<()> {
|
||||
let tmp = parent.join(format!(
|
||||
".{}.{}.tmp",
|
||||
path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(),
|
||||
std::process::id()
|
||||
uuid::Uuid::new_v4().simple()
|
||||
));
|
||||
let write = || -> std::io::Result<()> {
|
||||
let mut f = OpenOptions::new().write(true).create_new(true).open(&tmp)?;
|
||||
@@ -135,13 +135,41 @@ pub fn atomic_write(path: &Path, bytes: &[u8]) -> Result<()> {
|
||||
let _ = fs::remove_file(&tmp);
|
||||
return Err(e.into());
|
||||
}
|
||||
if let Err(e) = fs::rename(&tmp, path) {
|
||||
if let Err(e) = durable_replace(&tmp, path) {
|
||||
let _ = fs::remove_file(&tmp);
|
||||
return Err(e.into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The temporary file must already be flushed, on the same volume as the destination.
|
||||
pub(crate) fn durable_replace(from: &Path, to: &Path) -> std::io::Result<()> {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::os::windows::ffi::OsStrExt;
|
||||
use windows_sys::Win32::Storage::FileSystem::{MoveFileExW, MOVEFILE_REPLACE_EXISTING, MOVEFILE_WRITE_THROUGH};
|
||||
fn wide(path: &Path) -> std::io::Result<Vec<u16>> {
|
||||
let absolute = std::path::absolute(path)?;
|
||||
let text = absolute.as_os_str().to_string_lossy().replace('/', "\\");
|
||||
let extended = if text.starts_with("\\\\?\\") { text }
|
||||
else if let Some(unc) = text.strip_prefix("\\\\") { format!("\\\\?\\UNC\\{unc}") }
|
||||
else { format!("\\\\?\\{text}") };
|
||||
Ok(std::ffi::OsStr::new(&extended).encode_wide().chain(Some(0)).collect())
|
||||
}
|
||||
let src = wide(from)?;
|
||||
let dst = wide(to)?;
|
||||
if unsafe { MoveFileExW(src.as_ptr(), dst.as_ptr(), MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH) } == 0 {
|
||||
return Err(std::io::Error::last_os_error());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
fs::rename(from, to)?;
|
||||
File::open(to.parent().unwrap())?.sync_all()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn atomic_write_json<T: serde::Serialize>(path: &Path, value: &T) -> Result<()> {
|
||||
let mut bytes = serde_json::to_vec_pretty(value)?;
|
||||
bytes.push(b'\n');
|
||||
@@ -199,6 +227,16 @@ pub fn require_space(path: &Path, needed: u64) -> Result<()> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn durable_replacement_handles_long_transaction_backup_paths() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let parent = dir.path().join("a".repeat(90)).join("b".repeat(90));
|
||||
let path = parent.join("configuration-with-a-long-name.template");
|
||||
atomic_write(&path, b"old").unwrap();
|
||||
atomic_write(&path, b"new").unwrap();
|
||||
assert_eq!(fs::read(&path).unwrap(), b"new");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn safe_join_accepts_normal_and_rejects_traversal() {
|
||||
let root = Path::new("C:/srv");
|
||||
|
||||
@@ -148,10 +148,6 @@ pub(crate) fn bootstrap_database(root: &Path) -> Result<()> {
|
||||
with_scratch_ports(root, || bootstrap_database_inner(root))
|
||||
}
|
||||
|
||||
fn free_port() -> Result<u16> {
|
||||
Ok(std::net::TcpListener::bind("127.0.0.1:0")?.local_addr()?.port())
|
||||
}
|
||||
|
||||
/// Run `f` with the staging copy listening on unused ports, so an installation never collides with a server (or any
|
||||
/// other program) already using the shipped ports. The shipped ports are put back afterwards.
|
||||
pub(crate) fn with_scratch_ports<T>(root: &Path, f: impl FnOnce() -> Result<T>) -> Result<T> {
|
||||
@@ -159,10 +155,14 @@ pub(crate) fn with_scratch_ports<T>(root: &Path, f: impl FnOnce() -> Result<T>)
|
||||
let path = root.join("Settings/repack.json");
|
||||
let original: serde_json::Value = fsx::read_json(&path)?;
|
||||
let mut scratch = original.clone();
|
||||
let mut listeners = Vec::new();
|
||||
for k in KEYS {
|
||||
scratch[k] = free_port()?.into();
|
||||
let listener = std::net::TcpListener::bind("127.0.0.1:0")?;
|
||||
scratch[k] = listener.local_addr()?.port().into();
|
||||
listeners.push(listener);
|
||||
}
|
||||
fsx::atomic_write_json(&path, &scratch)?;
|
||||
drop(listeners);
|
||||
let result = f();
|
||||
// keep whatever else changed meanwhile (console credentials), restore only the ports
|
||||
let mut now: serde_json::Value = fsx::read_json(&path).unwrap_or(scratch);
|
||||
|
||||
@@ -25,6 +25,7 @@ pub mod population;
|
||||
pub mod process;
|
||||
pub mod manifest;
|
||||
pub mod migrations;
|
||||
pub mod migration_registry;
|
||||
pub mod multiworld;
|
||||
pub mod repair;
|
||||
pub mod schema_check;
|
||||
@@ -39,6 +40,8 @@ pub mod registry;
|
||||
pub mod release;
|
||||
pub mod release_schema;
|
||||
pub mod update;
|
||||
mod update_trial;
|
||||
mod update_fault;
|
||||
pub mod upnp;
|
||||
pub mod signing;
|
||||
pub mod srp6;
|
||||
|
||||
@@ -48,6 +48,8 @@ pub struct FileEntry {
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct Migration {
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub compatible_sha256: Vec<String>,
|
||||
pub id: String,
|
||||
pub db: String,
|
||||
pub sha256: String,
|
||||
@@ -134,6 +136,11 @@ impl Manifest {
|
||||
if parse_version(&self.min_manager_version).is_none() {
|
||||
return bad(format!("bad minManagerVersion {:?}", self.min_manager_version));
|
||||
}
|
||||
for migration in &self.migrations {
|
||||
if !is_sha256(&migration.sha256) || migration.compatible_sha256.iter().any(|h| !is_sha256(h) || h == &"0".repeat(64)) {
|
||||
return bad(format!("{}: invalid migration checksum compatibility", migration.id));
|
||||
}
|
||||
}
|
||||
for (label, rev) in [("core", Some(&self.core)), ("bots", self.bots.as_ref())] {
|
||||
if let Some(Revision { commit: Some(c) }) = rev {
|
||||
if !is_commit(c) {
|
||||
|
||||
@@ -37,6 +37,7 @@ pub trait Store {
|
||||
fn load(&self) -> Result<Vec<LedgerRow>>;
|
||||
fn put(&self, row: &LedgerRow) -> Result<()>;
|
||||
fn run_file(&self, schema: &str, file: &Path) -> Result<()>;
|
||||
fn checkpoint(&self, _point: &str) {}
|
||||
}
|
||||
|
||||
fn hex_of(s: &str) -> String {
|
||||
@@ -48,6 +49,9 @@ fn ident_ok(s: &str) -> bool {
|
||||
}
|
||||
|
||||
impl Store for Db {
|
||||
fn checkpoint(&self, point: &str) {
|
||||
if let Some(root) = self.native_root() { crate::update_fault::checkpoint(&root, point); }
|
||||
}
|
||||
fn load(&self) -> Result<Vec<LedgerRow>> {
|
||||
self.query(&format!(
|
||||
"CREATE TABLE IF NOT EXISTS `{LEDGER_SCHEMA}`.`{LEDGER_TABLE}` (`db` VARCHAR(32) NOT NULL, `id` VARCHAR(190) NOT NULL, `sha256` CHAR(64) NOT NULL, `status` VARCHAR(16) NOT NULL, `applied_at` DATETIME NOT NULL, `error` TEXT NULL, `baseline` TINYINT NOT NULL DEFAULT 0, PRIMARY KEY (`db`,`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;"
|
||||
@@ -148,7 +152,7 @@ fn recorded<'a>(rows: &'a [LedgerRow], m: &Migration) -> Option<&'a LedgerRow> {
|
||||
}
|
||||
|
||||
fn hash_changed(row: &LedgerRow, m: &Migration) -> bool {
|
||||
row.status == Status::Applied && row.sha256 != "0".repeat(64) && !row.sha256.eq_ignore_ascii_case(&m.sha256)
|
||||
row.status == Status::Applied && row.sha256 != "0".repeat(64) && !row.sha256.eq_ignore_ascii_case(&m.sha256) && !m.compatible_sha256.iter().any(|h| h.eq_ignore_ascii_case(&row.sha256))
|
||||
}
|
||||
|
||||
/// Record migrations as already present without running them (adopting an existing server whose database
|
||||
@@ -217,10 +221,13 @@ pub fn apply_pending(store: &dyn Store, list: &[Migration], dir: &Path, snapshot
|
||||
for (m, schema, path) in files {
|
||||
tracing::info!(migration = %m.id, database = %m.db, "database migration starting");
|
||||
store.put(&LedgerRow { db: m.db.clone(), id: m.id.clone(), sha256: m.sha256.clone(), status: Status::Running, error: Some("Interrupted SQL must be recovered before replay.".into()), baseline: false })?;
|
||||
store.checkpoint(&format!("before-sql:{}", m.id));
|
||||
match store.run_file(schema, &path) {
|
||||
Ok(()) => {
|
||||
store.checkpoint(&format!("after-sql:{}", m.id));
|
||||
store.put(&LedgerRow { db: m.db.clone(), id: m.id.clone(), sha256: m.sha256.clone(), status: Status::Applied, error: None, baseline: false })?;
|
||||
report.applied.push(m.id.clone());
|
||||
store.checkpoint(&format!("recorded-sql:{}", m.id));
|
||||
tracing::info!(migration = %m.id, database = %m.db, "database migration applied");
|
||||
}
|
||||
Err(e) => {
|
||||
@@ -273,7 +280,7 @@ mod tests {
|
||||
for (db, id, sql) in files {
|
||||
std::fs::create_dir_all(d.path().join(db)).unwrap();
|
||||
std::fs::write(d.path().join(db).join(format!("{id}.sql")), sql).unwrap();
|
||||
list.push(Migration { id: id.to_string(), db: db.to_string(), sha256: fsx::sha256_bytes(sql.as_bytes()), destructive: false });
|
||||
list.push(Migration { compatible_sha256: vec![], id: id.to_string(), db: db.to_string(), sha256: fsx::sha256_bytes(sql.as_bytes()), destructive: false });
|
||||
}
|
||||
(d, list)
|
||||
}
|
||||
@@ -304,6 +311,19 @@ mod tests {
|
||||
assert!(store.ran.borrow().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_explicit_published_compatibility_skips_changed_hash_without_rewriting_history() {
|
||||
let (d, mut list) = setup(&[("characters", "repair", "SELECT 1;\n")]);
|
||||
let store = Mem::default();
|
||||
let previous = fsx::sha256_bytes(b"SELECT 1;\r\n");
|
||||
store.rows.borrow_mut().push(LedgerRow { db: "characters".into(), id: "repair".into(), sha256: previous.clone(), status: Status::Applied, error: None, baseline: false });
|
||||
assert!(apply_pending(&store, &list, d.path(), &no_snapshot).is_err());
|
||||
list[0].compatible_sha256.push(previous.clone());
|
||||
assert!(apply_pending(&store, &list, d.path(), &no_snapshot).unwrap().applied.is_empty());
|
||||
assert!(store.ran.borrow().is_empty());
|
||||
assert_eq!(store.rows.borrow()[0].sha256, previous);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn applies_in_order_once_and_records_the_ledger() {
|
||||
let (d, list) = setup(&[("world", "2026_09_01_00_a", "CREATE TABLE t (id INT);"), ("world", "2026_09_02_00_b", "ALTER TABLE t ADD c INT;")]);
|
||||
|
||||
@@ -125,6 +125,14 @@ fn secondary_launcher(source: &str) -> Result<String> {
|
||||
}
|
||||
|
||||
pub fn start(main: &Path) -> Result<()> {
|
||||
start_inner(main, false)
|
||||
}
|
||||
|
||||
pub(crate) fn start_validation(main: &Path) -> Result<()> {
|
||||
start_inner(main, true)
|
||||
}
|
||||
|
||||
fn start_inner(main: &Path, offline: bool) -> Result<()> {
|
||||
if !realms::state(main)?.simultaneous { return Ok(()); }
|
||||
if is_running(main) {
|
||||
let second = root(main);
|
||||
@@ -132,7 +140,7 @@ pub fn start(main: &Path) -> Result<()> {
|
||||
return Err(Error::Invalid("The second realm is still starting or stopping.".into()));
|
||||
}
|
||||
let second = prepare(main)?;
|
||||
let out = driver::run(&second, Verb::StartWorld)?;
|
||||
let out = if offline { driver::validate_secondary(&second)? } else { driver::run(&second, Verb::StartWorld)? };
|
||||
if !out.ok { return Err(Error::Invalid(format!("The second realm did not start: {}", out.output))); }
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -4,6 +4,8 @@
|
||||
use std::fs;
|
||||
use std::io::Read;
|
||||
use std::path::{Path, PathBuf};
|
||||
use base64::{engine::general_purpose::STANDARD, Engine};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::download::{self, Cancel, Job, Progress};
|
||||
use crate::error::{Error, Result};
|
||||
@@ -20,6 +22,77 @@ pub enum Source {
|
||||
Dir(PathBuf),
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct Channel {
|
||||
pub schema: u32,
|
||||
pub version: String,
|
||||
pub release: String,
|
||||
pub manifest_sha256: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub acceptance_sha256: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
pub struct SignedChannel {
|
||||
pub payload: String,
|
||||
pub signature: String,
|
||||
}
|
||||
|
||||
pub fn verify_channel(bytes: &[u8], trusted_key: &str) -> Result<Channel> {
|
||||
let signed: SignedChannel = serde_json::from_slice(bytes).map_err(|e| Error::InvalidManifest(e.to_string()))?;
|
||||
let payload = STANDARD.decode(&signed.payload).map_err(|e| Error::InvalidManifest(e.to_string()))?;
|
||||
signing::verify(&payload, &signed.signature, trusted_key)?;
|
||||
let pointer: Channel = serde_json::from_slice(&payload).map_err(|e| Error::InvalidManifest(e.to_string()))?;
|
||||
let required = format!("https://github.com/Corfirean/coa-server-build/releases/download/server-{}/", pointer.version);
|
||||
if pointer.schema != 1 || crate::manifest::parse_version(&pointer.version).is_none() || pointer.release != required {
|
||||
return Err(Error::InvalidManifest("Channel does not point to an immutable server release.".into()));
|
||||
}
|
||||
Ok(pointer)
|
||||
}
|
||||
|
||||
/// A channel is one atomically replaced signed envelope. Its target is immutable.
|
||||
pub struct PinnedPackage {
|
||||
pub source: Source,
|
||||
pub manifest: Manifest,
|
||||
pub bytes: Vec<u8>,
|
||||
pub signature: Vec<u8>,
|
||||
}
|
||||
|
||||
pub fn fetch_package(source: &Source, trusted_key: &str) -> Result<PinnedPackage> {
|
||||
let channel = match source {
|
||||
Source::Dir(d) if !d.join("channel.json").exists() => None,
|
||||
_ => match fetch_small(source, "channel.json") {
|
||||
Ok(bytes) => Some(bytes),
|
||||
Err(Error::PackageNotPublished(_)) => None,
|
||||
Err(e) => return Err(e),
|
||||
},
|
||||
};
|
||||
let (mut resolved, expected) = if let Some(bytes) = channel {
|
||||
let pointer = verify_channel(&bytes, trusted_key)?;
|
||||
(Source::Url(pointer.release.clone()), Some(pointer))
|
||||
} else { (source.clone(), None) };
|
||||
let mut bytes = fetch_small(&resolved, "manifest.json")?;
|
||||
let mut signature = fetch_small(&resolved, "manifest.json.sig")?;
|
||||
signing::verify(&bytes, &String::from_utf8_lossy(&signature), trusted_key)?;
|
||||
let manifest = Manifest::parse(&bytes)?;
|
||||
// Legacy moving channels are pinned by matching their signed manifest to the immutable tag.
|
||||
if matches!(&resolved, Source::Url(url) if matches!(url.trim_end_matches('/'), "https://github.com/Corfirean/coa-server-build/releases/download/stable" | "https://github.com/Corfirean/coa-server-build/releases/download/edge")) {
|
||||
resolved = Source::Url(format!("https://github.com/Corfirean/coa-server-build/releases/download/server-{}/", manifest.version));
|
||||
let immutable = fetch_small(&resolved, "manifest.json")?;
|
||||
let sig = fetch_small(&resolved, "manifest.json.sig")?;
|
||||
signing::verify(&immutable, &String::from_utf8_lossy(&sig), trusted_key)?;
|
||||
if immutable != bytes { return Err(Error::InvalidManifest("Moving channel differs from its immutable release.".into())); }
|
||||
bytes = immutable;
|
||||
signature = sig;
|
||||
}
|
||||
if let Some(pointer) = expected {
|
||||
if pointer.version != manifest.version || pointer.manifest_sha256 != fsx::sha256_bytes(&bytes) {
|
||||
return Err(Error::InvalidManifest("Immutable release does not match the signed channel.".into()));
|
||||
}
|
||||
}
|
||||
Ok(PinnedPackage { source: resolved, manifest, bytes, signature })
|
||||
}
|
||||
|
||||
/// Read a small file (manifest, signature) from the source.
|
||||
pub fn fetch_small(source: &Source, name: &str) -> Result<Vec<u8>> {
|
||||
match source {
|
||||
@@ -44,11 +117,8 @@ pub fn fetch_small(source: &Source, name: &str) -> Result<Vec<u8>> {
|
||||
|
||||
/// Download and verify the manifest. Returns the parsed manifest and its exact bytes.
|
||||
pub fn fetch_manifest(source: &Source, trusted_key: &str) -> Result<(Manifest, Vec<u8>)> {
|
||||
let bytes = fetch_small(source, "manifest.json")?;
|
||||
let sig = String::from_utf8_lossy(&fetch_small(source, "manifest.json.sig")?).into_owned();
|
||||
signing::verify(&bytes, &sig, trusted_key)?;
|
||||
let manifest = Manifest::parse(&bytes)?;
|
||||
Ok((manifest, bytes))
|
||||
let pinned = fetch_package(source, trusted_key)?;
|
||||
Ok((pinned.manifest, pinned.bytes))
|
||||
}
|
||||
|
||||
/// Make every archive part available in a verified folder: a local source is used in place, a remote one is
|
||||
|
||||
@@ -13,6 +13,7 @@ use crate::package::{self, BuildOptions};
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct SqlFile {
|
||||
pub compatible_sha256: Vec<String>,
|
||||
pub db: String,
|
||||
pub id: String,
|
||||
/// Path relative to the checkout it came from (used only for ordering and display).
|
||||
@@ -49,7 +50,7 @@ pub fn collect_core_sql(core: &Path) -> Result<Vec<SqlFile>> {
|
||||
let mut out = Vec::new();
|
||||
let mut push = |db: &str, id: String, abs: PathBuf, origin: String| -> Result<()> {
|
||||
let sha256 = fsx::sha256_file(&abs)?;
|
||||
out.push(SqlFile { db: db.into(), id, origin, abs, sha256 });
|
||||
out.push(SqlFile { compatible_sha256: vec![], db: db.into(), id, origin, abs, sha256 });
|
||||
Ok(())
|
||||
};
|
||||
for (kind, dirs) in [("auth", ["db_auth", "pending_db_auth"]), ("characters", ["db_characters", "pending_db_characters"]), ("world", ["db_world", "pending_db_world"])] {
|
||||
@@ -92,13 +93,13 @@ pub fn collect_bots_sql(bots: &Path) -> Result<Vec<SqlFile>> {
|
||||
let mut out = Vec::new();
|
||||
for f in sql_in(&bots.join("dist/sql")) {
|
||||
let stem = f.file_stem().unwrap().to_string_lossy().into_owned();
|
||||
out.push(SqlFile { db: "characters".into(), id: format!("mod_coa_playerbots__{stem}"), origin: format!("dist/sql/{stem}.sql"), sha256: fsx::sha256_file(&f)?, abs: f });
|
||||
out.push(SqlFile { compatible_sha256: vec![], db: "characters".into(), id: format!("mod_coa_playerbots__{stem}"), origin: format!("dist/sql/{stem}.sql"), sha256: fsx::sha256_file(&f)?, abs: f });
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn to_migrations(files: &[SqlFile]) -> Vec<Migration> {
|
||||
files.iter().map(|f| Migration { id: f.id.clone(), db: f.db.clone(), sha256: f.sha256.clone(), destructive: false }).collect()
|
||||
files.iter().map(|f| Migration { compatible_sha256: f.compatible_sha256.clone(), id: f.id.clone(), db: f.db.clone(), sha256: f.sha256.clone(), destructive: false }).collect()
|
||||
}
|
||||
|
||||
pub struct UpdateParams<'a> {
|
||||
@@ -226,7 +227,7 @@ mod tests {
|
||||
write(&tree, "Core/newlib.dll", "n");
|
||||
write(&tree, crate::schema_check::CONTRACT, "same contract");
|
||||
write(&sqldir, "world.sql", "SELECT 1;");
|
||||
let sql = vec![SqlFile { db: "world".into(), id: "m1".into(), origin: "x".into(), abs: sqldir.join("world.sql"), sha256: fsx::sha256_file(&sqldir.join("world.sql")).unwrap() }];
|
||||
let sql = vec![SqlFile { compatible_sha256: vec![], db: "world".into(), id: "m1".into(), origin: "x".into(), abs: sqldir.join("world.sql"), sha256: fsx::sha256_file(&sqldir.join("world.sql")).unwrap() }];
|
||||
let m = pack_update(&UpdateParams { tree: &tree, base_manifest: &base, sql: &sql, out: &upd_out, version: "1.1.0".into(), core_commit: Some("a".repeat(40)), bots_commit: Some("b".repeat(40)), part_size: 1 << 20 }, &|_| {}).unwrap();
|
||||
let paths: Vec<&str> = m.files.iter().map(|f| f.path.as_str()).collect();
|
||||
assert!(paths.contains(&"Core/worldserver.exe") && paths.contains(&"Core/newlib.dll"));
|
||||
|
||||
@@ -16,7 +16,7 @@ pub fn collect(core: &Path, bots: Option<&Path>, repairs: Option<&Path>) -> Resu
|
||||
paths.sort();
|
||||
for path in paths.into_iter().filter(|p| p.extension().is_some_and(|e| e == "sql")) {
|
||||
let stem = path.file_stem().unwrap().to_string_lossy();
|
||||
files.push(SqlFile { db: kind.into(), id: format!("manager_repair__{stem}"), origin: format!("{kind}/{stem}.sql"), sha256: fsx::sha256_file(&path)?, abs: path });
|
||||
files.push(SqlFile { compatible_sha256: vec![], db: kind.into(), id: format!("manager_repair__{stem}"), origin: format!("{kind}/{stem}.sql"), sha256: fsx::sha256_file(&path)?, abs: path });
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -47,7 +47,7 @@ pub fn capture_release(fixture: &Path, tree: &Path, sql: &[SqlFile]) -> Result<(
|
||||
return Err(Error::Invalid("Refusing to apply release SQL to a non-fixture server.".into()));
|
||||
}
|
||||
let staging = tempfile::tempdir()?;
|
||||
let migrations: Vec<_> = sql.iter().map(|f| Migration { db: f.db.clone(), id: f.id.clone(), sha256: f.sha256.clone(), destructive: false }).collect();
|
||||
let migrations: Vec<_> = sql.iter().map(|f| Migration { compatible_sha256: f.compatible_sha256.clone(), db: f.db.clone(), id: f.id.clone(), sha256: f.sha256.clone(), destructive: false }).collect();
|
||||
for file in sql {
|
||||
let path = fsx::safe_join(staging.path(), &format!("{}/{}.sql", file.db, file.id))?;
|
||||
fsx::atomic_write(&path, &std::fs::read(&file.abs)?)?;
|
||||
|
||||
+803
-121
File diff suppressed because it is too large.
Load diff
@@ -7,4 +7,7 @@ license.workspace = true
|
||||
[dependencies]
|
||||
coa-core = { path = "../coa-core" }
|
||||
serde_json = "1"
|
||||
base64 = "0.22"
|
||||
ed25519-dalek = "2"
|
||||
tempfile = "3"
|
||||
chrono = { version = "0.4", default-features = false, features = ["clock", "std"] }
|
||||
@@ -46,6 +46,65 @@ fn run() -> Result<(), String> {
|
||||
let e = |x: coa_core::Error| x.to_string();
|
||||
let part = a.get("part-size").and_then(|v| v.parse().ok()).unwrap_or(DEFAULT_PART_SIZE);
|
||||
match cmd.as_str() {
|
||||
"verify-registry" => {
|
||||
let sql = coa_core::migration_registry::reconcile(&PathBuf::from(need(&a, "registry")?), Vec::new()).map_err(e)?;
|
||||
println!("Verified {} historical migrations, order and signed byte variants", sql.len());
|
||||
}
|
||||
"resolve" => {
|
||||
let package = coa_core::pkgsource::fetch_package(&coa_core::pkgsource::Source::Url(need(&a, "source")?.clone()), coa_core::signing::EMBEDDED_PUBLIC_KEY).map_err(e)?;
|
||||
coa_core::fsx::atomic_write(&PathBuf::from(need(&a, "out")?), &package.bytes).map_err(e)?;
|
||||
}
|
||||
"extract-game-data" => {
|
||||
let source = PathBuf::from(need(&a, "package")?);
|
||||
let package = coa_core::pkgsource::fetch_package(&coa_core::pkgsource::Source::Dir(source.clone()), coa_core::signing::EMBEDDED_PUBLIC_KEY).map_err(e)?;
|
||||
if !package.manifest.files.iter().any(|f| f.path.starts_with("Data/")) { return Err("Signed base has no game data.".into()); }
|
||||
coa_core::package::extract_selected(&source, &package.manifest, &PathBuf::from(need(&a, "fixture")?), &|p| p.starts_with("Data/"), &|_, _| {}).map_err(e)?;
|
||||
}
|
||||
"repackage" => {
|
||||
let source = PathBuf::from(need(&a, "package")?);
|
||||
let pinned = coa_core::pkgsource::fetch_package(&coa_core::pkgsource::Source::Dir(source.clone()), coa_core::signing::EMBEDDED_PUBLIC_KEY).map_err(e)?;
|
||||
let work = tempfile::tempdir().map_err(|e| e.to_string())?;
|
||||
coa_core::package::extract(&source, &pinned.manifest, work.path(), &|_, _| {}).map_err(e)?;
|
||||
let mut sql: Vec<_> = pinned.manifest.migrations.iter().map(|m| coa_core::release::SqlFile {
|
||||
compatible_sha256: m.compatible_sha256.clone(), db: m.db.clone(), id: m.id.clone(), sha256: m.sha256.clone(), origin: "signed package".into(), abs: work.path().join("_migrations").join(&m.db).join(format!("{}.sql", m.id)),
|
||||
}).collect();
|
||||
let repairs = PathBuf::from(need(&a, "repairs")?);
|
||||
for repair in coa_core::release_schema::collect(&work.path().join("no-core"), None, Some(&repairs)).map_err(e)? {
|
||||
if !sql.iter().any(|m| m.db == repair.db && m.id == repair.id) { sql.push(repair); }
|
||||
}
|
||||
let sql = coa_core::migration_registry::reconcile(&PathBuf::from(need(&a, "registry")?), sql).map_err(e)?;
|
||||
let migrations = sql.iter().map(|m| coa_core::manifest::Migration { compatible_sha256: m.compatible_sha256.clone(), db: m.db.clone(), id: m.id.clone(), sha256: m.sha256.clone(), destructive: false }).collect();
|
||||
for file in &sql { coa_core::fsx::atomic_write(&work.path().join("_migrations").join(&file.db).join(format!("{}.sql", file.id)), &std::fs::read(&file.abs).map_err(|e| e.to_string())?).map_err(e)?; }
|
||||
let out = PathBuf::from(need(&a, "out")?);
|
||||
let opts = BuildOptions { kind: Kind::Update, version: need(&a, "version")?.clone(), core_commit: pinned.manifest.core.commit, bots_commit: pinned.manifest.bots.and_then(|b| b.commit), built_at: chrono_now(), part_size: part, migrations };
|
||||
let mut manifest = build(work.path(), &out, &opts, &|s| eprintln!("{s}")).map_err(e)?;
|
||||
manifest.min_manager_version = coa_core::MANAGER_VERSION.into();
|
||||
coa_core::fsx::atomic_write_json(&out.join("manifest.json"), &manifest).map_err(e)?;
|
||||
}
|
||||
"archive-migrations" => {
|
||||
coa_core::migration_registry::import(&PathBuf::from(need(&a, "package")?), &PathBuf::from(need(&a, "registry")?), coa_core::signing::EMBEDDED_PUBLIC_KEY).map_err(e)?;
|
||||
println!("Published migration bytes and compatibility archived");
|
||||
}
|
||||
"verify-channel" => {
|
||||
let pointer = coa_core::pkgsource::verify_channel(&std::fs::read(need(&a, "file")?).map_err(|e| e.to_string())?, coa_core::signing::EMBEDDED_PUBLIC_KEY).map_err(e)?;
|
||||
let dir = PathBuf::from(need(&a, "dir")?);
|
||||
let manifest: Manifest = coa_core::fsx::read_json(&dir.join("manifest.json")).map_err(e)?;
|
||||
if manifest.version != pointer.version || coa_core::fsx::sha256_file(&dir.join("manifest.json")).map_err(e)? != pointer.manifest_sha256 || pointer.acceptance_sha256.as_deref() != Some(&coa_core::fsx::sha256_file(&dir.join("acceptance.json")).map_err(e)?) {
|
||||
return Err("Signed channel differs from the tested package/report".into());
|
||||
}
|
||||
}
|
||||
"channel" => {
|
||||
use base64::{engine::general_purpose::STANDARD, Engine};
|
||||
use ed25519_dalek::{Signer, SigningKey};
|
||||
let dir = PathBuf::from(need(&a, "dir")?);
|
||||
let pinned = coa_core::pkgsource::fetch_package(&coa_core::pkgsource::Source::Dir(dir.clone()), coa_core::signing::EMBEDDED_PUBLIC_KEY).map_err(e)?;
|
||||
let pointer = coa_core::pkgsource::Channel { schema: 1, version: pinned.manifest.version.clone(), release: format!("https://github.com/Corfirean/coa-server-build/releases/download/server-{}/", pinned.manifest.version), manifest_sha256: coa_core::fsx::sha256_bytes(&pinned.bytes), acceptance_sha256: Some(coa_core::fsx::sha256_file(&dir.join("acceptance.json")).map_err(e)?) };
|
||||
let payload = serde_json::to_vec(&pointer).map_err(|e| e.to_string())?;
|
||||
let seed: [u8; 32] = STANDARD.decode(signing_key()?.trim()).map_err(|e| e.to_string())?.try_into().map_err(|_| "Wrong signing key length")?;
|
||||
let signed = coa_core::pkgsource::SignedChannel { payload: STANDARD.encode(&payload), signature: STANDARD.encode(SigningKey::from_bytes(&seed).sign(&payload).to_bytes()) };
|
||||
coa_core::signing::verify_embedded(&payload, &signed.signature).map_err(e)?;
|
||||
coa_core::fsx::atomic_write_json(&PathBuf::from(need(&a, "out")?), &signed).map_err(e)?;
|
||||
}
|
||||
"extract-schema-base" => {
|
||||
coa_core::release_schema::extract_base(
|
||||
&PathBuf::from(need(&a, "package")?), &PathBuf::from(need(&a, "fixture")?),
|
||||
@@ -59,7 +118,8 @@ fn run() -> Result<(), String> {
|
||||
if let Some(core) = a.get("core") {
|
||||
let bots = a.get("bots").map(PathBuf::from);
|
||||
let repairs = a.get("repairs").map(PathBuf::from);
|
||||
let sql = coa_core::release_schema::collect(&PathBuf::from(core), bots.as_deref(), repairs.as_deref()).map_err(e)?;
|
||||
let mut sql = coa_core::release_schema::collect(&PathBuf::from(core), bots.as_deref(), repairs.as_deref()).map_err(e)?;
|
||||
if let Some(registry) = a.get("registry") { sql = coa_core::migration_registry::reconcile(&PathBuf::from(registry), sql).map_err(e)?; }
|
||||
coa_core::release_schema::capture_release(&repack, &tree, &sql).map_err(e)?;
|
||||
} else {
|
||||
coa_core::backup::with_database(&repack, |db| coa_core::schema_check::capture(db, &tree)).map_err(e)?;
|
||||
@@ -77,7 +137,8 @@ fn run() -> Result<(), String> {
|
||||
coa_core::schema_check::require_release_contract(&PathBuf::from(need(&a, "tree")?)).map_err(e)?;
|
||||
let bots = a.get("bots").map(PathBuf::from);
|
||||
let repairs = a.get("repairs").map(PathBuf::from);
|
||||
let sql = coa_core::release_schema::collect(&PathBuf::from(need(&a, "core")?), bots.as_deref(), repairs.as_deref()).map_err(e)?;
|
||||
let mut sql = coa_core::release_schema::collect(&PathBuf::from(need(&a, "core")?), bots.as_deref(), repairs.as_deref()).map_err(e)?;
|
||||
if let Some(registry) = a.get("registry") { sql = coa_core::migration_registry::reconcile(&PathBuf::from(registry), sql).map_err(e)?; }
|
||||
let out = PathBuf::from(need(&a, "out")?);
|
||||
let m = pack_update(
|
||||
&UpdateParams { tree: &PathBuf::from(need(&a, "tree")?), base_manifest: &base, sql: &sql, out: &out, version: need(&a, "version")?.clone(), core_commit: a.get("core-commit").cloned(), bots_commit: a.get("bots-commit").cloned(), part_size: part },
|
||||
|
||||
Reference in new issue
Block a user