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

+306 -57
View File
@@ -13,7 +13,9 @@ use sha2::{Digest, Sha256};
use crate::error::{Error, Result};
use crate::fsx;
use crate::manifest::{ArchiveInfo, ArchivePart, FileEntry, Kind, Manifest, Owner, ReplacePolicy, Revision};
use crate::manifest::{
ArchiveInfo, ArchivePart, FileEntry, Kind, Manifest, Owner, ReplacePolicy, Revision,
};
/// GitHub release assets are limited to 2 GiB; stay clearly below.
pub const DEFAULT_PART_SIZE: u64 = 1_900_000_000;
@@ -29,7 +31,13 @@ pub const BASELINE_DIR: &str = "Database/baseline";
/// Files that never belong in a shipped package: per-install state, logs, secrets, old binaries.
pub fn excluded(rel: &str) -> bool {
if rel.replace('\\', "/").to_lowercase().starts_with(".realms/") { return true; }
if rel
.replace('\\', "/")
.to_lowercase()
.starts_with(".realms/")
{
return true;
}
let l = rel.to_lowercase();
let name = l.rsplit('/').next().unwrap_or("");
l.starts_with(".state/")
@@ -84,7 +92,12 @@ struct SplitWriter {
impl SplitWriter {
fn new(dir: &Path, max: u64) -> Self {
SplitWriter { dir: dir.to_path_buf(), max, parts: Vec::new(), cur: None }
SplitWriter {
dir: dir.to_path_buf(),
max,
parts: Vec::new(),
cur: None,
}
}
fn open_next(&mut self) -> io::Result<()> {
@@ -97,7 +110,11 @@ impl SplitWriter {
fn close_current(&mut self) -> io::Result<()> {
if let Some((mut w, h, n, name)) = self.cur.take() {
w.flush()?;
self.parts.push(ArchivePart { name, size: n, sha256: hex::encode(h.finalize()) });
self.parts.push(ArchivePart {
name,
size: n,
sha256: hex::encode(h.finalize()),
});
}
Ok(())
}
@@ -136,7 +153,12 @@ fn walk(root: &Path, dir: &Path, out: &mut Vec<String>) -> io::Result<()> {
for e in fs::read_dir(dir)? {
let e = e?;
let ft = e.file_type()?;
let rel = e.path().strip_prefix(root).unwrap().to_string_lossy().replace('\\', "/");
let rel = e
.path()
.strip_prefix(root)
.unwrap()
.to_string_lossy()
.replace('\\', "/");
if ft.is_symlink() {
continue; // junctions / symlinks (e.g. a fixture's Data link) are never packaged
}
@@ -160,12 +182,20 @@ pub struct BuildOptions {
}
/// Package `src` into `out` (parts + manifest.json). Returns the manifest.
pub fn build(src: &Path, out: &Path, opts: &BuildOptions, progress: &dyn Fn(&str)) -> Result<Manifest> {
pub fn build(
src: &Path,
out: &Path,
opts: &BuildOptions,
progress: &dyn Fn(&str),
) -> Result<Manifest> {
fs::create_dir_all(out)?;
let mut rels = Vec::new();
walk(src, src, &mut rels)?;
// (name inside the archive, file on disk)
let mut files: Vec<(String, PathBuf)> = rels.into_iter().map(|r| (r.clone(), src.join(&r))).collect();
let mut files: Vec<(String, PathBuf)> = rels
.into_iter()
.map(|r| (r.clone(), src.join(&r)))
.collect();
// The database users of the packaged data directory: needed once at install to rotate the passwords.
let creds = src.join("Settings/database.json");
if opts.kind == Kind::Base && creds.is_file() {
@@ -175,7 +205,11 @@ pub fn build(src: &Path, out: &Path, opts: &BuildOptions, progress: &dyn Fn(&str
let split = SplitWriter::new(out, opts.part_size);
let mut enc = zstd::Encoder::new(split, 6)?;
enc.multithread(std::thread::available_parallelism().map(|n| n.get() as u32).unwrap_or(2))?;
enc.multithread(
std::thread::available_parallelism()
.map(|n| n.get() as u32)
.unwrap_or(2),
)?;
let mut tar = tar::Builder::new(enc);
tar.mode(tar::HeaderMode::Deterministic);
@@ -206,9 +240,22 @@ pub fn build(src: &Path, out: &Path, opts: &BuildOptions, progress: &dyn Fn(&str
}
}
let mut hasher = Sha256::new();
tar.append_data(&mut header, rel, Tee { inner: &mut f, hasher: &mut hasher })?;
tar.append_data(
&mut header,
rel,
Tee {
inner: &mut f,
hasher: &mut hasher,
},
)?;
let (owner, policy) = policy_for(rel);
entries.push(FileEntry { path: rel.clone(), sha256: hex::encode(hasher.finalize()), size, owner, policy });
entries.push(FileEntry {
path: rel.clone(),
sha256: hex::encode(hasher.finalize()),
size,
owner,
policy,
});
unpacked += size;
}
progress("Finishing archive");
@@ -220,16 +267,28 @@ pub fn build(src: &Path, out: &Path, opts: &BuildOptions, progress: &dyn Fn(&str
schema: crate::manifest::SCHEMA,
kind: opts.kind,
version: opts.version.clone(),
core: Revision { commit: opts.core_commit.clone() },
bots: opts.bots_commit.clone().map(|c| Revision { commit: Some(c) }),
core: Revision {
commit: opts.core_commit.clone(),
},
bots: opts
.bots_commit
.clone()
.map(|c| Revision { commit: Some(c) }),
built_at: opts.built_at.clone(),
min_manager_version: "0.1.0".into(),
files: entries,
migrations: opts.migrations.clone(),
archive: Some(ArchiveInfo { format: "tar.zst".into(), parts: split.parts.clone(), unpacked_size: unpacked }),
archive: Some(ArchiveInfo {
format: "tar.zst".into(),
parts: split.parts.clone(),
unpacked_size: unpacked,
}),
};
manifest.validate()?;
fsx::atomic_write(&out.join("manifest.json"), &serde_json::to_vec_pretty(&manifest)?)?;
fsx::atomic_write(
&out.join("manifest.json"),
&serde_json::to_vec_pretty(&manifest)?,
)?;
Ok(manifest)
}
@@ -262,32 +321,69 @@ impl Read for PartsReader {
/// Unpack verified `parts_dir` into `dest` (an empty or new staging folder). Every file must be listed in the
/// manifest with the recorded size and hash; anything else aborts the extraction.
pub fn extract(parts_dir: &Path, manifest: &Manifest, dest: &Path, progress: &dyn Fn(u64, u64)) -> Result<()> {
pub fn extract(
parts_dir: &Path,
manifest: &Manifest,
dest: &Path,
progress: &dyn Fn(u64, u64),
) -> Result<()> {
extract_selected(parts_dir, manifest, dest, &|_| true, progress)
}
/// Verify the entire archive, writing only selected files for a disposable release-schema fixture.
pub fn extract_selected(parts_dir: &Path, manifest: &Manifest, dest: &Path, select: &dyn Fn(&str) -> bool, progress: &dyn Fn(u64, u64)) -> Result<()> {
let archive = manifest.archive.as_ref().ok_or_else(|| Error::InvalidManifest("manifest has no archive".into()))?;
pub fn extract_selected(
parts_dir: &Path,
manifest: &Manifest,
dest: &Path,
select: &dyn Fn(&str) -> bool,
progress: &dyn Fn(u64, u64),
) -> Result<()> {
let archive = manifest
.archive
.as_ref()
.ok_or_else(|| Error::InvalidManifest("manifest has no archive".into()))?;
let mut paths = Vec::new();
for part in &archive.parts {
let p = parts_dir.join(&part.name);
let len = fs::metadata(&p).map_err(|_| Error::Invalid(format!("download part {} is missing", part.name)))?.len();
let len = fs::metadata(&p)
.map_err(|_| Error::Invalid(format!("download part {} is missing", part.name)))?
.len();
if len != part.size {
return Err(Error::HashMismatch { path: part.name.clone(), expected: format!("{} bytes", part.size), actual: format!("{len} bytes") });
return Err(Error::HashMismatch {
path: part.name.clone(),
expected: format!("{} bytes", part.size),
actual: format!("{len} bytes"),
});
}
let actual = fsx::sha256_file(&p)?;
if !actual.eq_ignore_ascii_case(&part.sha256) {
return Err(Error::HashMismatch { path: part.name.clone(), expected: part.sha256.clone(), actual });
return Err(Error::HashMismatch {
path: part.name.clone(),
expected: part.sha256.clone(),
actual,
});
}
paths.push(p);
}
let selected_size = manifest.files.iter().filter(|f| select(&f.path)).map(|f| f.size).sum();
let selected_size = manifest
.files
.iter()
.filter(|f| select(&f.path))
.map(|f| f.size)
.sum();
fsx::require_space(dest, selected_size)?;
fs::create_dir_all(dest)?;
let expected: HashMap<String, &FileEntry> = manifest.files.iter().map(|f| (f.path.replace('\\', "/").to_lowercase(), f)).collect();
let decoder = zstd::Decoder::new(PartsReader { paths, idx: 0, cur: None })?;
let expected: HashMap<String, &FileEntry> = manifest
.files
.iter()
.map(|f| (f.path.replace('\\', "/").to_lowercase(), f))
.collect();
let decoder = zstd::Decoder::new(PartsReader {
paths,
idx: 0,
cur: None,
})?;
let mut tar = tar::Archive::new(decoder);
let mut seen = std::collections::HashSet::new();
let mut done = 0u64;
@@ -298,19 +394,29 @@ pub fn extract_selected(parts_dir: &Path, manifest: &Manifest, dest: &Path, sele
match kind {
tar::EntryType::Directory => continue,
tar::EntryType::Regular | tar::EntryType::GNULongName | tar::EntryType::Continuous => {}
other => return Err(Error::PathRejected(format!("{rel}: unsupported archive entry type {other:?}"))),
other => {
return Err(Error::PathRejected(format!(
"{rel}: unsupported archive entry type {other:?}"
)))
}
}
let key = rel.to_lowercase();
let want = expected.get(&key).ok_or_else(|| Error::PathRejected(format!("{rel}: not listed in the manifest")))?;
let want = expected
.get(&key)
.ok_or_else(|| Error::PathRejected(format!("{rel}: not listed in the manifest")))?;
if !seen.insert(key) {
return Err(Error::PathRejected(format!("{rel}: appears twice in the archive")));
return Err(Error::PathRejected(format!(
"{rel}: appears twice in the archive"
)));
}
let target = fsx::safe_join(dest, &want.path)?;
let selected = select(&want.path);
let mut out = if selected {
fs::create_dir_all(target.parent().unwrap())?;
Some(BufWriter::new(File::create(&target)?))
} else { None };
} else {
None
};
let mut hasher = Sha256::new();
let mut buf = vec![0u8; 1 << 20];
let mut size = 0u64;
@@ -325,15 +431,27 @@ pub fn extract_selected(parts_dir: &Path, manifest: &Manifest, dest: &Path, sele
}
size += n as u64;
if size > want.size {
return Err(Error::HashMismatch { path: rel, expected: format!("{} bytes", want.size), actual: "more".into() });
return Err(Error::HashMismatch {
path: rel,
expected: format!("{} bytes", want.size),
actual: "more".into(),
});
}
hasher.update(&buf[..n]);
if let Some(out) = out.as_mut() { out.write_all(&buf[..n])?; }
if let Some(out) = out.as_mut() {
out.write_all(&buf[..n])?;
}
}
if let Some(out) = out.as_mut() {
out.flush()?;
}
if let Some(out) = out.as_mut() { out.flush()?; }
let actual = hex::encode(hasher.finalize());
if size != want.size || !actual.eq_ignore_ascii_case(&want.sha256) {
return Err(Error::HashMismatch { path: rel, expected: want.sha256.clone(), actual });
return Err(Error::HashMismatch {
path: rel,
expected: want.sha256.clone(),
actual,
});
}
// The archive does not carry per-file modes, so a Linux binary or script would be extracted unusable.
// Recognise them by content (ELF header or `#!`); Windows has no execute bit and ignores this.
@@ -346,7 +464,11 @@ pub fn extract_selected(parts_dir: &Path, manifest: &Manifest, dest: &Path, sele
progress(done, archive.unpacked_size);
}
if seen.len() != expected.len() {
return Err(Error::InvalidManifest(format!("archive holds {} files, manifest lists {}", seen.len(), expected.len())));
return Err(Error::InvalidManifest(format!(
"archive holds {} files, manifest lists {}",
seen.len(),
expected.len()
)));
}
Ok(())
}
@@ -356,7 +478,15 @@ mod tests {
use super::*;
fn opts(part: u64) -> BuildOptions {
BuildOptions { kind: Kind::Base, version: "0.1.0".into(), core_commit: Some("a".repeat(40)), built_at: "2026-09-30T00:00:00Z".into(), part_size: part, bots_commit: None, migrations: vec![] }
BuildOptions {
kind: Kind::Base,
version: "0.1.0".into(),
core_commit: Some("a".repeat(40)),
built_at: "2026-09-30T00:00:00Z".into(),
part_size: part,
bots_commit: None,
migrations: vec![],
}
}
fn tree(root: &Path) -> Vec<(String, Vec<u8>)> {
@@ -367,7 +497,14 @@ mod tests {
if e.file_type().unwrap().is_dir() {
walk(&e.path(), root, v);
} else {
v.push((e.path().strip_prefix(root).unwrap().to_string_lossy().replace('\\', "/"), fs::read(e.path()).unwrap()));
v.push((
e.path()
.strip_prefix(root)
.unwrap()
.to_string_lossy()
.replace('\\', "/"),
fs::read(e.path()).unwrap(),
));
}
}
}
@@ -381,12 +518,37 @@ mod tests {
let d = tempfile::tempdir().unwrap();
let src = d.path().join("src");
fs::create_dir_all(src.join("Core/configs/modules")).unwrap();
fs::write(src.join("Core/configs/modules/playerbots.conf.settings.json"), "{}\n").unwrap();
fs::write(src.join("Core/configs/modules/playerbots.conf"), "PlayerbotsDatabaseInfo = private\n").unwrap();
fs::write(
src.join("Core/configs/modules/playerbots.conf.settings.json"),
"{}\n",
)
.unwrap();
fs::write(
src.join("Core/configs/modules/playerbots.conf"),
"PlayerbotsDatabaseInfo = private\n",
)
.unwrap();
let out = d.path().join("package");
let manifest = build(&src, &out, &BuildOptions { kind: Kind::Update, version: "1.0.0".into(), core_commit: None, built_at: "test".into(), part_size: 1 << 20, bots_commit: None, migrations: vec![] }, &|_| {}).unwrap();
let manifest = build(
&src,
&out,
&BuildOptions {
kind: Kind::Update,
version: "1.0.0".into(),
core_commit: None,
built_at: "test".into(),
part_size: 1 << 20,
bots_commit: None,
migrations: vec![],
},
&|_| {},
)
.unwrap();
assert_eq!(manifest.files.len(), 1);
assert_eq!(manifest.files[0].path, "Core/configs/modules/playerbots.conf.settings.json");
assert_eq!(
manifest.files[0].path,
"Core/configs/modules/playerbots.conf.settings.json"
);
assert_eq!(manifest.files[0].policy, ReplacePolicy::Replace);
}
@@ -395,7 +557,13 @@ mod tests {
let src = d.path().join("src");
crate::layout::testkit::fake_repack(&src);
// noise that must be left out
for (p, c) in [("Core/Logs/Server.log", "log"), (".state/world.json", "{}"), ("Settings/database.json", "{\"rootPassword\":\"x\"}"), ("Core/worldserver.exe.pre-fix", "old"), ("Core/worldserver.pdb", "pdb")] {
for (p, c) in [
("Core/Logs/Server.log", "log"),
(".state/world.json", "{}"),
("Settings/database.json", "{\"rootPassword\":\"x\"}"),
("Core/worldserver.exe.pre-fix", "old"),
("Core/worldserver.pdb", "pdb"),
] {
let f = src.join(p);
fs::create_dir_all(f.parent().unwrap()).unwrap();
fs::write(f, c).unwrap();
@@ -435,8 +603,16 @@ mod tests {
extract(&out, &m, &dest, &|_, _| {}).unwrap();
let mode = |p: &str| fs::metadata(dest.join(p)).unwrap().permissions().mode() & 0o111;
assert_ne!(mode("Core/worldserver"), 0, "ELF binary must be executable");
assert_ne!(mode("Scripts/tool.sh"), 0, "script with a shebang must be executable");
assert_eq!(mode("Core/configs/worldserver.conf.dist"), 0, "plain files stay non-executable");
assert_ne!(
mode("Scripts/tool.sh"),
0,
"script with a shebang must be executable"
);
assert_eq!(
mode("Core/configs/worldserver.conf.dist"),
0,
"plain files stay non-executable"
);
}
#[test]
@@ -445,11 +621,32 @@ mod tests {
let out = d.path().join("out");
let mut manifest = build(&src, &out, &opts(64 * 1024), &|_| {}).unwrap();
let dest = d.path().join("selected");
extract_selected(&out, &manifest, &dest, &|p| p.starts_with("Core/"), &|_, _| {}).unwrap();
extract_selected(
&out,
&manifest,
&dest,
&|p| p.starts_with("Core/"),
&|_, _| {},
)
.unwrap();
assert!(dest.join("Core/worldserver.exe").exists());
assert!(!dest.join("Data").exists());
manifest.files.iter_mut().find(|f| f.path.starts_with("Data/")).unwrap().sha256 = "f".repeat(64);
assert!(matches!(extract_selected(&out, &manifest, &d.path().join("bad"), &|_| false, &|_, _| {}), Err(Error::HashMismatch { .. })));
manifest
.files
.iter_mut()
.find(|f| f.path.starts_with("Data/"))
.unwrap()
.sha256 = "f".repeat(64);
assert!(matches!(
extract_selected(
&out,
&manifest,
&d.path().join("bad"),
&|_| false,
&|_, _| {}
),
Err(Error::HashMismatch { .. })
));
}
#[test]
@@ -458,25 +655,43 @@ mod tests {
let out = d.path().join("out");
let m = build(&src, &out, &opts(64 * 1024), &|_| {}).unwrap();
let parts = &m.archive.as_ref().unwrap().parts;
assert!(parts.len() >= 3, "small part size forces a split, got {}", parts.len());
assert!(
parts.len() >= 3,
"small part size forces a split, got {}",
parts.len()
);
assert!(parts.iter().all(|p| p.size <= 64 * 1024));
let listed: Vec<&str> = m.files.iter().map(|f| f.path.as_str()).collect();
for bad in ["Core/Logs/Server.log", ".state/world.json", "Settings/database.json", "Core/worldserver.pdb"] {
for bad in [
"Core/Logs/Server.log",
".state/world.json",
"Settings/database.json",
"Core/worldserver.pdb",
] {
assert!(!listed.contains(&bad), "{bad} must not be packaged");
}
assert!(listed.contains(&"Core/worldserver.exe"));
assert!(listed.contains(&BOOTSTRAP_CREDENTIALS) || !src.join("Settings/database.json").exists());
assert!(
listed.contains(&BOOTSTRAP_CREDENTIALS) || !src.join("Settings/database.json").exists()
);
let dest = d.path().join("dest");
extract(&out, &m, &dest, &|_, _| {}).unwrap();
let mut expected = tree(&src);
expected.retain(|(p, _)| listed.contains(&p.as_str()));
// the source's database.json travels under its bootstrap name
expected.push((BOOTSTRAP_CREDENTIALS.to_string(), fs::read(src.join("Settings/database.json")).unwrap()));
expected.push((
BOOTSTRAP_CREDENTIALS.to_string(),
fs::read(src.join("Settings/database.json")).unwrap(),
));
expected.sort();
assert_eq!(tree(&dest), expected);
// user data policy
assert!(m.files.iter().filter(|f| f.path.starts_with("mysql/data/")).all(|f| f.policy == ReplacePolicy::NeverTouch));
assert!(m
.files
.iter()
.filter(|f| f.path.starts_with("mysql/data/"))
.all(|f| f.policy == ReplacePolicy::NeverTouch));
}
#[test]
@@ -489,12 +704,17 @@ mod tests {
b[100] ^= 0x55;
fs::write(&p, b).unwrap();
let dest = d.path().join("dest");
assert!(matches!(extract(&out, &m, &dest, &|_, _| {}), Err(Error::HashMismatch { .. })));
assert!(matches!(
extract(&out, &m, &dest, &|_, _| {}),
Err(Error::HashMismatch { .. })
));
assert!(!dest.exists(), "nothing extracted");
}
/// Build a hostile archive by hand and run it through `extract` with a manifest that "allows" it.
fn hostile(build_tar: impl FnOnce(&mut tar::Builder<zstd::Encoder<'static, Vec<u8>>>)) -> (tempfile::TempDir, Manifest) {
fn hostile(
build_tar: impl FnOnce(&mut tar::Builder<zstd::Encoder<'static, Vec<u8>>>),
) -> (tempfile::TempDir, Manifest) {
let d = tempfile::tempdir().unwrap();
let mut tb = tar::Builder::new(zstd::Encoder::new(Vec::new(), 1).unwrap());
build_tar(&mut tb);
@@ -510,14 +730,33 @@ mod tests {
bots: None,
built_at: "x".into(),
min_manager_version: "0.1.0".into(),
files: vec![FileEntry { path: "ok.txt".into(), sha256: ok_sha, size: 4, owner: Owner::Core, policy: ReplacePolicy::Replace }],
files: vec![FileEntry {
path: "ok.txt".into(),
sha256: ok_sha,
size: 4,
owner: Owner::Core,
policy: ReplacePolicy::Replace,
}],
migrations: vec![],
archive: Some(ArchiveInfo { format: "tar.zst".into(), parts: vec![ArchivePart { name: name.into(), size: bytes.len() as u64, sha256: fsx::sha256_bytes(&bytes) }], unpacked_size: 4 }),
archive: Some(ArchiveInfo {
format: "tar.zst".into(),
parts: vec![ArchivePart {
name: name.into(),
size: bytes.len() as u64,
sha256: fsx::sha256_bytes(&bytes),
}],
unpacked_size: 4,
}),
};
(d, m)
}
fn add(tb: &mut tar::Builder<zstd::Encoder<'static, Vec<u8>>>, path: &str, data: &[u8], ty: tar::EntryType) {
fn add(
tb: &mut tar::Builder<zstd::Encoder<'static, Vec<u8>>>,
path: &str,
data: &[u8],
ty: tar::EntryType,
) {
let mut h = tar::Header::new_gnu();
h.set_size(data.len() as u64);
h.set_entry_type(ty);
@@ -531,10 +770,17 @@ mod tests {
#[test]
fn traversal_unlisted_and_symlink_entries_are_refused() {
for (path, ty) in [("../evil.txt", tar::EntryType::Regular), ("not-listed.txt", tar::EntryType::Regular), ("ok.txt", tar::EntryType::Symlink)] {
for (path, ty) in [
("../evil.txt", tar::EntryType::Regular),
("not-listed.txt", tar::EntryType::Regular),
("ok.txt", tar::EntryType::Symlink),
] {
let (d, m) = hostile(|tb| add(tb, path, b"data", ty));
let dest = d.path().join("dest");
assert!(extract(d.path(), &m, &dest, &|_, _| {}).is_err(), "{path} {ty:?}");
assert!(
extract(d.path(), &m, &dest, &|_, _| {}).is_err(),
"{path} {ty:?}"
);
assert!(!d.path().join("evil.txt").exists());
}
}
@@ -542,7 +788,10 @@ mod tests {
#[test]
fn content_that_does_not_match_the_manifest_is_refused() {
let (d, m) = hostile(|tb| add(tb, "ok.txt", b"DATA", tar::EntryType::Regular));
assert!(matches!(extract(d.path(), &m, &d.path().join("dest"), &|_, _| {}), Err(Error::HashMismatch { .. })));
assert!(matches!(
extract(d.path(), &m, &d.path().join("dest"), &|_, _| {}),
Err(Error::HashMismatch { .. })
));
let (d2, m2) = hostile(|tb| add(tb, "ok.txt", b"data", tar::EntryType::Regular));
extract(d2.path(), &m2, &d2.path().join("dest"), &|_, _| {}).unwrap();
assert_eq!(fs::read(d2.path().join("dest/ok.txt")).unwrap(), b"data");