diff --git a/.github/workflows/launcher.yml b/.github/workflows/launcher.yml index c902acf32..70a3d4070 100644 --- a/.github/workflows/launcher.yml +++ b/.github/workflows/launcher.yml @@ -221,7 +221,10 @@ jobs: release: needs: [decide, build] runs-on: ubuntu-latest - timeout-minutes: 10 + timeout-minutes: 15 + # The signing key is a secret of the `release` environment (docs/security.md), which only main's real releases + # enter; a dry run signs with a throwaway key. + environment: ${{ needs.decide.outputs.dry_run != 'true' && 'release' || '' }} permissions: contents: write steps: @@ -239,6 +242,13 @@ jobs: with: path: dist merge-multiple: true + - name: Sign the checksums (SHA256SUMS, SHA256SUMS.sig), checked as the launcher checks them + env: + RELEASE_SIGNING_KEY: ${{ secrets.RELEASE_SIGNING_KEY }} + RELEASE_SIGNING_KEY_NEXT: ${{ secrets.RELEASE_SIGNING_KEY_NEXT }} + TAG: ${{ needs.decide.outputs.tag }} + EPHEMERAL: ${{ needs.decide.outputs.dry_run == 'true' && 'yes' || '' }} + run: cargo run --locked --quiet -p horizon-release-sign -- sign --tag "$TAG" ${EPHEMERAL:+--ephemeral} dist/horizon-launcher-* # Never marked latest: Horizon's own releases stay the repository's latest. - name: Publish ${{ needs.decide.outputs.tag }} if: needs.decide.outputs.dry_run != 'true' @@ -246,8 +256,9 @@ jobs: GH_TOKEN: ${{ github.token }} TAG: ${{ needs.decide.outputs.tag }} run: | + signature=(); [[ -f dist/SHA256SUMS.sig ]] && signature=(dist/SHA256SUMS.sig) gh release create "$TAG" --target "${{ needs.decide.outputs.head }}" --title "$(cat notes/title.txt)" \ - --notes-file notes/body.md --latest=false dist/horizon-launcher-* + --notes-file notes/body.md --latest=false dist/horizon-launcher-* dist/SHA256SUMS "${signature[@]}" - name: Dry run, the release that would be published if: needs.decide.outputs.dry_run == 'true' run: | diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index bd916514b..b30fa6663 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -220,7 +220,10 @@ jobs: publish: needs: [decide, build] runs-on: ubuntu-latest - timeout-minutes: 10 + timeout-minutes: 15 + # The signing key is a secret of the `release` environment (docs/security.md), which only main's real releases + # enter; a dry run signs with a throwaway key. + environment: ${{ needs.decide.outputs.dry_run != 'true' && 'release' || '' }} permissions: contents: write steps: @@ -238,15 +241,26 @@ jobs: with: path: dist merge-multiple: true + - name: Sign the checksums (SHA256SUMS, SHA256SUMS.sig), checked as the launcher checks them + env: + RELEASE_SIGNING_KEY: ${{ secrets.RELEASE_SIGNING_KEY }} + RELEASE_SIGNING_KEY_NEXT: ${{ secrets.RELEASE_SIGNING_KEY_NEXT }} + TAG: ${{ needs.decide.outputs.tag }} + EPHEMERAL: ${{ needs.decide.outputs.dry_run == 'true' && 'yes' || '' }} + run: | + cargo run --locked --quiet -p horizon-release-sign -- sign --tag "$TAG" ${EPHEMERAL:+--ephemeral} \ + dist/horizon-linux-x86_64.tar.gz dist/horizon-windows-x64.zip dist/horizon-macos-arm64.zip \ + dist/horizon-server-linux-x86_64.tar.gz - name: Publish ${{ needs.decide.outputs.tag }} if: needs.decide.outputs.dry_run != 'true' env: GH_TOKEN: ${{ github.token }} TAG: ${{ needs.decide.outputs.tag }} run: | + signature=(); [[ -f dist/SHA256SUMS.sig ]] && signature=(dist/SHA256SUMS.sig) gh release create "$TAG" --target "${{ needs.decide.outputs.head }}" --title "$(cat notes/title.txt)" \ --notes-file notes/body.md --latest dist/horizon-linux-x86_64.tar.gz dist/horizon-windows-x64.zip \ - dist/horizon-macos-arm64.zip dist/horizon-server-linux-x86_64.tar.gz + dist/horizon-macos-arm64.zip dist/horizon-server-linux-x86_64.tar.gz dist/SHA256SUMS "${signature[@]}" - name: Dry run, the release that would be published if: needs.decide.outputs.dry_run == 'true' run: | diff --git a/Cargo.lock b/Cargo.lock index ea7bc6449..4100e167f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1554,6 +1554,14 @@ dependencies = [ "serde_json", ] +[[package]] +name = "horizon-release-sign" +version = "0.1.0" +dependencies = [ + "base64", + "ring", +] + [[package]] name = "horizon-server" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index 409bf4689..bc67ec748 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [workspace] exclude = ["launcher", "crates/horizon-telemetry-server", "third_party/wgpu-hal"] -members = ["crates/horizon-core", "crates/horizon-dualsense", "crates/horizon-threads", "crates/horizon-world", "crates/voxel-kernels", "crates/horizon-client", "crates/horizon-server-files", "crates/horizon-server", "crates/horizon-bots", "crates/horizon-assets", "crates/horizon-protocol", "crates/horizon-theme", "crates/horizon-shaderpack", "crates/horizon-prepare", "crates/horizon-telemetry", "crates/horizon-bench", "crates/horizon-friends", "crates/horizon-relay", "crates/horizon-mod-sdk", "crates/horizon-mods", "crates/horizon-mods/tests/guest", "crates/cargo-horizon-mod", "crates/horizon-port-pack", "crates/horizon-mod-sdk/examples/coords-hud", "xtask"] +members = ["crates/horizon-core", "crates/horizon-dualsense", "crates/horizon-threads", "crates/horizon-world", "crates/voxel-kernels", "crates/horizon-client", "crates/horizon-server-files", "crates/horizon-server", "crates/horizon-bots", "crates/horizon-assets", "crates/horizon-protocol", "crates/horizon-theme", "crates/horizon-shaderpack", "crates/horizon-prepare", "crates/horizon-telemetry", "crates/horizon-bench", "crates/horizon-friends", "crates/horizon-relay", "crates/horizon-mod-sdk", "crates/horizon-mods", "crates/horizon-mods/tests/guest", "crates/cargo-horizon-mod", "crates/horizon-port-pack", "crates/horizon-release-sign", "crates/horizon-mod-sdk/examples/coords-hud", "xtask"] resolver = "2" [workspace.package] diff --git a/crates/horizon-release-sign/Cargo.toml b/crates/horizon-release-sign/Cargo.toml new file mode 100644 index 000000000..0585adcf8 --- /dev/null +++ b/crates/horizon-release-sign/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "horizon-release-sign" +version = "0.1.0" +edition.workspace = true +license.workspace = true +rust-version = "1.85" +description = "Signed release checksums: release.yml signs SHA256SUMS, the launcher and horizon-server check them before installing" + +[dependencies] +# Ed25519 and SHA-256, already in every build through rustls (ureq's TLS): no new crypto code. +ring = "0.17" +base64 = "0.22" + +[lints] +workspace = true diff --git a/crates/horizon-release-sign/release-keys.txt b/crates/horizon-release-sign/release-keys.txt new file mode 100644 index 000000000..ea2579203 --- /dev/null +++ b/crates/horizon-release-sign/release-keys.txt @@ -0,0 +1,4 @@ +# The public keys Horizon's releases are signed with (docs/security.md, "Signed updates"): one base64 Ed25519 +# key per line. The launcher and horizon-server build these in and refuse a download no key here signed. +# The private keys exist only as the RELEASE_SIGNING_KEY secret(s) of the repository's `release` environment. +# Changing this file needs Ludovic's review (.github/CODEOWNERS). diff --git a/crates/horizon-release-sign/src/lib.rs b/crates/horizon-release-sign/src/lib.rs new file mode 100644 index 000000000..7b1255921 --- /dev/null +++ b/crates/horizon-release-sign/src/lib.rs @@ -0,0 +1,320 @@ +//! Signed release checksums (docs/security.md, "Signed updates"). +//! +//! Every release carries `SHA256SUMS` (`sha256sum`'s format, ` ` per line) and +//! `SHA256SUMS.sig`: one base64 Ed25519 signature per line, each over `horizon release \n` +//! followed by SHA256SUMS's bytes, so a signed list can't be passed off under another tag. +//! release.yml and launcher.yml sign with the key(s) in the `release` environment's secrets; the +//! launcher and `horizon-server update` check a download against the public keys built in from +//! `release-keys.txt` before installing it, and refuse it otherwise. + +use base64::{Engine, engine::general_purpose::STANDARD}; +use ring::signature::{ED25519, Ed25519KeyPair, KeyPair, UnparsedPublicKey}; + +/// The checksum list's asset name. +pub const SUMS: &str = "SHA256SUMS"; +/// Its signatures' asset name. +pub const SIGNATURE: &str = "SHA256SUMS.sig"; +/// The secrets release.yml signs with: the key in use and, while rotating, the next one. +pub const KEY_VARIABLES: [&str; 2] = ["RELEASE_SIGNING_KEY", "RELEASE_SIGNING_KEY_NEXT"]; + +const KEYS: &str = include_str!("../release-keys.txt"); + +/// An Ed25519 public key. +pub type PublicKey = [u8; 32]; + +/// The public keys built in: those in `release-keys.txt`. A file that doesn't parse gives none, +/// so every download is refused rather than trusted (a test keeps the file valid). +pub fn trusted_keys() -> Vec { + parse_keys(KEYS).unwrap_or_default() +} + +/// The keys in a keys file: one base64 key per line; blank lines and `#` comments are skipped. +pub fn parse_keys(text: &str) -> Result, String> { + text.lines() + .map(str::trim) + .filter(|line| !line.is_empty() && !line.starts_with('#')) + .map(|line| { + let bytes = STANDARD + .decode(line) + .map_err(|e| format!("{line}: not base64 ({e})"))?; + PublicKey::try_from(bytes.as_slice()) + .map_err(|_| format!("{line}: not a 32-byte Ed25519 public key")) + }) + .collect() +} + +/// What a signature covers: the tag, then the checksum list. +pub fn message(tag: &str, sums: &[u8]) -> Vec { + let mut message = format!("horizon release {tag}\n").into_bytes(); + message.extend_from_slice(sums); + message +} + +/// A checksum list for `(file name, SHA-256 hex)` pairs, as `sha256sum` writes it. +pub fn sums_file(files: &[(String, String)]) -> String { + files + .iter() + .map(|(name, hex)| format!("{hex} {name}\n")) + .collect() +} + +/// The `(file name, SHA-256 hex)` pairs of a checksum list (` ` or ` *`). +pub fn parse_sums(text: &str) -> Result, String> { + text.lines() + .filter(|line| !line.trim().is_empty()) + .map(|line| { + let (hex, name) = line + .split_once(' ') + .ok_or_else(|| format!("{SUMS}: {line:?} is not ` `"))?; + let name = name.strip_prefix([' ', '*']).unwrap_or(name); + if hex.len() != 64 || !hex.bytes().all(|b| b.is_ascii_hexdigit()) || name.is_empty() { + return Err(format!("{SUMS}: {line:?} is not ` `")); + } + Ok((name.to_string(), hex.to_ascii_lowercase())) + }) + .collect() +} + +/// Checks that one of `keys` signed `sums` for `tag`, and returns the list. +pub fn verify( + tag: &str, + sums: &[u8], + signature: &str, + keys: &[PublicKey], +) -> Result, String> { + if keys.is_empty() { + return Err( + "This build has no release key built in, so it can't check downloads: none are installed." + .into(), + ); + } + let message = message(tag, sums); + let signed = signature + .lines() + .filter_map(|line| STANDARD.decode(line.trim()).ok()) + .any(|signature| { + keys.iter().any(|key| { + UnparsedPublicKey::new(&ED25519, key) + .verify(&message, &signature) + .is_ok() + }) + }); + if !signed { + return Err(format!( + "{tag}'s signature doesn't match Horizon's release key, so it was not installed. \ + The download may have been tampered with: please report it on Discord or GitHub." + )); + } + let text = std::str::from_utf8(sums).map_err(|_| format!("{SUMS} is not text"))?; + parse_sums(text) +} + +/// The signed SHA-256 of `asset` in release `tag`, or why the download must be refused. +/// `sums` and `signature` are the release's SHA256SUMS and SHA256SUMS.sig, None when it has none. +pub fn signed_digest( + tag: &str, + asset: &str, + sums: Option<&[u8]>, + signature: Option<&str>, + keys: &[PublicKey], +) -> Result { + let (Some(sums), Some(signature)) = (sums, signature) else { + return Err(format!( + "{tag} is not signed, and Horizon installs only signed releases: pick a newer version." + )); + }; + verify(tag, sums, signature, keys)? + .into_iter() + .find(|(name, _)| name == asset) + .map(|(_, hex)| hex) + .ok_or_else(|| { + format!("{asset} is not in {tag}'s signed checksums, so it was not installed.") + }) +} + +/// Whether a downloaded file's SHA-256 (`got`) is the signed one. +pub fn check(asset: &str, expected: &str, got: &str) -> Result<(), String> { + if expected.eq_ignore_ascii_case(got) { + Ok(()) + } else { + Err(format!( + "{asset} doesn't match its signed checksum (corrupted or tampered with), so it was \ + not installed. Try again." + )) + } +} + +/// SHA-256 over data that arrives in pieces (a download). +pub struct Sha256(ring::digest::Context); + +impl Default for Sha256 { + fn default() -> Self { + Self(ring::digest::Context::new(&ring::digest::SHA256)) + } +} + +impl Sha256 { + pub fn update(&mut self, bytes: &[u8]) { + self.0.update(bytes); + } + + pub fn hex(self) -> String { + self.0 + .finish() + .as_ref() + .iter() + .map(|b| format!("{b:02x}")) + .collect() + } +} + +/// The SHA-256 of `bytes`, in hex. +pub fn sha256_hex(bytes: &[u8]) -> String { + let mut hash = Sha256::default(); + hash.update(bytes); + hash.hex() +} + +/// A private signing key (release.yml only). +pub struct SigningKey(Ed25519KeyPair); + +impl SigningKey { + /// A new key, and its PKCS#8 document in base64 (what the secret holds). + pub fn generate() -> Result<(Self, String), String> { + let document = Ed25519KeyPair::generate_pkcs8(&ring::rand::SystemRandom::new()) + .map_err(|_| "no randomness to make a key with".to_string())?; + let key = Ed25519KeyPair::from_pkcs8(document.as_ref()) + .map_err(|_| "the new key doesn't parse".to_string())?; + Ok((Self(key), STANDARD.encode(document.as_ref()))) + } + + /// The key a secret holds (base64 PKCS#8). The error never quotes the secret. + pub fn from_base64(text: &str) -> Result { + let document = STANDARD + .decode(text.trim()) + .map_err(|_| "the signing key is not base64".to_string())?; + Ed25519KeyPair::from_pkcs8_maybe_unchecked(&document) + .map(Self) + .map_err(|_| "the signing key is not an Ed25519 PKCS#8 key".to_string()) + } + + pub fn public(&self) -> PublicKey { + PublicKey::try_from(self.0.public_key().as_ref()).expect("Ed25519 public keys are 32 bytes") + } + + /// The public key in base64, as release-keys.txt lists it. + pub fn public_base64(&self) -> String { + STANDARD.encode(self.public()) + } + + /// A signature line for SHA256SUMS.sig. + pub fn sign(&self, tag: &str, sums: &[u8]) -> String { + STANDARD.encode(self.0.sign(&message(tag, sums)).as_ref()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn signed(tag: &str) -> (SigningKey, String, String) { + let (key, _) = SigningKey::generate().unwrap(); + let sums = sums_file(&[ + ("horizon-linux-x86_64.tar.gz".into(), sha256_hex(b"linux")), + ("horizon-windows-x64.zip".into(), sha256_hex(b"windows")), + ]); + let signature = key.sign(tag, sums.as_bytes()) + "\n"; + (key, sums, signature) + } + + #[test] + fn the_built_in_keys_file_parses() { + assert!(parse_keys(KEYS).is_ok()); + } + + #[test] + fn a_signed_release_gives_its_digests() { + let (key, sums, signature) = signed("v2026.10.19"); + let digest = signed_digest( + "v2026.10.19", + "horizon-windows-x64.zip", + Some(sums.as_bytes()), + Some(&signature), + &[key.public()], + ); + assert_eq!(digest, Ok(sha256_hex(b"windows"))); + assert!(check("x", &sha256_hex(b"windows"), &sha256_hex(b"windows")).is_ok()); + assert!(check("x", &sha256_hex(b"windows"), &sha256_hex(b"linux")).is_err()); + } + + #[test] + fn tampering_is_refused() { + let (key, sums, signature) = signed("v2026.10.19"); + let keys = [key.public()]; + // Another tag: an old signed list replayed for a new release. + assert!(verify("v2026.10.20", sums.as_bytes(), &signature, &keys).is_err()); + // A changed checksum. + let changed = sums.replacen(&sha256_hex(b"linux"), &sha256_hex(b"evil"), 1); + assert!(verify("v2026.10.19", changed.as_bytes(), &signature, &keys).is_err()); + // Another key. + let (other, _) = SigningKey::generate().unwrap(); + assert!( + verify( + "v2026.10.19", + sums.as_bytes(), + &signature, + &[other.public()] + ) + .is_err() + ); + // No signature, no keys, an asset that isn't listed. + let none = signed_digest("v2026.10.19", "a", None, None, &keys).unwrap_err(); + assert!(none.contains("not signed"), "{none}"); + assert!(verify("v2026.10.19", sums.as_bytes(), &signature, &[]).is_err()); + let missing = signed_digest( + "v2026.10.19", + "horizon-macos-arm64.zip", + Some(sums.as_bytes()), + Some(&signature), + &keys, + ); + assert!(missing.unwrap_err().contains("not in")); + } + + #[test] + fn any_line_signed_by_any_trusted_key_passes() { + // While rotating, releases carry one signature per key and launchers trust one or both. + let (old, sums, old_line) = signed("v1"); + let (new, _) = SigningKey::generate().unwrap(); + let both = format!("{old_line}{}\n", new.sign("v1", sums.as_bytes())); + assert!(verify("v1", sums.as_bytes(), &both, &[old.public()]).is_ok()); + assert!(verify("v1", sums.as_bytes(), &both, &[new.public()]).is_ok()); + assert!(verify("v1", sums.as_bytes(), "garbage\n\n", &[old.public()]).is_err()); + } + + #[test] + fn keys_round_trip_through_their_text_forms() { + let (key, secret) = SigningKey::generate().unwrap(); + let again = SigningKey::from_base64(&format!("{secret}\n")).unwrap(); + assert_eq!(again.public(), key.public()); + assert_eq!( + parse_keys(&format!("# comment\n\n{}\n", key.public_base64())), + Ok(vec![key.public()]) + ); + assert!(parse_keys("AAAA\n").is_err()); + let error = SigningKey::from_base64("bm90IGEga2V5").err().unwrap(); + assert!(!error.contains("bm90")); + } + + #[test] + fn checksum_lists_read_both_sha256sum_forms() { + let hex = sha256_hex(b"x"); + let list = + parse_sums(&format!("{hex} a.zip\n{} *b.tar.gz\n", hex.to_uppercase())).unwrap(); + assert_eq!( + list, + [("a.zip".into(), hex.clone()), ("b.tar.gz".into(), hex)] + ); + assert!(parse_sums("nothex a.zip\n").is_err()); + } +} diff --git a/crates/horizon-release-sign/src/main.rs b/crates/horizon-release-sign/src/main.rs new file mode 100644 index 000000000..85255e4b7 --- /dev/null +++ b/crates/horizon-release-sign/src/main.rs @@ -0,0 +1,189 @@ +//! horizon-release-sign: signs a release's checksums in release.yml and launcher.yml, checks a +//! downloaded release, and makes new keys (docs/security.md, "Signed updates"). +//! +//! horizon-release-sign sign --tag v2026.10.19 dist/*.zip dist/*.tar.gz +//! horizon-release-sign sign --tag v2026.10.19 --ephemeral dist/* # a dry run: a throwaway key +//! horizon-release-sign verify --tag v2026.10.19 +//! horizon-release-sign keygen --public-out key.pub | gh secret set RELEASE_SIGNING_KEY --env release +//! +//! `sign` reads the private keys from RELEASE_SIGNING_KEY (and RELEASE_SIGNING_KEY_NEXT while +//! rotating), writes SHA256SUMS and SHA256SUMS.sig beside the first file, and checks the result +//! the way the launcher does, against the keys built in from release-keys.txt. Until that file +//! lists a key it publishes SHA256SUMS alone with a warning; once it does, a missing or unknown +//! signing key fails the release instead of publishing something launchers would refuse. + +use horizon_release_sign::{ + KEY_VARIABLES, SIGNATURE, SUMS, Sha256, SigningKey, parse_sums, sums_file, trusted_keys, verify, +}; +use std::io::{IsTerminal, Read, Write}; +use std::path::{Path, PathBuf}; +use std::process::ExitCode; + +fn main() -> ExitCode { + let args: Vec = std::env::args().skip(1).collect(); + let result = match args.first().map(String::as_str) { + Some("sign") => sign(&args[1..]), + Some("verify") => check_folder(&args[1..]), + Some("keygen") => keygen(&args[1..]), + _ => Err( + "usage: horizon-release-sign sign --tag [--ephemeral] ... | \ + verify --tag | keygen --public-out " + .into(), + ), + }; + match result { + Ok(()) => ExitCode::SUCCESS, + Err(e) => { + eprintln!("horizon-release-sign: {e}"); + ExitCode::FAILURE + } + } +} + +/// `--name value` from `args`, and the rest. +fn option(args: &[String], name: &str) -> (Option, Vec) { + let mut value = None; + let mut rest = Vec::new(); + let mut it = args.iter(); + while let Some(arg) = it.next() { + if arg == name { + value = it.next().cloned(); + } else { + rest.push(arg.clone()); + } + } + (value, rest) +} + +fn file_hash(path: &Path) -> Result { + let mut file = std::fs::File::open(path).map_err(|e| format!("{}: {e}", path.display()))?; + let mut hash = Sha256::default(); + let mut buffer = vec![0; 1 << 16]; + loop { + let n = file + .read(&mut buffer) + .map_err(|e| format!("{}: {e}", path.display()))?; + if n == 0 { + return Ok(hash.hex()); + } + hash.update(&buffer[..n]); + } +} + +fn sign(args: &[String]) -> Result<(), String> { + let (tag, rest) = option(args, "--tag"); + let tag = tag.ok_or("sign needs --tag")?; + let ephemeral = rest.iter().any(|a| a == "--ephemeral"); + let files: Vec = rest + .iter() + .filter(|a| *a != "--ephemeral") + .map(PathBuf::from) + .collect(); + let first = files.first().ok_or("sign needs the files to sign")?; + let folder = first.parent().unwrap_or(Path::new(".")); + let mut listed = Vec::new(); + for file in &files { + let name = file + .file_name() + .and_then(|n| n.to_str()) + .ok_or_else(|| format!("{}: no file name", file.display()))?; + if name != SUMS && name != SIGNATURE { + listed.push((name.to_string(), file_hash(file)?)); + } + } + let sums = sums_file(&listed); + std::fs::write(folder.join(SUMS), &sums).map_err(|e| e.to_string())?; + + let trusted = trusted_keys(); + let keys: Vec = if ephemeral { + vec![SigningKey::generate()?.0] + } else { + KEY_VARIABLES + .iter() + .filter_map(|name| std::env::var(name).ok().filter(|v| !v.trim().is_empty())) + .map(|secret| SigningKey::from_base64(&secret)) + .collect::>()? + }; + if keys.is_empty() { + if !trusted.is_empty() { + return Err(format!( + "no signing key (the release environment's {}): launchers would refuse an unsigned \ + release, so it is not published", + KEY_VARIABLES[0] + )); + } + println!( + "::warning::{tag}: published with {SUMS} but unsigned: release-keys.txt lists no key yet" + ); + return Ok(()); + } + let signature: String = keys + .iter() + .map(|key| key.sign(&tag, sums.as_bytes()) + "\n") + .collect(); + std::fs::write(folder.join(SIGNATURE), &signature).map_err(|e| e.to_string())?; + let check_with = if ephemeral || trusted.is_empty() { + if !ephemeral { + println!( + "::warning::{tag}: signed, but release-keys.txt lists no key yet: add {} to it", + keys[0].public_base64() + ); + } + keys.iter().map(SigningKey::public).collect() + } else { + trusted + }; + verify(&tag, sums.as_bytes(), &signature, &check_with).map_err(|_| { + "the signing key is not one release-keys.txt lists: launchers would refuse this release" + .to_string() + })?; + println!( + "{tag}: {} files signed with {} key(s){}", + listed.len(), + keys.len(), + if ephemeral { + " (a throwaway key: dry run)" + } else { + "" + } + ); + Ok(()) +} + +/// Checks a folder holding a release's assets with the built-in keys, as the launcher does. +fn check_folder(args: &[String]) -> Result<(), String> { + let (tag, rest) = option(args, "--tag"); + let tag = tag.ok_or("verify needs --tag")?; + let folder = PathBuf::from(rest.first().ok_or("verify needs the release's folder")?); + let read = |name: &str| std::fs::read(folder.join(name)).map_err(|e| format!("{name}: {e}")); + let sums = read(SUMS)?; + let signature = String::from_utf8(read(SIGNATURE)?).map_err(|e| e.to_string())?; + let listed = verify(&tag, &sums, &signature, &trusted_keys())?; + for (name, hex) in &listed { + horizon_release_sign::check(name, hex, &file_hash(&folder.join(name))?)?; + } + let text = String::from_utf8_lossy(&sums); + println!( + "{tag}: signature good, {} files match", + parse_sums(&text)?.len() + ); + Ok(()) +} + +/// Prints a new private key to stdout, which must be a pipe (into `gh secret set`), never a +/// terminal, and writes its public key to `--public-out`. +fn keygen(args: &[String]) -> Result<(), String> { + let (public_out, _) = option(args, "--public-out"); + let public_out = public_out.ok_or("keygen needs --public-out ")?; + if std::io::stdout().is_terminal() { + return Err( + "keygen writes the private key to its output: pipe it into `gh secret set`".into(), + ); + } + let (key, secret) = SigningKey::generate()?; + std::fs::write(&public_out, key.public_base64() + "\n").map_err(|e| e.to_string())?; + let mut out = std::io::stdout().lock(); + out.write_all(secret.as_bytes()) + .and_then(|()| out.flush()) + .map_err(|e| e.to_string()) +} diff --git a/crates/horizon-release-sign/tests/cli.rs b/crates/horizon-release-sign/tests/cli.rs new file mode 100644 index 000000000..50e4c2856 --- /dev/null +++ b/crates/horizon-release-sign/tests/cli.rs @@ -0,0 +1,100 @@ +//! The signing command as release.yml runs it. +use horizon_release_sign::{SIGNATURE, SUMS, SigningKey, signed_digest, trusted_keys}; +use std::process::Command; + +fn folder(name: &str) -> std::path::PathBuf { + let dir = std::env::temp_dir().join(format!( + "horizon-release-sign-{name}-{}", + std::process::id() + )); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("horizon-linux-x86_64.tar.gz"), b"linux build").unwrap(); + std::fs::write(dir.join("horizon-windows-x64.zip"), b"windows build").unwrap(); + dir +} + +fn sign(dir: &std::path::Path, extra: &[&str], key: Option<&str>) -> std::process::Output { + let mut cmd = Command::new(env!("CARGO_BIN_EXE_horizon-release-sign")); + cmd.args(["sign", "--tag", "v2026.10.19"]) + .args(extra) + .arg(dir.join("horizon-linux-x86_64.tar.gz")) + .arg(dir.join("horizon-windows-x64.zip")) + .env_remove("RELEASE_SIGNING_KEY") + .env_remove("RELEASE_SIGNING_KEY_NEXT"); + if let Some(key) = key { + cmd.env("RELEASE_SIGNING_KEY", key); + } + cmd.output().unwrap() +} + +#[test] +fn a_dry_run_signs_with_a_throwaway_key() { + let dir = folder("dry"); + let out = sign(&dir, &["--ephemeral"], None); + assert!( + out.status.success(), + "{}", + String::from_utf8_lossy(&out.stderr) + ); + assert!(dir.join(SUMS).exists() && dir.join(SIGNATURE).exists()); + std::fs::remove_dir_all(dir).unwrap(); +} + +#[test] +fn a_release_signs_with_the_secret_and_launchers_can_check_it() { + let dir = folder("key"); + let (key, secret) = SigningKey::generate().unwrap(); + let out = sign(&dir, &[], Some(&secret)); + let stdout = String::from_utf8_lossy(&out.stdout); + assert!(!stdout.contains(&secret) && !String::from_utf8_lossy(&out.stderr).contains(&secret)); + if trusted_keys().is_empty() { + // Before release-keys.txt lists a key: signed, with a warning naming the public key. + assert!(out.status.success()); + assert!(stdout.contains(&key.public_base64()), "{stdout}"); + let sums = std::fs::read(dir.join(SUMS)).unwrap(); + let signature = std::fs::read_to_string(dir.join(SIGNATURE)).unwrap(); + let digest = signed_digest( + "v2026.10.19", + "horizon-windows-x64.zip", + Some(&sums), + Some(&signature), + &[key.public()], + ); + assert_eq!( + digest, + Ok(horizon_release_sign::sha256_hex(b"windows build")) + ); + } else { + // A key release-keys.txt doesn't list fails the release. + assert!(!out.status.success()); + } + std::fs::remove_dir_all(dir).unwrap(); +} + +#[test] +fn without_a_secret_it_publishes_unsigned_only_until_a_key_is_listed() { + let dir = folder("none"); + let out = sign(&dir, &[], None); + assert_eq!(out.status.success(), trusted_keys().is_empty()); + assert!(!dir.join(SIGNATURE).exists()); + std::fs::remove_dir_all(dir).unwrap(); +} + +#[test] +fn keygen_writes_the_secret_to_a_pipe_and_the_public_key_to_a_file() { + let dir = folder("keygen"); + let public = dir.join("key.pub"); + let out = Command::new(env!("CARGO_BIN_EXE_horizon-release-sign")) + .args(["keygen", "--public-out"]) + .arg(&public) + .output() + .unwrap(); + assert!(out.status.success()); + let key = SigningKey::from_base64(&String::from_utf8(out.stdout).unwrap()).unwrap(); + assert_eq!( + std::fs::read_to_string(&public).unwrap().trim(), + key.public_base64() + ); + std::fs::remove_dir_all(dir).unwrap(); +} diff --git a/docs/release-flow.md b/docs/release-flow.md index b72d896b8..2947a6cb7 100644 --- a/docs/release-flow.md +++ b/docs/release-flow.md @@ -153,6 +153,38 @@ runs the game: GitHub's runners have neither a GPU worth the name nor the game f Kira posts every published release in #releases and pings the releases role only when the notes have a `### New` section. +### Signed checksums + +Every game and launcher release carries `SHA256SUMS` (the archives' SHA-256, `sha256sum`'s format) and +`SHA256SUMS.sig`: one base64 Ed25519 signature per line over `horizon release \n` followed by SHA256SUMS, +so a signed list can't be reused under another tag. The publish job signs with +`cargo run -p horizon-release-sign -- sign` (crates/horizon-release-sign), then checks the result the way +launchers do, against the public keys built in from `crates/horizon-release-sign/release-keys.txt`: + +- The private key is the `RELEASE_SIGNING_KEY` secret of the repository's `release` environment, which only real + releases from main enter (`environment:` is empty in dry runs, which sign with a throwaway key). It is in no + file, no log and no password vault; nobody needs to read it. +- While release-keys.txt lists no key, releases go out with SHA256SUMS alone and a warning (today's releases keep + working). Once it lists one, a missing secret or a key it doesn't list fails the release before anything is + published, instead of publishing something launchers would refuse. +- Making the key: `tools/ci/new_release_key.sh` pipes a new key from `horizon-release-sign keygen` straight into + `gh secret set RELEASE_SIGNING_KEY --env release` and prints only the public key, which then goes into + release-keys.txt by pull request. + +**Rotating the key** (a new key every year, or at once if the old one may have leaked). The publish job signs +with every key the environment holds, `RELEASE_SIGNING_KEY` and `RELEASE_SIGNING_KEY_NEXT`, and the two names take +turns: + +1. `tools/ci/new_release_key.sh ` makes the next key; add its public key to release-keys.txt + beside the old one. From then on every release is signed with both keys (one line each). +2. Wait until launchers and servers built with both keys are in use (a few weeks: launchers update themselves). +3. Delete the old key's secret (`gh secret delete --env release`) and its line in release-keys.txt. + The next rotation makes its new key under the name just freed. + +If the old key may have leaked, skip the wait: remove its public key from release-keys.txt at once and delete +its secret. Launchers built before the new key cannot check releases signed only with it: they refuse to install +them with a clear message, and players download the launcher again from the website once. + ### Starting one by hand ```sh diff --git a/tools/ci/new_release_key.sh b/tools/ci/new_release_key.sh new file mode 100755 index 000000000..dc2a23742 --- /dev/null +++ b/tools/ci/new_release_key.sh @@ -0,0 +1,22 @@ +#!/usr/bin/env bash +# Makes a release signing key (docs/security.md, "Signed updates"): the private key goes straight from +# horizon-release-sign into the `release` environment's secret through a pipe (never on disk, never printed, +# never in the Agents vault); the public key is printed for crates/horizon-release-sign/release-keys.txt. +# Needs a gh login that may write the repository's environment secrets (the maintainer's), and the `release` +# environment to exist. +# +# tools/ci/new_release_key.sh # the first key: RELEASE_SIGNING_KEY +# tools/ci/new_release_key.sh RELEASE_SIGNING_KEY_NEXT # rotating: the next key, signed with alongside +set -euo pipefail +secret=${1:-RELEASE_SIGNING_KEY} +case "$secret" in RELEASE_SIGNING_KEY|RELEASE_SIGNING_KEY_NEXT) ;; *) echo "unknown secret $secret" >&2; exit 2 ;; esac +repo=${GITHUB_REPOSITORY:-ludovic111/horizon} +cd "$(dirname "$0")/../.." +gh api "repos/$repo/environments/release" > /dev/null || { + echo "The release environment doesn't exist yet: create it first (docs/security.md)." >&2; exit 1; } +public=$(mktemp) +trap 'rm -f "$public"' EXIT +cargo run --quiet --locked -p horizon-release-sign -- keygen --public-out "$public" \ + | gh secret set "$secret" --env release --repo "$repo" +echo "$secret is set in $repo's release environment. Its public key, for crates/horizon-release-sign/release-keys.txt:" +cat "$public"