Phase 0/1a: architecture audit and coa-core foundation (fsx, registry, manifest, logging, errors)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
ДмитрийandClaude Sonnet 5.5 committed 2026-09-30 06:59:11 +05:00
commit c39ff556a3
11 files changed
+2277

No files matched your search

+20
View File
@@ -0,0 +1,20 @@
[package]
name = "coa-core"
version.workspace = true
edition.workspace = true
[dependencies]
serde = { version = "1", features = ["derive"] }
serde_json = "1"
sha2 = "0.10"
hex = "0.4"
thiserror = "2"
uuid = { version = "1", features = ["v4", "serde"] }
chrono = { version = "0.4", default-features = false, features = ["clock", "serde", "std"] }
dunce = "1"
fs4 = "0.13"
tracing = "0.1"
tracing-subscriber = { version = "0.3", default-features = false, features = ["fmt", "std"] }
[dev-dependencies]
tempfile = "3"
+136
View File
@@ -0,0 +1,136 @@
use serde::Serialize;
pub type Result<T> = std::result::Result<T, Error>;
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("io: {0}")]
Io(#[from] std::io::Error),
#[error("json: {0}")]
Json(#[from] serde_json::Error),
#[error("path rejected: {0}")]
PathRejected(String),
#[error("not enough free space: need {needed} bytes, have {available}")]
InsufficientSpace { needed: u64, available: u64 },
#[error("hash mismatch for {path}: expected {expected}, got {actual}")]
HashMismatch { path: String, expected: String, actual: String },
#[error("invalid manifest: {0}")]
InvalidManifest(String),
#[error("installation {0} is not registered")]
UnknownInstallation(String),
#[error("{0}")]
Invalid(String),
}
/// Stable identifiers the UI maps to human messages. Raw exit codes never reach the user.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum ErrorCode {
DatabaseNotRunning,
PortInUse,
ServerFilesIncomplete,
WorldDbIncompatible,
WorldserverAlreadyRunning,
InvalidConfigValue,
DiskFull,
HashMismatch,
PathRejected,
Unknown,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum FixAction {
FixAutomatically,
OpenFolder,
ShowDetails,
ChooseAnotherFolder,
Retry,
}
#[derive(Debug, Clone, Serialize)]
pub struct Human {
pub code: ErrorCode,
pub title: &'static str,
pub message: &'static str,
pub actions: &'static [FixAction],
}
impl ErrorCode {
pub fn human(self) -> Human {
use FixAction::*;
let (title, message, actions): (&str, &str, &'static [FixAction]) = match self {
ErrorCode::DatabaseNotRunning => (
"Database isn't running",
"The server needs its database to start. Start the database first.",
&[FixAutomatically, ShowDetails],
),
ErrorCode::PortInUse => (
"Server port is already in use",
"Another program (or another server) is using a port this server needs.",
&[ShowDetails],
),
ErrorCode::ServerFilesIncomplete => (
"Server files are incomplete",
"Some server files are missing or damaged.",
&[FixAutomatically, OpenFolder, ShowDetails],
),
ErrorCode::WorldDbIncompatible => (
"World database is incompatible with this build",
"A database update is required before this server version can start.",
&[FixAutomatically, ShowDetails],
),
ErrorCode::WorldserverAlreadyRunning => (
"Another worldserver process is already running",
"Stop the other server before starting this one.",
&[ShowDetails],
),
ErrorCode::InvalidConfigValue => (
"Your server configuration contains an invalid value",
"Fix the highlighted setting and save again.",
&[OpenFolder, ShowDetails],
),
ErrorCode::DiskFull => (
"Not enough free disk space",
"Free up some space or choose another drive, then try again.",
&[ChooseAnotherFolder, Retry],
),
ErrorCode::HashMismatch => (
"A downloaded file is damaged",
"The file did not match its checksum and was not used.",
&[Retry, ShowDetails],
),
ErrorCode::PathRejected => (
"That location is not allowed",
"The requested file location is outside the server folder.",
&[ShowDetails],
),
ErrorCode::Unknown => ("Something went wrong", "See the technical details.", &[ShowDetails]),
};
Human { code: self, title, message, actions }
}
}
impl Error {
pub fn code(&self) -> ErrorCode {
match self {
Error::InsufficientSpace { .. } => ErrorCode::DiskFull,
Error::HashMismatch { .. } => ErrorCode::HashMismatch,
Error::PathRejected(_) => ErrorCode::PathRejected,
_ => ErrorCode::Unknown,
}
}
}
/// Error shape sent over Tauri IPC: human text plus the technical string (needed for GitHub issues).
#[derive(Debug, Serialize)]
pub struct UiError {
pub human: Human,
pub technical: String,
}
impl From<Error> for UiError {
fn from(e: Error) -> Self {
UiError { human: e.code().human(), technical: e.to_string() }
}
}
+281
View File
@@ -0,0 +1,281 @@
//! The only module allowed to mutate the filesystem. Every function validates its target first.
use std::fs::{self, File, OpenOptions};
use std::io::{Read, Write};
use std::path::{Component, Path, PathBuf};
use sha2::{Digest, Sha256};
use crate::error::{Error, Result};
/// Resolve `.` and `..` lexically without touching the filesystem.
pub fn normalize_lexical(path: &Path) -> PathBuf {
let mut out = PathBuf::new();
for component in path.components() {
match component {
Component::CurDir => {}
Component::ParentDir => {
if !out.pop() {
out.push("..");
}
}
other => out.push(other.as_os_str()),
}
}
out
}
fn key(path: &Path) -> Vec<String> {
path.components()
.map(|c| c.as_os_str().to_string_lossy().to_lowercase())
.collect()
}
/// Case-insensitive component-wise prefix test (Windows semantics).
pub fn starts_with_ci(path: &Path, prefix: &Path) -> bool {
let (p, q) = (key(path), key(prefix));
p.len() >= q.len() && p[..q.len()] == q[..]
}
/// Canonicalize the deepest existing ancestor, then re-append the not-yet-existing tail.
/// Detects symlink / junction escapes for paths that do not exist yet.
pub fn canonicalize_lenient(path: &Path) -> Result<PathBuf> {
let path = normalize_lexical(path);
let mut tail: Vec<std::ffi::OsString> = Vec::new();
let mut cursor = path.as_path();
loop {
match dunce::canonicalize(cursor) {
Ok(mut base) => {
for part in tail.iter().rev() {
base.push(part);
}
return Ok(base);
}
Err(_) => match (cursor.file_name(), cursor.parent()) {
(Some(name), Some(parent)) => {
tail.push(name.to_os_string());
cursor = parent;
}
_ => return Err(Error::PathRejected(format!("cannot resolve {}", path.display()))),
},
}
}
}
/// Validate that `candidate` (absolute, or relative to `root`) resolves inside `root`,
/// following existing symlinks/junctions. Returns the resolved path.
pub fn ensure_within(root: &Path, candidate: &Path) -> Result<PathBuf> {
let root = canonicalize_lenient(root)?;
let joined = if candidate.is_absolute() { candidate.to_path_buf() } else { root.join(candidate) };
let resolved = canonicalize_lenient(&joined)?;
if starts_with_ci(&resolved, &root) {
Ok(resolved)
} else {
Err(Error::PathRejected(format!("{} is outside {}", resolved.display(), root.display())))
}
}
/// Join an untrusted relative path (from a manifest / archive) onto `root`.
/// Rejects absolute paths, drive prefixes, `..`, empty components, NTFS streams and reserved device names.
pub fn safe_join(root: &Path, rel: &str) -> Result<PathBuf> {
let bad = |why: &str| Error::PathRejected(format!("{rel:?}: {why}"));
if rel.is_empty() {
return Err(bad("empty"));
}
if rel.contains(':') {
return Err(bad("drive or stream marker"));
}
let normalized = rel.replace('\\', "/");
if normalized.starts_with('/') {
return Err(bad("absolute"));
}
let mut out = root.to_path_buf();
for part in normalized.split('/') {
match part {
"" | "." => return Err(bad("empty or dot component")),
".." => return Err(bad("parent traversal")),
p => {
if p.ends_with('.') || p.ends_with(' ') {
return Err(bad("trailing dot or space"));
}
let stem = p.split('.').next().unwrap_or("").to_ascii_uppercase();
const RESERVED: [&str; 22] = [
"CON", "PRN", "AUX", "NUL", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8",
"COM9", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9",
];
if RESERVED.contains(&stem.as_str()) {
return Err(bad("reserved device name"));
}
out.push(p);
}
}
}
Ok(out)
}
/// Write `bytes` to `path` so readers see either the old or the new content, never a partial file.
pub fn atomic_write(path: &Path, bytes: &[u8]) -> Result<()> {
let parent = path.parent().ok_or_else(|| Error::PathRejected("no parent directory".into()))?;
fs::create_dir_all(parent)?;
let tmp = parent.join(format!(
".{}.{}.tmp",
path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(),
std::process::id()
));
let write = || -> std::io::Result<()> {
let mut f = OpenOptions::new().write(true).create_new(true).open(&tmp)?;
f.write_all(bytes)?;
f.sync_all()?;
Ok(())
};
if let Err(e) = write() {
let _ = fs::remove_file(&tmp);
return Err(e.into());
}
if let Err(e) = fs::rename(&tmp, path) {
let _ = fs::remove_file(&tmp);
return Err(e.into());
}
Ok(())
}
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');
atomic_write(path, &bytes)
}
pub fn read_json<T: serde::de::DeserializeOwned>(path: &Path) -> Result<T> {
let bytes = fs::read(path)?;
let bytes = bytes.strip_prefix(&[0xEF, 0xBB, 0xBF][..]).unwrap_or(&bytes);
Ok(serde_json::from_slice(bytes)?)
}
pub fn sha256_file(path: &Path) -> Result<String> {
let mut file = File::open(path)?;
let mut hasher = Sha256::new();
let mut buf = vec![0u8; 1 << 20];
loop {
let n = file.read(&mut buf)?;
if n == 0 {
break;
}
hasher.update(&buf[..n]);
}
Ok(hex::encode(hasher.finalize()))
}
pub fn sha256_bytes(bytes: &[u8]) -> String {
hex::encode(Sha256::digest(bytes))
}
/// Free bytes on the volume that holds `path` (or its nearest existing ancestor).
pub fn free_space(path: &Path) -> Result<u64> {
let mut cursor = Some(path);
while let Some(p) = cursor {
if p.exists() {
return Ok(fs4::available_space(p)?);
}
cursor = p.parent();
}
Err(Error::PathRejected(format!("no existing ancestor for {}", path.display())))
}
/// Fail before writing if the volume cannot hold `needed` bytes plus a safety margin.
pub fn require_space(path: &Path, needed: u64) -> Result<()> {
const MARGIN: u64 = 256 * 1024 * 1024;
let available = free_space(path)?;
if available < needed.saturating_add(MARGIN) {
return Err(Error::InsufficientSpace { needed: needed.saturating_add(MARGIN), available });
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn safe_join_accepts_normal_and_rejects_traversal() {
let root = Path::new("C:/srv");
assert!(safe_join(root, "Core/worldserver.exe").is_ok());
assert!(safe_join(root, "Core\\configs\\a.conf").is_ok());
for bad in ["", "../x", "a/../../x", "/abs", "C:/x", "a/./b", "a//b", "a/CON", "a/nul.txt", "x.exe:zone", "a/b.", "a/b "] {
assert!(safe_join(root, bad).is_err(), "should reject {bad:?}");
}
}
#[test]
fn ensure_within_blocks_escape() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path().join("srv");
fs::create_dir_all(&root).unwrap();
assert!(ensure_within(&root, Path::new("Core/new/file.txt")).is_ok());
assert!(ensure_within(&root, Path::new("../evil")).is_err());
assert!(ensure_within(&root, &dir.path().join("other")).is_err());
// case-insensitive root match (Windows)
let upper = PathBuf::from(root.to_string_lossy().to_uppercase()).join("a");
if cfg!(windows) {
assert!(ensure_within(&root, &upper).is_ok());
}
}
#[test]
fn ensure_within_blocks_junction_escape() {
if !cfg!(windows) {
return;
}
let dir = tempfile::tempdir().unwrap();
let root = dir.path().join("srv");
let outside = dir.path().join("outside");
fs::create_dir_all(&root).unwrap();
fs::create_dir_all(&outside).unwrap();
let link = root.join("link");
// A directory junction needs no privileges (unlike symlinks).
let status = std::process::Command::new("cmd")
.args(["/C", "mklink", "/J"])
.arg(&link)
.arg(&outside)
.output()
.unwrap();
if !status.status.success() {
return;
}
assert!(ensure_within(&root, &link.join("file.txt")).is_err());
}
#[test]
fn atomic_write_replaces_and_leaves_no_temp() {
let dir = tempfile::tempdir().unwrap();
let p = dir.path().join("a.json");
atomic_write(&p, b"one").unwrap();
atomic_write(&p, b"two").unwrap();
assert_eq!(fs::read(&p).unwrap(), b"two");
let leftovers: Vec<_> = fs::read_dir(dir.path()).unwrap().collect();
assert_eq!(leftovers.len(), 1);
}
#[test]
fn sha256_matches_known_vector() {
assert_eq!(sha256_bytes(b"abc"), "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad");
let dir = tempfile::tempdir().unwrap();
let p = dir.path().join("f");
fs::write(&p, b"abc").unwrap();
assert_eq!(sha256_file(&p).unwrap(), sha256_bytes(b"abc"));
}
#[test]
fn read_json_tolerates_bom() {
let dir = tempfile::tempdir().unwrap();
let p = dir.path().join("b.json");
fs::write(&p, b"\xEF\xBB\xBF{\"a\":1}").unwrap();
let v: serde_json::Value = read_json(&p).unwrap();
assert_eq!(v["a"], 1);
}
#[test]
fn require_space_rejects_absurd_request() {
let dir = tempfile::tempdir().unwrap();
assert!(matches!(require_space(dir.path(), u64::MAX / 2), Err(Error::InsufficientSpace { .. })));
}
}
+9
View File
@@ -0,0 +1,9 @@
pub mod error;
pub mod fsx;
pub mod logging;
pub mod manifest;
pub mod registry;
pub use error::{Error, ErrorCode, Result};
pub const MANAGER_VERSION: &str = env!("CARGO_PKG_VERSION");
+126
View File
@@ -0,0 +1,126 @@
//! Size-bounded rotating log file: `manager.log`, `manager.log.1` .. `manager.log.N`.
use std::fs::{self, File, OpenOptions};
use std::io::{self, Write};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
pub struct RotatingWriter {
path: PathBuf,
max_bytes: u64,
keep: usize,
file: Option<File>,
written: u64,
}
impl RotatingWriter {
pub fn open(path: impl Into<PathBuf>, max_bytes: u64, keep: usize) -> io::Result<Self> {
let path = path.into();
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)?;
}
let file = OpenOptions::new().create(true).append(true).open(&path)?;
let written = file.metadata()?.len();
Ok(Self { path, max_bytes, keep, file: Some(file), written })
}
fn numbered(&self, n: usize) -> PathBuf {
let mut name = self.path.file_name().unwrap_or_default().to_os_string();
name.push(format!(".{n}"));
self.path.with_file_name(name)
}
fn rotate(&mut self) -> io::Result<()> {
self.file = None;
let _ = fs::remove_file(self.numbered(self.keep));
for n in (1..self.keep).rev() {
let from = self.numbered(n);
if from.exists() {
let _ = fs::rename(&from, self.numbered(n + 1));
}
}
if self.keep > 0 {
let _ = fs::rename(&self.path, self.numbered(1));
} else {
let _ = fs::remove_file(&self.path);
}
self.file = Some(OpenOptions::new().create(true).append(true).open(&self.path)?);
self.written = 0;
Ok(())
}
}
impl Write for RotatingWriter {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
if self.written > 0 && self.written + buf.len() as u64 > self.max_bytes {
self.rotate()?;
}
let file = self.file.as_mut().ok_or_else(|| io::Error::other("log closed"))?;
let n = file.write(buf)?;
self.written += n as u64;
Ok(n)
}
fn flush(&mut self) -> io::Result<()> {
match self.file.as_mut() {
Some(f) => f.flush(),
None => Ok(()),
}
}
}
#[derive(Clone)]
pub struct SharedWriter(Arc<Mutex<RotatingWriter>>);
impl SharedWriter {
pub fn new(w: RotatingWriter) -> Self {
Self(Arc::new(Mutex::new(w)))
}
}
impl Write for SharedWriter {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.0.lock().map_err(|_| io::Error::other("log poisoned"))?.write(buf)
}
fn flush(&mut self) -> io::Result<()> {
self.0.lock().map_err(|_| io::Error::other("log poisoned"))?.flush()
}
}
impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for SharedWriter {
type Writer = SharedWriter;
fn make_writer(&'a self) -> Self::Writer {
self.clone()
}
}
/// Install the global tracing subscriber writing to a rotated file (2 MiB x 5).
pub fn init(log_path: &Path) -> io::Result<()> {
let writer = SharedWriter::new(RotatingWriter::open(log_path, 2 * 1024 * 1024, 5)?);
let _ = tracing_subscriber::fmt().with_writer(writer).with_ansi(false).with_max_level(tracing::Level::INFO).try_init();
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn rotates_and_bounds_total_size() {
let dir = tempfile::tempdir().unwrap();
let p = dir.path().join("m.log");
let mut w = RotatingWriter::open(&p, 100, 2).unwrap();
for _ in 0..50 {
w.write_all(&[b'x'; 30]).unwrap();
}
w.flush().unwrap();
let mut names: Vec<_> =
fs::read_dir(dir.path()).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect();
names.sort();
assert_eq!(names, ["m.log", "m.log.1", "m.log.2"]);
let total: u64 = fs::read_dir(dir.path()).unwrap().map(|e| e.unwrap().metadata().unwrap().len()).sum();
assert!(total <= 3 * 100);
}
}
+238
View File
@@ -0,0 +1,238 @@
//! Release manifest (`manifest.json`) shipped with every base/update/bots package.
use std::collections::HashSet;
use std::path::Path;
use serde::{Deserialize, Serialize};
use crate::error::{Error, Result};
use crate::fsx;
pub const SCHEMA: u32 = 1;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum Kind {
Base,
Update,
Bots,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum Owner {
Core,
Bots,
Manager,
User,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum ReplacePolicy {
Replace,
ReplaceIfPristine,
MergeConfig,
CreateIfMissing,
NeverTouch,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FileEntry {
pub path: String,
pub sha256: String,
pub size: u64,
pub owner: Owner,
pub policy: ReplacePolicy,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Migration {
pub id: String,
pub db: String,
pub sha256: String,
#[serde(default)]
pub destructive: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Revision {
pub commit: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Signature {
pub alg: String,
pub key_id: String,
pub sig: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Manifest {
pub schema: u32,
pub kind: Kind,
pub version: String,
pub core: Revision,
#[serde(default)]
pub bots: Option<Revision>,
pub built_at: String,
pub min_manager_version: String,
#[serde(default)]
pub files: Vec<FileEntry>,
#[serde(default)]
pub migrations: Vec<Migration>,
#[serde(default)]
pub signature: Option<Signature>,
}
fn is_sha256(s: &str) -> bool {
s.len() == 64 && s.bytes().all(|b| b.is_ascii_hexdigit())
}
fn is_commit(s: &str) -> bool {
s.len() == 40 && s.bytes().all(|b| b.is_ascii_hexdigit())
}
/// Parse "1.2.3" leniently into a comparable tuple.
pub fn parse_version(v: &str) -> Option<(u64, u64, u64)> {
let core = v.trim_start_matches('v').split(['-', '+']).next()?;
let mut it = core.split('.');
let major = it.next()?.parse().ok()?;
let minor = it.next().unwrap_or("0").parse().ok()?;
let patch = it.next().unwrap_or("0").parse().ok()?;
if it.next().is_some() {
return None;
}
Some((major, minor, patch))
}
impl Manifest {
pub fn parse(bytes: &[u8]) -> Result<Self> {
let m: Manifest = serde_json::from_slice(bytes).map_err(|e| Error::InvalidManifest(e.to_string()))?;
m.validate()?;
Ok(m)
}
pub fn validate(&self) -> Result<()> {
let bad = |s: String| Err(Error::InvalidManifest(s));
if self.schema != SCHEMA {
return bad(format!("unsupported schema {}", self.schema));
}
if parse_version(&self.version).is_none() {
return bad(format!("bad version {:?}", self.version));
}
if parse_version(&self.min_manager_version).is_none() {
return bad(format!("bad minManagerVersion {:?}", self.min_manager_version));
}
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) {
return bad(format!("{label} commit must be a full 40-hex SHA, got {c:?}"));
}
}
}
let scratch = Path::new("root");
let mut seen = HashSet::new();
for f in &self.files {
fsx::safe_join(scratch, &f.path).map_err(|e| Error::InvalidManifest(e.to_string()))?;
if !is_sha256(&f.sha256) {
return bad(format!("{}: bad sha256", f.path));
}
if !seen.insert(f.path.replace('\\', "/").to_lowercase()) {
return bad(format!("{}: duplicate path", f.path));
}
}
let mut ids = HashSet::new();
for m in &self.migrations {
if m.id.is_empty() || !is_sha256(&m.sha256) || !ids.insert((m.db.clone(), m.id.clone())) {
return bad(format!("migration {:?} invalid or duplicated", m.id));
}
}
Ok(())
}
/// True if this Manager build may apply the manifest.
pub fn compatible_with_manager(&self, manager_version: &str) -> bool {
match (parse_version(manager_version), parse_version(&self.min_manager_version)) {
(Some(have), Some(need)) => have >= need,
_ => false,
}
}
pub fn total_size(&self) -> u64 {
self.files.iter().map(|f| f.size).sum()
}
}
/// Verify `path` against the entry; never trusts size alone.
pub fn verify_file(path: &Path, entry: &FileEntry) -> Result<()> {
let len = std::fs::metadata(path)?.len();
if len != entry.size {
return Err(Error::HashMismatch {
path: entry.path.clone(),
expected: format!("{} bytes", entry.size),
actual: format!("{len} bytes"),
});
}
let actual = fsx::sha256_file(path)?;
if !actual.eq_ignore_ascii_case(&entry.sha256) {
return Err(Error::HashMismatch { path: entry.path.clone(), expected: entry.sha256.clone(), actual });
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
fn sample(files: &str) -> String {
format!(
r#"{{"schema":1,"kind":"update","version":"0.4.1","core":{{"commit":"{c}"}},"bots":{{"commit":null}},
"builtAt":"2026-09-30T00:00:00Z","minManagerVersion":"0.1.0","files":[{files}],"migrations":[]}}"#,
c = "a".repeat(40)
)
}
fn file(path: &str, sha: &str) -> String {
format!(r#"{{"path":"{path}","sha256":"{sha}","size":3,"owner":"core","policy":"replace"}}"#)
}
#[test]
fn parses_valid_manifest() {
let m = Manifest::parse(sample(&file("Core/worldserver.exe", &"b".repeat(64))).as_bytes()).unwrap();
assert_eq!(m.files.len(), 1);
assert!(m.compatible_with_manager("0.1.0"));
assert!(!m.compatible_with_manager("0.0.9"));
}
#[test]
fn rejects_traversal_bad_hash_duplicates_and_short_commit() {
let ok = "b".repeat(64);
assert!(Manifest::parse(sample(&file("../x", &ok)).as_bytes()).is_err());
assert!(Manifest::parse(sample(&file("a/b", "zz")).as_bytes()).is_err());
let dup = format!("{},{}", file("A/b", &ok), file("a/B", &ok));
assert!(Manifest::parse(sample(&dup).as_bytes()).is_err());
let s = sample("").replace(&"a".repeat(40), "master");
assert!(Manifest::parse(s.as_bytes()).is_err());
}
#[test]
fn verify_file_detects_corruption() {
let dir = tempfile::tempdir().unwrap();
let p = dir.path().join("f");
std::fs::write(&p, b"abc").unwrap();
let entry = FileEntry {
path: "f".into(),
sha256: fsx::sha256_bytes(b"abc"),
size: 3,
owner: Owner::Core,
policy: ReplacePolicy::Replace,
};
verify_file(&p, &entry).unwrap();
std::fs::write(&p, b"abd").unwrap();
assert!(matches!(verify_file(&p, &entry), Err(Error::HashMismatch { .. })));
std::fs::write(&p, b"abcd").unwrap();
assert!(verify_file(&p, &entry).is_err());
}
}
+272
View File
@@ -0,0 +1,272 @@
//! Installation registry and per-installation metadata directory (`<server>.manager`).
//!
//! Registering or importing an installation writes only inside the metadata directory and the registry file.
//! The server folder itself is never written to.
use std::collections::BTreeMap;
use std::fs;
use std::path::{Path, PathBuf};
use serde::{Deserialize, Serialize};
use crate::error::{Error, Result};
use crate::fsx;
pub const META_SCHEMA: u32 = 1;
pub const LAYOUT_REPACK_V1: &str = "repack-v1";
const META_SUBDIRS: [&str; 6] = ["manifests", "backups", "migrations", "logs", "cache", "staging"];
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum InstallKind {
New,
Imported,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct VersionInfo {
pub version: Option<String>,
pub commit: Option<String>,
}
/// Non-secret database facts only. Credentials never live in install.json.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct DbInfo {
pub port: Option<u16>,
pub schemas: Vec<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct InstallMeta {
pub schema: u32,
pub id: String,
pub kind: InstallKind,
pub server_path: String,
pub layout: String,
pub created_at: String,
pub manager_version: String,
#[serde(default)]
pub core: VersionInfo,
#[serde(default)]
pub bots: VersionInfo,
#[serde(default)]
pub database: DbInfo,
#[serde(default)]
pub client_path: Option<String>,
/// Files that existed before the Manager touched the installation (path -> sha256, when known).
#[serde(default)]
pub original_hashes: BTreeMap<String, String>,
/// Files the Manager itself created or later modified.
#[serde(default)]
pub managed_files: Vec<String>,
}
impl InstallMeta {
pub fn new(kind: InstallKind, server_path: &Path) -> Self {
Self {
schema: META_SCHEMA,
id: uuid::Uuid::new_v4().to_string(),
kind,
server_path: server_path.to_string_lossy().into_owned(),
layout: LAYOUT_REPACK_V1.into(),
created_at: chrono::Utc::now().to_rfc3339(),
manager_version: crate::MANAGER_VERSION.into(),
core: VersionInfo::default(),
bots: VersionInfo::default(),
database: DbInfo::default(),
client_path: None,
original_hashes: BTreeMap::new(),
managed_files: Vec::new(),
}
}
}
/// `D:\CoA-Repack` -> `D:\CoA-Repack.manager`.
pub fn metadata_dir_for(server: &Path) -> Result<PathBuf> {
let name = server
.file_name()
.ok_or_else(|| Error::Invalid("a drive root cannot be a server folder".into()))?
.to_string_lossy()
.into_owned();
Ok(server.with_file_name(format!("{name}.manager")))
}
pub struct MetaDir {
pub root: PathBuf,
}
impl MetaDir {
pub fn install_json(&self) -> PathBuf {
self.root.join("install.json")
}
pub fn log_file(&self) -> PathBuf {
self.root.join("logs").join("manager.log")
}
/// Create the metadata directory for `server` (which must already exist) and write `install.json`.
pub fn create(server: &Path, meta: &InstallMeta) -> Result<MetaDir> {
if !server.is_dir() {
return Err(Error::Invalid(format!("{} is not a folder", server.display())));
}
let server_abs = fsx::canonicalize_lenient(server)?;
let root = metadata_dir_for(&server_abs)?;
if fsx::starts_with_ci(&root, &server_abs) {
return Err(Error::PathRejected("metadata folder would be inside the server folder".into()));
}
fs::create_dir_all(&root)?;
for sub in META_SUBDIRS {
fs::create_dir_all(root.join(sub))?;
}
let dir = MetaDir { root };
fsx::atomic_write_json(&dir.install_json(), meta)?;
Ok(dir)
}
pub fn open(root: &Path) -> Result<(MetaDir, InstallMeta)> {
let meta: InstallMeta = fsx::read_json(&root.join("install.json"))?;
Ok((MetaDir { root: root.to_path_buf() }, meta))
}
}
#[derive(Debug, Default, Serialize, Deserialize)]
struct RegistryFile {
installs: BTreeMap<String, String>,
}
/// `%LOCALAPPDATA%\CoAServerManager\installs.json`: id -> server path. Removing an entry never touches files.
pub struct Registry {
file: PathBuf,
}
impl Registry {
pub fn at(file: impl Into<PathBuf>) -> Self {
Self { file: file.into() }
}
fn load(&self) -> Result<RegistryFile> {
if !self.file.exists() {
return Ok(RegistryFile::default());
}
fsx::read_json(&self.file)
}
pub fn list(&self) -> Result<Vec<(String, PathBuf)>> {
Ok(self.load()?.installs.into_iter().map(|(id, p)| (id, PathBuf::from(p))).collect())
}
pub fn find_by_path(&self, server: &Path) -> Result<Option<String>> {
let target = fsx::canonicalize_lenient(server)?;
for (id, p) in self.list()? {
if fsx::canonicalize_lenient(&p).map(|c| fsx::starts_with_ci(&c, &target) && fsx::starts_with_ci(&target, &c)).unwrap_or(false) {
return Ok(Some(id));
}
}
Ok(None)
}
/// Register an installation. Rejects duplicates and nested/overlapping folders.
pub fn register(&self, id: &str, server: &Path) -> Result<()> {
let target = fsx::canonicalize_lenient(server)?;
let mut file = self.load()?;
for (other_id, other) in &file.installs {
let other = fsx::canonicalize_lenient(Path::new(other)).unwrap_or_else(|_| PathBuf::from(other));
if other_id == id {
continue;
}
if fsx::starts_with_ci(&target, &other) || fsx::starts_with_ci(&other, &target) {
return Err(Error::Invalid(format!(
"{} overlaps already registered installation {}",
target.display(),
other.display()
)));
}
}
file.installs.insert(id.to_string(), target.to_string_lossy().into_owned());
fsx::atomic_write_json(&self.file, &file)
}
pub fn unregister(&self, id: &str) -> Result<()> {
let mut file = self.load()?;
if file.installs.remove(id).is_none() {
return Err(Error::UnknownInstallation(id.into()));
}
fsx::atomic_write_json(&self.file, &file)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn metadata_dir_is_a_sibling_and_server_folder_is_untouched() {
let dir = tempfile::tempdir().unwrap();
let server = dir.path().join("CoA-Repack");
fs::create_dir_all(server.join("Core")).unwrap();
fs::write(server.join("Core/worldserver.exe"), b"x").unwrap();
let before = snapshot(&server);
let meta = InstallMeta::new(InstallKind::Imported, &server);
let md = MetaDir::create(&server, &meta).unwrap();
assert_eq!(md.root.file_name().unwrap(), "CoA-Repack.manager");
assert!(md.install_json().exists());
for sub in META_SUBDIRS {
assert!(md.root.join(sub).is_dir());
}
assert_eq!(before, snapshot(&server), "import must not modify the server folder");
let (_, loaded) = MetaDir::open(&md.root).unwrap();
assert_eq!(loaded.id, meta.id);
assert_eq!(loaded.kind, InstallKind::Imported);
}
fn snapshot(root: &Path) -> Vec<(String, u64)> {
let mut out = Vec::new();
fn walk(dir: &Path, root: &Path, out: &mut Vec<(String, u64)>) {
for e in fs::read_dir(dir).unwrap() {
let e = e.unwrap();
let md = e.metadata().unwrap();
let rel = e.path().strip_prefix(root).unwrap().to_string_lossy().into_owned();
out.push((rel, if md.is_dir() { 0 } else { md.len() }));
if md.is_dir() {
walk(&e.path(), root, out);
}
}
}
walk(root, root, &mut out);
out.sort();
out
}
#[test]
fn registry_rejects_duplicates_and_nesting_but_allows_reregister_same_id() {
let dir = tempfile::tempdir().unwrap();
let reg = Registry::at(dir.path().join("reg/installs.json"));
let a = dir.path().join("a");
let inner = a.join("inner");
let b = dir.path().join("b");
for p in [&a, &inner, &b] {
fs::create_dir_all(p).unwrap();
}
reg.register("1", &a).unwrap();
reg.register("1", &a).unwrap();
assert!(reg.register("2", &a).is_err(), "same folder");
assert!(reg.register("2", &inner).is_err(), "nested inside existing");
assert!(reg.register("3", dir.path()).is_err(), "contains existing");
reg.register("2", &b).unwrap();
assert_eq!(reg.list().unwrap().len(), 2);
assert_eq!(reg.find_by_path(&a).unwrap().as_deref(), Some("1"));
reg.unregister("1").unwrap();
assert!(a.exists(), "unregister never deletes files");
assert!(matches!(reg.unregister("1"), Err(Error::UnknownInstallation(_))));
}
#[test]
fn drive_root_and_missing_folder_are_rejected() {
let meta = InstallMeta::new(InstallKind::New, Path::new("C:/nope"));
assert!(MetaDir::create(Path::new("C:/definitely/missing/folder"), &meta).is_err());
assert!(metadata_dir_for(Path::new("C:/")).is_err());
}
}