feat(phase15): release and security hardening, DPAPI key store, probe & protocol hardening, secret redaction, audit and readiness report

This commit is contained in:
Дмитрий committed 2026-10-09 21:59:44 +05:00
1 parent b69fa6b867
commit 51e0f136d6
207 files changed
+38235 -7770

No files matched your search

+253 -64
View File
@@ -68,43 +68,71 @@ fn no_window(cmd: &mut Command) {
}
/// Schema names of the three game databases.
pub const SCHEMAS: [(&str, &str); 3] = [("characters", "acore_characters"), ("auth", "acore_auth"), ("world", "acore_world")];
pub const SCHEMAS: [(&str, &str); 3] = [
("characters", "acore_characters"),
("auth", "acore_auth"),
("world", "acore_world"),
];
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("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("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 {
!name.is_empty() && name.len() <= 64 && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
!name.is_empty()
&& name.len() <= 64
&& name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
}
/// (root password, application password) from `Settings/database.json`.
pub(crate) fn credentials(root: &Path) -> Result<(String, String)> {
let c: Credentials = fsx::read_json(&root.join("Settings/database.json"))
.map_err(|_| Error::Invalid("The database settings of this server could not be read.".into()))?;
let c: Credentials = fsx::read_json(&root.join("Settings/database.json")).map_err(|_| {
Error::Invalid("The database settings of this server could not be read.".into())
})?;
Ok((c.root_password, c.app_password))
}
impl Db {
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()))?;
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())
})?;
let ports: Ports = read_ports(root);
if crate::docker::is_docker(root) {
return Db::in_container(root, creds, account);
}
let bin = root.join("mysql/bin");
if !bin.join("mysqldump.exe").is_file() || !bin.join("mysql.exe").is_file() {
return Err(Error::Invalid("The bundled database tools are missing.".into()));
return Err(Error::Invalid(
"The bundled database tools are missing.".into(),
));
}
let (user, password) = match account {
Account::Admin => ("root", creds.root_password),
Account::App => ("acore", creds.app_password),
};
Ok(Db { bin, port: ports.mysql, user, password: Secret(password), realm: crate::realms::state(root)?.active, container: None })
Ok(Db {
bin,
port: ports.mysql,
user,
password: Secret(password),
realm: crate::realms::state(root)?.active,
container: None,
})
}
/// The database of a Docker installation: the client tools of the database image, run with `docker exec`. The
@@ -117,17 +145,42 @@ impl Db {
};
// Inside the container the server listens on its standard port; the commands below connect to it over TCP on
// the container's own loopback, exactly like the commands of a repack do on the host.
Ok(Db { bin: PathBuf::new(), port: 3306, user, password: Secret(password), realm: crate::realms::state(root)?.active, container: Some(container) })
Ok(Db {
bin: PathBuf::new(),
port: 3306,
user,
password: Secret(password),
realm: crate::realms::state(root)?.active,
container: Some(container),
})
}
/// A database reached through explicitly given client tools. Used by tests against a disposable server; the
/// installation-based constructors above are what the Manager itself uses.
pub fn with_tools(bin: PathBuf, port: u16, user: &'static str, password: &str, realm: crate::realms::Mode) -> Db {
Db { bin, port, user, password: Secret(password.to_string()), realm, container: None }
pub fn with_tools(
bin: PathBuf,
port: u16,
user: &'static str,
password: &str,
realm: crate::realms::Mode,
) -> Db {
Db {
bin,
port,
user,
password: Secret(password.to_string()),
realm,
container: None,
}
}
pub fn for_realm(mut self, realm: crate::realms::Mode) -> Self { self.realm = realm; self }
pub fn realm(&self) -> crate::realms::Mode { self.realm }
pub fn for_realm(mut self, realm: crate::realms::Mode) -> Self {
self.realm = realm;
self
}
pub fn realm(&self) -> crate::realms::Mode {
self.realm
}
pub fn realm_schema<'a>(&self, name: &'a str) -> &'a str {
if self.realm == crate::realms::Mode::Wildcard {
@@ -136,11 +189,15 @@ impl Db {
"acore_characters" => "acore_characters_wildcard",
_ => name,
}
} else { name }
} else {
name
}
}
pub fn clone_structure(&self, source: &str, dest: &str, cache: &Path) -> Result<()> {
if !ident_ok(source) || !ident_ok(dest) { return Err(Error::Invalid("Invalid schema name.".into())); }
if !ident_ok(source) || !ident_ok(dest) {
return Err(Error::Invalid("Invalid schema name.".into()));
}
let path = cache.join("characters-structure.sql");
self.dump_structure_to(source, &path)?;
self.run_sql_file(dest, &path)?;
@@ -149,12 +206,22 @@ impl Db {
}
pub fn dump_structure_to(&self, source: &str, path: &Path) -> Result<()> {
if !ident_ok(source) { return Err(Error::Invalid("Invalid schema name.".into())); }
if !ident_ok(source) {
return Err(Error::Invalid("Invalid schema name.".into()));
}
let mut c = self.command("mysqldump.exe");
c.args(["--no-data", "--no-tablespaces", "--skip-comments", "--default-character-set=utf8mb4", source]);
c.stdout(Stdio::from(File::create(&path)?));
c.args([
"--no-data",
"--no-tablespaces",
"--skip-comments",
"--default-character-set=utf8mb4",
source,
]);
c.stdout(Stdio::from(File::create(path)?));
let out = c.output()?;
if !out.status.success() { return Err(self.fail(&out.stderr)); }
if !out.status.success() {
return Err(self.fail(&out.stderr));
}
Ok(())
}
@@ -164,7 +231,14 @@ impl Db {
Some(name) => {
// `-e MYSQL_PWD` without a value takes it from this process's environment: never on a command line.
let mut c = Command::new("docker");
c.args(["exec", "-i", "-e", "MYSQL_PWD", name, tool.trim_end_matches(".exe")]);
c.args([
"exec",
"-i",
"-e",
"MYSQL_PWD",
name,
tool.trim_end_matches(".exe"),
]);
c
}
};
@@ -182,11 +256,23 @@ impl Db {
fn fail(&self, stderr: &[u8]) -> Error {
let text = String::from_utf8_lossy(stderr);
let down = text.contains("2003") || text.contains("Can't connect") || text.contains("is not running") || text.contains("No such container");
let code = if down { ErrorCode::DatabaseNotRunning } else { ErrorCode::Unknown };
let down = text.contains("2003")
|| text.contains("Can't connect")
|| text.contains("is not running")
|| text.contains("No such container");
let code = if down {
ErrorCode::DatabaseNotRunning
} else {
ErrorCode::Unknown
};
match code {
ErrorCode::DatabaseNotRunning => Error::Invalid("The database is not running. Start the server first.".into()),
_ => Error::Invalid(format!("database command failed: {}", text.trim().lines().last().unwrap_or(""))),
ErrorCode::DatabaseNotRunning => {
Error::Invalid("The database is not running. Start the server first.".into())
}
_ => Error::Invalid(format!(
"database command failed: {}",
text.trim().lines().last().unwrap_or("")
)),
}
}
@@ -200,10 +286,17 @@ impl Db {
pub fn query(&self, sql: &str) -> Result<String> {
let mut c = self.command("mysql.exe");
c.args(["--batch", "--skip-column-names", "--connect-timeout=5"]);
c.args(["--default-character-set=utf8mb4", "--max-allowed-packet=128M"]);
c.args([
"--default-character-set=utf8mb4",
"--max-allowed-packet=128M",
]);
c.stdin(Stdio::piped());
let mut child = c.spawn()?;
child.stdin.take().expect("piped").write_all(route_sql(sql, self.realm).as_bytes())?;
child
.stdin
.take()
.expect("piped")
.write_all(route_sql(sql, self.realm).as_bytes())?;
let out = child.wait_with_output()?;
if !out.status.success() {
return Err(self.fail(&out.stderr));
@@ -216,7 +309,9 @@ impl Db {
if !ident_ok(name) {
return Err(Error::Invalid("bad schema name".into()));
}
Ok(self.query(&format!("SELECT COUNT(*) FROM information_schema.schemata WHERE schema_name='{name}';"))? == "1")
Ok(self.query(&format!(
"SELECT COUNT(*) FROM information_schema.schemata WHERE schema_name='{name}';"
))? == "1")
}
pub fn tables(&self, schema: &str) -> Result<Vec<String>> {
@@ -225,7 +320,11 @@ impl Db {
return Err(Error::Invalid("bad schema name".into()));
}
let out = self.query(&format!("SELECT table_name FROM information_schema.tables WHERE table_schema='{schema}' AND table_type='BASE TABLE' ORDER BY table_name;"))?;
Ok(out.lines().map(str::to_string).filter(|s| !s.is_empty()).collect())
Ok(out
.lines()
.map(str::to_string)
.filter(|s| !s.is_empty())
.collect())
}
/// Bytes of data + index the schema occupies (used to estimate backup size).
@@ -235,7 +334,9 @@ impl Db {
return Err(Error::Invalid("bad schema name".into()));
}
let out = self.query(&format!("SELECT COALESCE(SUM(data_length+index_length),0) FROM information_schema.tables WHERE table_schema='{schema}';"))?;
out.trim().parse().map_err(|_| Error::Invalid("unexpected size reply".into()))
out.trim()
.parse()
.map_err(|_| Error::Invalid("unexpected size reply".into()))
}
/// Stored routines / triggers / views make a table-level swap unsafe; count them.
@@ -247,7 +348,10 @@ impl Db {
let sql = format!(
"SELECT (SELECT COUNT(*) FROM information_schema.routines WHERE routine_schema='{schema}') + (SELECT COUNT(*) FROM information_schema.triggers WHERE trigger_schema='{schema}') + (SELECT COUNT(*) FROM information_schema.views WHERE table_schema='{schema}');"
);
self.query(&sql)?.trim().parse().map_err(|_| Error::Invalid("unexpected reply".into()))
self.query(&sql)?
.trim()
.parse()
.map_err(|_| Error::Invalid("unexpected reply".into()))
}
/// Consistent dump of one schema, zstd-compressed to `out`. Returns (compressed bytes, sha256 of the file).
@@ -257,7 +361,16 @@ impl Db {
return Err(Error::Invalid("bad schema name".into()));
}
let mut c = self.command("mysqldump.exe");
c.args(["--single-transaction", "--quick", "--routines", "--triggers", "--default-character-set=utf8mb4", "--no-tablespaces", "--skip-comments", "--hex-blob"]);
c.args([
"--single-transaction",
"--quick",
"--routines",
"--triggers",
"--default-character-set=utf8mb4",
"--no-tablespaces",
"--skip-comments",
"--hex-blob",
]);
c.arg(schema);
let mut child = c.spawn()?;
let mut stdout = child.stdout.take().expect("piped");
@@ -292,11 +405,17 @@ impl Db {
}
if self.realm == crate::realms::Mode::Wildcard {
let sql = std::fs::read_to_string(file)?;
self.query(&format!("SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci; USE `{schema}`;\n{sql}"))?;
self.query(&format!(
"SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci; USE `{schema}`;\n{sql}"
))?;
return Ok(());
}
let mut c = self.command("mysql.exe");
c.args(["--default-character-set=utf8mb4", "--init-command=SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci", "--max-allowed-packet=128M"]);
c.args([
"--default-character-set=utf8mb4",
"--init-command=SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci",
"--max-allowed-packet=128M",
]);
c.arg(schema);
c.stdin(Stdio::from(File::open(file)?));
let out = c.output()?;
@@ -313,7 +432,11 @@ impl Db {
return Err(Error::Invalid("bad schema name".into()));
}
let mut c = self.command("mysql.exe");
c.args(["--default-character-set=utf8mb4", "--init-command=SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci", "--max-allowed-packet=128M"]);
c.args([
"--default-character-set=utf8mb4",
"--init-command=SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci",
"--max-allowed-packet=128M",
]);
c.arg(schema);
c.stdin(Stdio::piped());
let mut child = c.spawn()?;
@@ -359,7 +482,9 @@ impl Db {
pub fn write_console_credentials(root: &Path, password: &str) -> Result<()> {
let path = root.join("Settings/repack.json");
let mut v: serde_json::Value = fsx::read_json(&path)?;
let obj = v.as_object_mut().ok_or_else(|| Error::Invalid("repack.json is not an object".into()))?;
let obj = v
.as_object_mut()
.ok_or_else(|| Error::Invalid("repack.json is not an object".into()))?;
obj.insert("raUsername".into(), SERVICE_ACCOUNT.into());
obj.insert("raPassword".into(), password.into());
fsx::atomic_write_json(&path, &v)
@@ -371,36 +496,55 @@ pub fn valid_identifier(name: &str) -> bool {
// Route only SQL identifiers. User names, values, comments and longer identifiers remain untouched.
fn route_sql(sql: &str, realm: crate::realms::Mode) -> String {
if realm == crate::realms::Mode::Coa { return sql.into(); }
if realm == crate::realms::Mode::Coa {
return sql.into();
}
let bytes = sql.as_bytes();
let mut out = String::new();
let mut i = 0;
while i < bytes.len() {
let start = i;
if matches!(bytes[i], b'\'' | b'"') {
let quote = bytes[i]; i += 1;
let quote = bytes[i];
i += 1;
while i < bytes.len() {
if bytes[i] == b'\\' { i = (i + 2).min(bytes.len()); }
else if bytes[i] == quote {
if bytes[i] == b'\\' {
i = (i + 2).min(bytes.len());
} else if bytes[i] == quote {
i += 1;
if i < bytes.len() && bytes[i] == quote { i += 1; } else { break; }
} else { i += 1; }
if i < bytes.len() && bytes[i] == quote {
i += 1;
} else {
break;
}
} else {
i += 1;
}
}
out.push_str(&sql[start..i]);
} else if bytes[i] == b'#' || sql[i..].starts_with("--") || sql[i..].starts_with("/*") {
if sql[i..].starts_with("/*") {
i = sql[i + 2..].find("*/").map(|p| i + p + 4).unwrap_or(bytes.len());
} else { i = sql[i..].find('\n').map(|p| i + p).unwrap_or(bytes.len()); }
i = sql[i + 2..]
.find("*/")
.map(|p| i + p + 4)
.unwrap_or(bytes.len());
} else {
i = sql[i..].find('\n').map(|p| i + p).unwrap_or(bytes.len());
}
out.push_str(&sql[start..i]);
} else if bytes[i].is_ascii_alphanumeric() || bytes[i] == b'_' {
while i < bytes.len() && (bytes[i].is_ascii_alphanumeric() || bytes[i] == b'_') { i += 1; }
while i < bytes.len() && (bytes[i].is_ascii_alphanumeric() || bytes[i] == b'_') {
i += 1;
}
out.push_str(match &sql[start..i] {
"acore_world" => "acore_world_wildcard",
"acore_characters" => "acore_characters_wildcard",
other => other,
});
} else {
let c = sql[i..].chars().next().unwrap(); out.push(c); i += c.len_utf8();
let c = sql[i..].chars().next().unwrap();
out.push(c);
i += c.len_utf8();
}
}
out
@@ -428,7 +572,11 @@ mod tests {
let d = tempfile::tempdir().unwrap();
let root = d.path().join("srv");
std::fs::create_dir_all(root.join("Settings")).unwrap();
std::fs::write(root.join("Settings/database.json"), format!(r#"{{"rootPassword":"{ROOT_PW}","appPassword":"{APP_PW}"}}"#)).unwrap();
std::fs::write(
root.join("Settings/database.json"),
format!(r#"{{"rootPassword":"{ROOT_PW}","appPassword":"{APP_PW}"}}"#),
)
.unwrap();
if docker {
std::fs::write(root.join("Settings/docker.json"), r#"{"project":"t1"}"#).unwrap();
}
@@ -436,28 +584,48 @@ mod tests {
}
fn args(c: &Command) -> Vec<String> {
c.get_args().map(|a| a.to_string_lossy().into_owned()).collect()
c.get_args()
.map(|a| a.to_string_lossy().into_owned())
.collect()
}
fn env_of(c: &Command, key: &str) -> Option<String> {
c.get_envs().find(|(k, _)| *k == OsStr::new(key)).and_then(|(_, v)| v.map(|v| v.to_string_lossy().into_owned()))
c.get_envs()
.find(|(k, _)| *k == OsStr::new(key))
.and_then(|(_, v)| v.map(|v| v.to_string_lossy().into_owned()))
}
#[test]
fn a_docker_installation_runs_the_client_tools_inside_the_database_container() {
let (_d, root) = folder(true);
let db = Db::from_repack(&root, Account::Admin).unwrap();
for (tool, program) in [("mysql.exe", "mysql"), ("mysqldump.exe", "mysqldump"), ("mysqladmin.exe", "mysqladmin")] {
for (tool, program) in [
("mysql.exe", "mysql"),
("mysqldump.exe", "mysqldump"),
("mysqladmin.exe", "mysqladmin"),
] {
let c = db.command(tool);
assert_eq!(c.get_program(), "docker");
let a = args(&c);
assert_eq!(&a[..6], ["exec", "-i", "-e", "MYSQL_PWD", "coa-t1-db", program]);
assert!(a.contains(&"--protocol=tcp".to_string()) && a.contains(&"--host=127.0.0.1".to_string()) && a.contains(&"--port=3306".to_string()));
assert_eq!(
&a[..6],
["exec", "-i", "-e", "MYSQL_PWD", "coa-t1-db", program]
);
assert!(
a.contains(&"--protocol=tcp".to_string())
&& a.contains(&"--host=127.0.0.1".to_string())
&& a.contains(&"--port=3306".to_string())
);
assert!(a.contains(&"--user=root".to_string()));
assert!(a.iter().all(|x| !x.contains(ROOT_PW)), "the password must not be on the command line");
assert!(
a.iter().all(|x| !x.contains(ROOT_PW)),
"the password must not be on the command line"
);
assert_eq!(env_of(&c, "MYSQL_PWD").as_deref(), Some(ROOT_PW));
}
let app = Db::from_repack(&root, Account::App).unwrap().command("mysql.exe");
let app = Db::from_repack(&root, Account::App)
.unwrap()
.command("mysql.exe");
assert!(args(&app).contains(&"--user=acore".to_string()));
assert_eq!(env_of(&app, "MYSQL_PWD").as_deref(), Some(APP_PW));
}
@@ -470,11 +638,18 @@ mod tests {
std::fs::write(root.join("mysql/bin").join(f), b"x").unwrap();
}
std::fs::write(root.join("Settings/repack.json"), r#"{"mysqlPort":3999}"#).unwrap();
let c = Db::from_repack(&root, Account::Admin).unwrap().command("mysql.exe");
assert_eq!(c.get_program(), root.join("mysql/bin").join("mysql.exe").as_os_str());
let c = Db::from_repack(&root, Account::Admin)
.unwrap()
.command("mysql.exe");
assert_eq!(
c.get_program(),
root.join("mysql/bin").join("mysql.exe").as_os_str()
);
let a = args(&c);
assert!(!a.contains(&"exec".to_string()));
assert!(a.contains(&"--port=3999".to_string()) && a.contains(&"--host=127.0.0.1".to_string()));
assert!(
a.contains(&"--port=3999".to_string()) && a.contains(&"--host=127.0.0.1".to_string())
);
assert_eq!(env_of(&c, "MYSQL_PWD").as_deref(), Some(ROOT_PW));
}
@@ -484,7 +659,11 @@ mod tests {
assert!(!root.join("mysql").exists());
assert!(Db::from_repack(&root, Account::Admin).is_ok());
// ...but a broken Docker settings file is reported, not ignored.
std::fs::write(root.join("Settings/docker.json"), r#"{"project":"Bad Name"}"#).unwrap();
std::fs::write(
root.join("Settings/docker.json"),
r#"{"project":"Bad Name"}"#,
)
.unwrap();
assert!(Db::from_repack(&root, Account::Admin).is_err());
}
@@ -492,9 +671,19 @@ mod tests {
fn a_stopped_database_container_is_reported_as_a_database_that_is_not_running() {
let (_d, root) = folder(true);
let db = Db::from_repack(&root, Account::Admin).unwrap();
for text in ["Error response from daemon: container abc is not running", "Error response from daemon: No such container: coa-t1-db", "ERROR 2003 (HY000): Can't connect to MySQL server"] {
assert!(db.fail(text.as_bytes()).to_string().contains("not running"), "{text}");
for text in [
"Error response from daemon: container abc is not running",
"Error response from daemon: No such container: coa-t1-db",
"ERROR 2003 (HY000): Can't connect to MySQL server",
] {
assert!(
db.fail(text.as_bytes()).to_string().contains("not running"),
"{text}"
);
}
assert!(db.fail(b"ERROR 1045 (28000): Access denied for user 'root'").to_string().contains("Access denied"));
assert!(db
.fail(b"ERROR 1045 (28000): Access denied for user 'root'")
.to_string()
.contains("Access denied"));
}
}