mirror of
https://github.com/Corfirean/coa-server-manager.git
synced 2026-11-25 11:25:56 +00:00
coa-release: CLI for pack-base, pack-update (cumulative, ordered SQL), sign, verify
This commit is contained in:
1 parent
6a550353b3
commit
41121f116f
12 files changed
+360
-10
No files matched your search
@@ -16,7 +16,7 @@ fn main() {
|
||||
assert!(std::fs::symlink_metadata(fixture.join("Data")).unwrap().file_type().is_symlink(), "Data junction must be skipped by the packager");
|
||||
|
||||
let t = std::time::Instant::now();
|
||||
let m = build(&fixture, &out, &BuildOptions { kind: coa_core::manifest::Kind::Base, version: "0.1.0".into(), core_commit: None, built_at: chrono::Utc::now().to_rfc3339(), part_size: 256 * 1024 * 1024 }, &|s| eprintln!(" pack: {s}")).expect("build");
|
||||
let m = build(&fixture, &out, &BuildOptions { kind: coa_core::manifest::Kind::Base, version: "0.1.0".into(), core_commit: None, built_at: chrono::Utc::now().to_rfc3339(), part_size: 256 * 1024 * 1024, bots_commit: None, migrations: vec![] }, &|s| eprintln!(" pack: {s}")).expect("build");
|
||||
let arch = m.archive.as_ref().unwrap();
|
||||
println!("packaged {} files, {:.2} GB -> {} parts, {:.2} GB in {:?}", m.files.len(), arch.unpacked_size as f64 / 1e9, arch.parts.len(), arch.parts.iter().map(|p| p.size).sum::<u64>() as f64 / 1e9, t.elapsed());
|
||||
|
||||
|
||||
@@ -16,7 +16,7 @@ fn main() {
|
||||
std::fs::create_dir_all(f.parent().unwrap()).unwrap();
|
||||
std::fs::write(f, c.replace("\n", "\n")).unwrap();
|
||||
}
|
||||
build(&src, &out, &BuildOptions { kind: Kind::Update, version: a[1].clone(), core_commit: None, built_at: chrono::Utc::now().to_rfc3339(), part_size: 1 << 20 }, &|_| {}).unwrap();
|
||||
build(&src, &out, &BuildOptions { kind: Kind::Update, version: a[1].clone(), core_commit: None, built_at: chrono::Utc::now().to_rfc3339(), part_size: 1 << 20, bots_commit: None, migrations: vec![] }, &|_| {}).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();
|
||||
let sig = SigningKey::from_bytes(&seed).sign(&std::fs::read(out.join("manifest.json")).unwrap());
|
||||
|
||||
@@ -32,7 +32,7 @@ fn main() {
|
||||
put(&src, "Settings/worldserver.conf.template", "[worldserver]\nUpdateE2E.NewSetting = 7\n");
|
||||
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 }, &|_| {}).unwrap();
|
||||
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 });
|
||||
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());
|
||||
|
||||
@@ -350,7 +350,7 @@ mod tests {
|
||||
layout::testkit::fake_repack(&src);
|
||||
fs::create_dir_all(src.join("Settings")).unwrap();
|
||||
fs::write(src.join("Settings/database.json"), br#"{"rootPassword":"a","appPassword":"b"}"#).unwrap();
|
||||
let opts = package::BuildOptions { kind: manifest::Kind::Base, version: "0.1.0".into(), core_commit: None, built_at: "x".into(), part_size: 1 << 20 };
|
||||
let opts = package::BuildOptions { kind: manifest::Kind::Base, version: "0.1.0".into(), core_commit: None, built_at: "x".into(), part_size: 1 << 20, bots_commit: None, migrations: vec![] };
|
||||
package::build(&src, &pkg, &opts, &|_| {}).unwrap();
|
||||
let good = SigningKey::generate(&mut rand_core::OsRng);
|
||||
let evil = SigningKey::generate(&mut rand_core::OsRng);
|
||||
|
||||
@@ -18,6 +18,7 @@ pub mod migrations;
|
||||
pub mod package;
|
||||
pub mod ra;
|
||||
pub mod registry;
|
||||
pub mod release;
|
||||
pub mod update;
|
||||
pub mod signing;
|
||||
pub mod srp6;
|
||||
|
||||
@@ -148,6 +148,8 @@ pub struct BuildOptions {
|
||||
pub core_commit: Option<String>,
|
||||
pub built_at: String,
|
||||
pub part_size: u64,
|
||||
pub bots_commit: Option<String>,
|
||||
pub migrations: Vec<crate::manifest::Migration>,
|
||||
}
|
||||
|
||||
/// Package `src` into `out` (parts + manifest.json). Returns the manifest.
|
||||
@@ -212,11 +214,11 @@ pub fn build(src: &Path, out: &Path, opts: &BuildOptions, progress: &dyn Fn(&str
|
||||
kind: opts.kind,
|
||||
version: opts.version.clone(),
|
||||
core: Revision { commit: opts.core_commit.clone() },
|
||||
bots: None,
|
||||
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: Vec::new(),
|
||||
migrations: opts.migrations.clone(),
|
||||
archive: Some(ArchiveInfo { format: "tar.zst".into(), parts: split.parts.clone(), unpacked_size: unpacked }),
|
||||
};
|
||||
manifest.validate()?;
|
||||
@@ -327,7 +329,7 @@ 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 }
|
||||
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>)> {
|
||||
|
||||
@@ -0,0 +1,238 @@
|
||||
//! Release engineering: ordered SQL collection, cumulative update packages and a clean base tree.
|
||||
//! Used by the `coa-release` command line tool (CI and the maintainer's machine); never by the app at runtime.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
|
||||
use crate::error::{Error, Result};
|
||||
use crate::fsx;
|
||||
use crate::manifest::{Kind, Manifest, Migration, Revision};
|
||||
use crate::package::{self, BuildOptions};
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct SqlFile {
|
||||
pub db: String,
|
||||
pub id: String,
|
||||
/// Path relative to the checkout it came from (used only for ordering and display).
|
||||
pub origin: String,
|
||||
pub abs: PathBuf,
|
||||
pub sha256: String,
|
||||
}
|
||||
|
||||
fn sql_in(dir: &Path) -> Vec<PathBuf> {
|
||||
let mut v: Vec<PathBuf> = fs::read_dir(dir)
|
||||
.map(|rd| rd.flatten().map(|e| e.path()).filter(|p| p.extension().map(|e| e == "sql").unwrap_or(false)).collect())
|
||||
.unwrap_or_default();
|
||||
v.sort();
|
||||
v
|
||||
}
|
||||
|
||||
/// The order in which files were first added to the repository (a pending script may rely on a table a module
|
||||
/// created earlier). Files git does not know come last, in name order.
|
||||
fn introduction_rank(repo: &Path, pathspecs: &[&str]) -> std::collections::HashMap<String, usize> {
|
||||
let mut args = vec!["log", "--reverse", "--diff-filter=A", "--name-only", "--pretty=format:", "--"];
|
||||
args.extend_from_slice(pathspecs);
|
||||
let out = Command::new("git").current_dir(repo).args(&args).output();
|
||||
let mut rank = std::collections::HashMap::new();
|
||||
if let Ok(o) = out {
|
||||
for (i, line) in String::from_utf8_lossy(&o.stdout).lines().filter(|l| l.ends_with(".sql")).enumerate() {
|
||||
rank.entry(line.to_string()).or_insert(i);
|
||||
}
|
||||
}
|
||||
rank
|
||||
}
|
||||
|
||||
/// Every SQL script of a core checkout (released + pending updates, module base and update scripts), in application order.
|
||||
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 });
|
||||
Ok(())
|
||||
};
|
||||
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 {
|
||||
for f in sql_in(&core.join("data/sql/updates").join(d)) {
|
||||
let stem = f.file_stem().unwrap().to_string_lossy().into_owned();
|
||||
let rel = format!("data/sql/updates/{d}/{}", f.file_name().unwrap().to_string_lossy());
|
||||
push(kind, stem, f, rel)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Ok(rd) = fs::read_dir(core.join("modules")) {
|
||||
let mut mods: Vec<_> = rd.flatten().collect();
|
||||
mods.sort_by_key(|e| e.file_name());
|
||||
for m in mods {
|
||||
let name = m.file_name().to_string_lossy().into_owned();
|
||||
let mname = name.replace('-', "_");
|
||||
for kind in ["auth", "characters", "world"] {
|
||||
let base = m.path().join(format!("data/sql/db-{kind}"));
|
||||
for f in sql_in(&base.join("base")) {
|
||||
let stem = f.file_stem().unwrap().to_string_lossy().into_owned();
|
||||
let rel = format!("modules/{name}/data/sql/db-{kind}/base/{}", f.file_name().unwrap().to_string_lossy());
|
||||
push(kind, format!("mod_{mname}__base__{stem}"), f, rel)?;
|
||||
}
|
||||
for f in sql_in(&base) {
|
||||
let stem = f.file_stem().unwrap().to_string_lossy().into_owned();
|
||||
let rel = format!("modules/{name}/data/sql/db-{kind}/{}", f.file_name().unwrap().to_string_lossy());
|
||||
push(kind, format!("mod_{mname}__{stem}"), f, rel)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let rank = introduction_rank(core, &["data/sql/updates", "modules"]);
|
||||
out.sort_by_key(|f| rank.get(&f.origin).copied().unwrap_or(usize::MAX));
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// SQL a bots module checkout ships for the characters database (its `dist/sql`).
|
||||
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 });
|
||||
}
|
||||
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()
|
||||
}
|
||||
|
||||
pub struct UpdateParams<'a> {
|
||||
/// Directory laid out like the server folder that holds the release's files (binaries, dist configs, addon...).
|
||||
pub tree: &'a Path,
|
||||
/// Manifest of the base package this update is cumulative against.
|
||||
pub base_manifest: &'a Manifest,
|
||||
pub sql: &'a [SqlFile],
|
||||
pub out: &'a Path,
|
||||
pub version: String,
|
||||
pub core_commit: Option<String>,
|
||||
pub bots_commit: Option<String>,
|
||||
pub part_size: u64,
|
||||
}
|
||||
|
||||
fn walk(root: &Path, dir: &Path, out: &mut Vec<String>) -> Result<()> {
|
||||
for e in fs::read_dir(dir)? {
|
||||
let e = e?;
|
||||
let p = e.path();
|
||||
if e.file_type()?.is_dir() {
|
||||
walk(root, &p, out)?;
|
||||
} else {
|
||||
out.push(p.strip_prefix(root).unwrap().to_string_lossy().replace('\\', "/"));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Build a cumulative update: every file of `tree` that differs from the base, plus every SQL script. Unsigned.
|
||||
pub fn pack_update(p: &UpdateParams, progress: &dyn Fn(&str)) -> Result<Manifest> {
|
||||
let base: BTreeMap<String, &str> = p.base_manifest.files.iter().map(|f| (f.path.to_lowercase(), f.sha256.as_str())).collect();
|
||||
let work = p.out.with_file_name(format!("{}-staging", p.out.file_name().unwrap().to_string_lossy()));
|
||||
let _ = fs::remove_dir_all(&work);
|
||||
fs::create_dir_all(&work)?;
|
||||
|
||||
let mut rels = Vec::new();
|
||||
walk(p.tree, p.tree, &mut rels)?;
|
||||
let mut changed = 0;
|
||||
for rel in &rels {
|
||||
let src = fsx::safe_join(p.tree, rel)?;
|
||||
if base.get(&rel.to_lowercase()).map(|h| h.eq_ignore_ascii_case(&fsx::sha256_file(&src).unwrap_or_default())).unwrap_or(false) {
|
||||
continue;
|
||||
}
|
||||
let dst = fsx::safe_join(&work, rel)?;
|
||||
fs::create_dir_all(dst.parent().unwrap())?;
|
||||
fs::copy(&src, &dst)?;
|
||||
changed += 1;
|
||||
}
|
||||
progress(&format!("{changed} of {} files differ from the base", rels.len()));
|
||||
for f in p.sql {
|
||||
let dst = fsx::safe_join(&work, &format!("_migrations/{}/{}.sql", f.db, f.id))?;
|
||||
fs::create_dir_all(dst.parent().unwrap())?;
|
||||
fs::copy(&f.abs, dst)?;
|
||||
}
|
||||
let opts = BuildOptions {
|
||||
kind: Kind::Update,
|
||||
version: p.version.clone(),
|
||||
core_commit: p.core_commit.clone(),
|
||||
built_at: chrono::Utc::now().to_rfc3339(),
|
||||
part_size: p.part_size,
|
||||
bots_commit: p.bots_commit.clone(),
|
||||
migrations: to_migrations(p.sql),
|
||||
};
|
||||
let m = package::build(&work, p.out, &opts, &|s| progress(s))?;
|
||||
let _ = fs::remove_dir_all(&work);
|
||||
Ok(m)
|
||||
}
|
||||
|
||||
/// Sign `manifest.json` in `dir` with the Ed25519 seed (base64) and write `manifest.json.sig`.
|
||||
pub fn sign_manifest(dir: &Path, seed_b64: &str) -> Result<()> {
|
||||
use base64::{engine::general_purpose::STANDARD, Engine};
|
||||
use ed25519_dalek::{Signer, SigningKey};
|
||||
let seed: [u8; 32] = STANDARD.decode(seed_b64.trim()).map_err(|_| Error::Invalid("signing key is not base64".into()))?.try_into().map_err(|_| Error::Invalid("signing key has the wrong length".into()))?;
|
||||
let bytes = fs::read(dir.join("manifest.json"))?;
|
||||
let sig = SigningKey::from_bytes(&seed).sign(&bytes);
|
||||
fsx::atomic_write(&dir.join("manifest.json.sig"), format!("{}\n", STANDARD.encode(sig.to_bytes())).as_bytes())?;
|
||||
// never publish something the app would reject
|
||||
crate::signing::verify_embedded(&bytes, &fs::read_to_string(dir.join("manifest.json.sig"))?)
|
||||
.map_err(|_| Error::Invalid("The signature does not match the public key built into the app; wrong signing key.".into()))
|
||||
}
|
||||
|
||||
pub fn revision(commit: &str) -> Revision {
|
||||
Revision { commit: Some(commit.to_string()) }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn write(root: &Path, rel: &str, c: &str) {
|
||||
let p = root.join(rel);
|
||||
fs::create_dir_all(p.parent().unwrap()).unwrap();
|
||||
fs::write(p, c).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn collects_core_and_module_sql_with_module_base_first_and_stable_ids() {
|
||||
let d = tempfile::tempdir().unwrap();
|
||||
let c = d.path();
|
||||
write(c, "data/sql/updates/db_world/2026_01_01_00.sql", "SELECT 1;");
|
||||
write(c, "data/sql/updates/pending_db_world/rev_1.sql", "SELECT 2;");
|
||||
write(c, "data/sql/updates/db_characters/2026_01_02_00.sql", "SELECT 3;");
|
||||
write(c, "modules/mod-x/data/sql/db-world/base/01_a.sql", "SELECT 4;");
|
||||
write(c, "modules/mod-x/data/sql/db-world/2026_02_02_00_b.sql", "SELECT 5;");
|
||||
let v = collect_core_sql(c).unwrap();
|
||||
let ids: Vec<(&str, &str)> = v.iter().map(|f| (f.db.as_str(), f.id.as_str())).collect();
|
||||
assert!(ids.contains(&("world", "2026_01_01_00")) && ids.contains(&("world", "rev_1")) && ids.contains(&("characters", "2026_01_02_00")));
|
||||
assert!(ids.contains(&("world", "mod_mod_x__base__01_a")) && ids.contains(&("world", "mod_mod_x__2026_02_02_00_b")));
|
||||
// without git history, order falls back to a stable one (all "unknown" keep insertion order)
|
||||
let base_pos = ids.iter().position(|x| x.1 == "mod_mod_x__base__01_a").unwrap();
|
||||
let upd_pos = ids.iter().position(|x| x.1 == "mod_mod_x__2026_02_02_00_b").unwrap();
|
||||
assert!(base_pos < upd_pos, "a module's base script precedes its updates");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cumulative_update_contains_only_what_differs_from_the_base_plus_all_sql() {
|
||||
let d = tempfile::tempdir().unwrap();
|
||||
let (base_src, base_out, tree, upd_out, sqldir) = (d.path().join("bs"), d.path().join("bo"), d.path().join("tree"), d.path().join("uo"), d.path().join("sql"));
|
||||
write(&base_src, "Core/worldserver.exe", "v1");
|
||||
write(&base_src, "Core/authserver.exe", "same");
|
||||
let base = package::build(&base_src, &base_out, &BuildOptions { kind: Kind::Base, version: "1.0.0".into(), core_commit: None, built_at: "x".into(), part_size: 1 << 20, bots_commit: None, migrations: vec![] }, &|_| {}).unwrap();
|
||||
write(&tree, "Core/worldserver.exe", "v2");
|
||||
write(&tree, "Core/authserver.exe", "same");
|
||||
write(&tree, "Core/newlib.dll", "n");
|
||||
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 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"));
|
||||
assert!(!paths.contains(&"Core/authserver.exe"), "identical to the base: not shipped");
|
||||
assert!(paths.contains(&"_migrations/world/m1.sql"));
|
||||
assert_eq!(m.kind, Kind::Update);
|
||||
assert_eq!(m.migrations.len(), 1);
|
||||
assert_eq!(m.bots.as_ref().and_then(|b| b.commit.clone()), Some("b".repeat(40)));
|
||||
assert!(!upd_out.with_file_name("uo-staging").exists(), "staging removed");
|
||||
}
|
||||
}
|
||||
@@ -596,7 +596,7 @@ mod tests {
|
||||
if migrations {
|
||||
write(&src, "_migrations/world/m1.sql", b"SELECT 1;");
|
||||
}
|
||||
let mut m = build(&src, &pkg, &BuildOptions { kind: Kind::Update, version: "2.0.0".into(), core_commit: None, built_at: "x".into(), part_size: 1 << 20 }, &|_| {}).unwrap();
|
||||
let mut m = build(&src, &pkg, &BuildOptions { kind: Kind::Update, version: "2.0.0".into(), core_commit: None, built_at: "x".into(), part_size: 1 << 20, bots_commit: None, migrations: vec![] }, &|_| {}).unwrap();
|
||||
// Settings/* are merge-config by the packager; make the migration entry visible to the runner
|
||||
if migrations {
|
||||
m.migrations.push(crate::manifest::Migration { id: "m1".into(), db: "world".into(), sha256: fsx::sha256_bytes(b"SELECT 1;"), destructive: false });
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
[package]
|
||||
name = "coa-release"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
|
||||
[dependencies]
|
||||
coa-core = { path = "../coa-core" }
|
||||
serde_json = "1"
|
||||
chrono = { version = "0.4", default-features = false, features = ["clock", "std"] }
|
||||
@@ -0,0 +1,92 @@
|
||||
//! Release tooling for the CoA server packages. Used by CI and by the maintainer; never shipped to players.
|
||||
//!
|
||||
//! coa-release pack-base --tree DIR --out DIR --version X [--core-commit SHA] [--part-size BYTES]
|
||||
//! coa-release pack-update --tree DIR --base-manifest FILE --core DIR --out DIR --version X
|
||||
//! [--bots DIR] [--core-commit SHA] [--bots-commit SHA] [--part-size BYTES]
|
||||
//! coa-release sign --dir DIR (key: env COA_SIGNING_KEY, or ~/.coa-manager/signing/manifest-signing.key)
|
||||
//! coa-release verify --dir DIR (against the public key built into this tool)
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use coa_core::manifest::{Kind, Manifest};
|
||||
use coa_core::package::{build, BuildOptions, DEFAULT_PART_SIZE};
|
||||
use coa_core::release::{collect_bots_sql, collect_core_sql, pack_update, sign_manifest, UpdateParams};
|
||||
|
||||
fn args(rest: &[String]) -> HashMap<String, String> {
|
||||
let mut m = HashMap::new();
|
||||
let mut it = rest.iter();
|
||||
while let Some(k) = it.next() {
|
||||
if let (Some(k), Some(v)) = (k.strip_prefix("--"), it.next()) {
|
||||
m.insert(k.to_string(), v.clone());
|
||||
}
|
||||
}
|
||||
m
|
||||
}
|
||||
|
||||
fn need<'a>(a: &'a HashMap<String, String>, k: &str) -> Result<&'a String, String> {
|
||||
a.get(k).ok_or_else(|| format!("missing --{k}"))
|
||||
}
|
||||
|
||||
fn signing_key() -> Result<String, String> {
|
||||
if let Ok(k) = std::env::var("COA_SIGNING_KEY") {
|
||||
return Ok(k);
|
||||
}
|
||||
let home = std::env::var("USERPROFILE").or_else(|_| std::env::var("HOME")).map_err(|_| "no home folder".to_string())?;
|
||||
std::fs::read_to_string(PathBuf::from(home).join(".coa-manager/signing/manifest-signing.key")).map_err(|_| "no signing key: set COA_SIGNING_KEY".to_string())
|
||||
}
|
||||
|
||||
fn run() -> Result<(), String> {
|
||||
let all: Vec<String> = std::env::args().skip(1).collect();
|
||||
let (cmd, rest) = all.split_first().ok_or("usage: coa-release <pack-base|pack-update|sign|verify> ...")?;
|
||||
let a = args(rest);
|
||||
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() {
|
||||
"pack-base" => {
|
||||
let opts = BuildOptions { kind: Kind::Base, version: need(&a, "version")?.clone(), core_commit: a.get("core-commit").cloned(), built_at: chrono_now(), part_size: part, bots_commit: a.get("bots-commit").cloned(), migrations: vec![] };
|
||||
let m = build(&PathBuf::from(need(&a, "tree")?), &PathBuf::from(need(&a, "out")?), &opts, &|s| eprintln!("{s}")).map_err(e)?;
|
||||
println!("base {}: {} files, {} parts", m.version, m.files.len(), m.archive.as_ref().map(|x| x.parts.len()).unwrap_or(0));
|
||||
}
|
||||
"pack-update" => {
|
||||
let base: Manifest = Manifest::parse(&std::fs::read(need(&a, "base-manifest")?).map_err(|x| x.to_string())?).map_err(e)?;
|
||||
let mut sql = collect_core_sql(&PathBuf::from(need(&a, "core")?)).map_err(e)?;
|
||||
if let Some(b) = a.get("bots") {
|
||||
sql.extend(collect_bots_sql(&PathBuf::from(b)).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 },
|
||||
&|s| eprintln!("{s}"),
|
||||
)
|
||||
.map_err(e)?;
|
||||
println!("update {}: {} files, {} migrations", m.version, m.files.len(), m.migrations.len());
|
||||
}
|
||||
"sign" => {
|
||||
let dir = PathBuf::from(need(&a, "dir")?);
|
||||
sign_manifest(&dir, &signing_key()?).map_err(e)?;
|
||||
println!("signed {}", dir.join("manifest.json").display());
|
||||
}
|
||||
"verify" => {
|
||||
let dir = PathBuf::from(need(&a, "dir")?);
|
||||
let bytes = std::fs::read(dir.join("manifest.json")).map_err(|x| x.to_string())?;
|
||||
let sig = std::fs::read_to_string(dir.join("manifest.json.sig")).map_err(|x| x.to_string())?;
|
||||
coa_core::signing::verify_embedded(&bytes, &sig).map_err(e)?;
|
||||
Manifest::parse(&bytes).map_err(e)?;
|
||||
println!("signature and manifest OK");
|
||||
}
|
||||
other => return Err(format!("unknown command {other}")),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn chrono_now() -> String {
|
||||
chrono::Utc::now().to_rfc3339()
|
||||
}
|
||||
|
||||
fn main() {
|
||||
if let Err(e) = run() {
|
||||
eprintln!("error: {e}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user