diff --git a/.github/workflows/release-build.yml b/.github/workflows/release-build.yml index 9d7084eb2d..a6f02b07ea 100644 --- a/.github/workflows/release-build.yml +++ b/.github/workflows/release-build.yml @@ -220,6 +220,44 @@ jobs: if command -v sha256sum >/dev/null; then sha256sum "$ASSET"; else shasum -a 256 "$ASSET"; fi > "$ASSET.sha256" gh release upload "$TAG" "$ASSET" "$ASSET.sha256" --clobber + # Signs every server archive with the updater key (`.sig`), so the app verifies a + # server from the CNB mirror as it does from GitHub (ide-tools `server::fetch`). Only this job + # gets the key; without it the archives keep only their .sha256. + server-signatures: + permissions: + contents: write + needs: server + runs-on: ubuntu-latest + steps: + - name: Signing configured + id: signing + env: + UPDATER_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }} + run: echo "updater=$([ -n "$UPDATER_KEY" ] && echo true || echo false)" >> "$GITHUB_OUTPUT" + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 + if: steps.signing.outputs.updater == 'true' + with: { ref: "${{ env.TAG }}" } + - uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0 + if: steps.signing.outputs.updater == 'true' + with: { version: 11 } + - uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0 + if: steps.signing.outputs.updater == 'true' + with: { node-version: 22, cache: pnpm } + - if: steps.signing.outputs.updater == 'true' + run: pnpm install --frozen-lockfile + - name: Sign server archives + if: steps.signing.outputs.updater == 'true' + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }} + TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }} + run: | + gh release download "$TAG" -p 'openidea-server-*.gz' -D "$RUNNER_TEMP/server" + for asset in "$RUNNER_TEMP"/server/*.gz; do + pnpm exec tauri signer sign "$asset" + done + gh release upload "$TAG" "$RUNNER_TEMP"/server/*.gz.sig --clobber + # The updater manifest (latest.json), built once from the signed bundles every build uploaded. # Fails when a platform is missing, so a release never ships a manifest without it. updater-manifest: diff --git a/Cargo.lock b/Cargo.lock index 07784ffe83..9569c7ff5d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5014,6 +5014,7 @@ dependencies = [ name = "ide-tools" version = "0.1.55" dependencies = [ + "base64 0.22.1", "blake3", "flate2", "hex", @@ -5022,6 +5023,7 @@ dependencies = [ "ide-core", "ide-language", "libc", + "minisign-verify", "parking_lot 0.12.5", "serde", "serde_json", diff --git a/crates/ide-tools/Cargo.toml b/crates/ide-tools/Cargo.toml index 67eacd2cc6..75a130474f 100644 --- a/crates/ide-tools/Cargo.toml +++ b/crates/ide-tools/Cargo.toml @@ -22,6 +22,8 @@ tar = "0.4" zip.workspace = true sha2 = "0.10" hex = "0.4" +base64.workspace = true +minisign-verify = "0.3" tempfile.workspace = true [target.'cfg(unix)'.dev-dependencies] diff --git a/crates/ide-tools/src/server.rs b/crates/ide-tools/src/server.rs index 7f342d1e2a..fcb4e10af6 100644 --- a/crates/ide-tools/src/server.rs +++ b/crates/ide-tools/src/server.rs @@ -4,11 +4,31 @@ use crate::process::Http; use crate::{InstallEvent, fetch_verified, sources}; use ide_core::CancellationToken; +use ide_core::error::ErrorKind; use ide_core::{IdeError, IdeResult}; use std::io::Read; use std::path::{Path, PathBuf}; const RELEASES: &str = "https://github.com/l0ng-ai/openidea/releases/download"; +/// The CNB copy of every published release (`cnb-mirror.yml`), the updater's other source. +const CNB_RELEASES: &str = "https://cnb.cool/l0ng-ai/openidea/-/releases/download"; + +/// Where [`fetch`] downloads a server from. +#[derive(Clone, Debug, Default)] +pub struct ReleaseSource { + /// Try the CNB mirror before GitHub (the app's update source is CNB). + pub prefer_mirror: bool, + /// The updater's minisign public key (tauri.conf.json `plugins.updater.pubkey`). Releases + /// sign each server archive with the updater key, so a signed archive verifies whichever + /// source served it. + pub updater_pubkey: Option, +} + +impl ReleaseSource { + fn bases(&self) -> [&'static str; 2] { + if self.prefer_mirror { [CNB_RELEASES, RELEASES] } else { [RELEASES, CNB_RELEASES] } + } +} /// Host platforms with a published server (Rust's `OS`-`ARCH` names). pub const PLATFORMS: &[(&str, &str)] = @@ -25,12 +45,15 @@ pub fn cached_path(app_data: &Path, version: &str, os: &str, arch: &str) -> Path } /// The server of `version` for `os`-`arch`: the cached download, or the release -/// asset downloaded now (checksum verified). +/// asset downloaded now. A signed archive (`.sig`, the updater key) is taken from `source`'s +/// preferred host first, then the other; a release without signatures falls back to GitHub +/// and its `.sha256`. pub fn fetch( app_data: &Path, version: &str, os: &str, arch: &str, + source: &ReleaseSource, cancel: &CancellationToken, emit: &dyn Fn(InstallEvent), ) -> IdeResult { @@ -48,6 +71,11 @@ pub fn fetch( let staging = tempfile_dir(dir)?; let result = (|| { let http = Http::new(&ide_core::tool_path::search_path())?; + if let Some(pubkey) = source.updater_pubkey.as_deref() + && let Some(archive) = fetch_signed(&http, source.bases(), version, &name, pubkey, &staging, cancel, emit)? + { + return install(&archive, &staging, &dest); + } // The binary runs on the remote host: never install it unverified. let checksum_url = format!("{url}.sha256"); let sha256 = sources::parse_checksum(&http.get_text(&checksum_url, cancel)?, &name) @@ -63,24 +91,92 @@ pub fn fetch( // The remote server binary is not part of Tools › Download sources: it always comes // from its own release. let archive = fetch_verified(&Default::default(), &http, &dl, &staging, cancel, emit)?; - let unpacked = staging.join("openidea-server"); - let mut gz = flate2::read::GzDecoder::new(std::fs::File::open(&archive)?); - std::io::copy(&mut gz, &mut std::fs::File::create(&unpacked)?)?; - drop(gz); - #[cfg(unix)] - { - use std::os::unix::fs::PermissionsExt; - std::fs::set_permissions(&unpacked, std::fs::Permissions::from_mode(0o755))?; - } - std::fs::rename(&unpacked, &dest)?; - // The executable is the cache entry; keeping the archive only optimizes SSH uploads. - let _ = std::fs::rename(archive, dest.with_extension("gz")); - Ok(dest.clone()) + install(&archive, &staging, &dest) })(); let _ = std::fs::remove_dir_all(&staging); result } +/// The archive from the first of `bases` that has a signature for it, verified against +/// `pubkey`. `None` when no source has a signature (a release built without the updater key); +/// an error when a signature exists but no source served an archive that matches it. +#[allow(clippy::too_many_arguments)] +fn fetch_signed( + http: &Http, + bases: [&str; 2], + version: &str, + name: &str, + pubkey: &str, + staging: &Path, + cancel: &CancellationToken, + emit: &dyn Fn(InstallEvent), +) -> IdeResult> { + let archive = staging.join(name); + let mut failures = Vec::new(); + for base in bases { + if cancel.is_cancelled() { + return Err(IdeError::cancelled()); + } + let url = format!("{base}/v{version}/{name}"); + let signature = match http.get_text_or_empty_on_404(&format!("{url}.sig"), cancel) { + Ok(text) if !text.trim().is_empty() => text, + Ok(_) => continue, + Err(e) if e.kind == ErrorKind::Cancelled => return Err(e), + Err(e) => { + failures.push(format!("{url}.sig: {}", e.message)); + continue; + } + }; + let _ = std::fs::remove_file(&archive); + let checked = http + .download(&url, &archive, None, cancel, emit) + .and_then(|()| Ok(std::fs::read(&archive)?)) + .and_then(|bytes| verify_signature(pubkey, &bytes, &signature).map_err(IdeError::unavailable)); + match checked { + Ok(()) => return Ok(Some(archive)), + Err(e) if e.kind == ErrorKind::Cancelled => return Err(e), + Err(e) => failures.push(format!("{url}: {}", e.message)), + } + } + if failures.is_empty() { + return Ok(None); + } + Err(IdeError::unavailable(format!("no verified {name}: {}", failures.join("; ")))) +} + +/// Checks `data` against a Tauri updater signature: both the key and the `.sig` file are the +/// base64 of minisign's text format. +fn verify_signature(pubkey: &str, data: &[u8], signature: &str) -> Result<(), String> { + use base64::Engine as _; + let decode = |text: &str, what: &str| { + base64::engine::general_purpose::STANDARD + .decode(text.trim()) + .ok() + .and_then(|bytes| String::from_utf8(bytes).ok()) + .ok_or_else(|| format!("unreadable {what}")) + }; + let key = minisign_verify::PublicKey::decode(&decode(pubkey, "public key")?).map_err(|e| e.to_string())?; + let signature = minisign_verify::Signature::decode(&decode(signature, "signature")?).map_err(|e| e.to_string())?; + key.verify(data, &signature, true).map_err(|_| "the signature does not match".to_owned()) +} + +/// Unpacks the verified `archive` into the cache entry `dest`. +fn install(archive: &Path, staging: &Path, dest: &Path) -> IdeResult { + let unpacked = staging.join("openidea-server"); + let mut gz = flate2::read::GzDecoder::new(std::fs::File::open(archive)?); + std::io::copy(&mut gz, &mut std::fs::File::create(&unpacked)?)?; + drop(gz); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&unpacked, std::fs::Permissions::from_mode(0o755))?; + } + std::fs::rename(&unpacked, dest)?; + // The executable is the cache entry; keeping the archive only optimizes SSH uploads. + let _ = std::fs::rename(archive, dest.with_extension("gz")); + Ok(dest.to_path_buf()) +} + /// The cached release gzip, if it unpacks to the selected server binary. pub fn matching_archive(binary: &Path, expected: blake3::Hash) -> Option> { let archive = binary.with_extension("gz"); @@ -116,6 +212,27 @@ fn tempfile_dir(parent: &Path) -> IdeResult { mod tests { use super::*; + // A throwaway key pair and a signature of PAYLOAD, made with `tauri signer generate` / `sign`. + const PUBKEY: &str = "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IEFDRjEyM0Y5NkQ2N0MxQzIKUldUQ3dXZHQrU1B4ckljNDNHNXR6QnBUQUI2WUVuSlZtNVk0cVYveGpmcEQ3cG1yYzlJN2thK24K"; + const PAYLOAD: &[u8] = b"openidea-server test payload\n"; + const SIGNATURE: &str = "dW50cnVzdGVkIGNvbW1lbnQ6IHNpZ25hdHVyZSBmcm9tIHRhdXJpIHNlY3JldCBrZXkKUlVUQ3dXZHQrU1B4ckZwcVlHejllNUl1T3h3Nk1ybVNPeWh6dTR5dXBwRmNSblE0ODBWZkdRLzZPZU16Y3NBN1hnbnpBNTk3K0VZQlk0bGkyaFlJdklQc3ZWWFdwK2F0ZEE0PQp0cnVzdGVkIGNvbW1lbnQ6IHRpbWVzdGFtcDoxNzk1OTYxNTY5CWZpbGU6cGF5bG9hZC5negpBNm52UVFPdEczK3NLZnVyOXBtVk1uUnFnYUNyRXF1bWpYbWN2RGt1SFEwV0x1b0dxb204RjJIYmo2dWlmSUtqaXdWdnRXVk9BYnpZQWFXM2JVVEhCdz09Cg=="; + + #[test] + fn archives_verify_against_the_updater_key() { + assert_eq!(verify_signature(PUBKEY, PAYLOAD, SIGNATURE), Ok(())); + assert_eq!(verify_signature(PUBKEY, PAYLOAD, &format!("{SIGNATURE}\n")), Ok(())); + assert!(verify_signature(PUBKEY, b"tampered payload\n", SIGNATURE).is_err()); + assert!(verify_signature(PUBKEY, PAYLOAD, "not base64!").is_err()); + } + + #[test] + fn the_preferred_source_comes_first() { + let github = ReleaseSource::default(); + assert_eq!(github.bases(), [RELEASES, CNB_RELEASES]); + let cnb = ReleaseSource { prefer_mirror: true, updater_pubkey: None }; + assert_eq!(cnb.bases(), [CNB_RELEASES, RELEASES]); + } + #[test] fn names_and_cache_layout() { assert_eq!(asset_name("linux", "x86_64"), "openidea-server-linux-x86_64.gz"); @@ -158,7 +275,16 @@ mod tests { #[test] fn unsupported_hosts_are_refused_without_downloading() { let tmp = tempfile::tempdir().unwrap(); - let e = fetch(tmp.path(), "1.2.3", "freebsd", "x86_64", &CancellationToken::new(), &|_| {}).unwrap_err(); + let e = fetch( + tmp.path(), + "1.2.3", + "freebsd", + "x86_64", + &ReleaseSource::default(), + &CancellationToken::new(), + &|_| {}, + ) + .unwrap_err(); assert!(e.message.contains("freebsd-x86_64"), "{e:?}"); } } diff --git a/src-tauri/src/remote_dev.rs b/src-tauri/src/remote_dev.rs index 3734ce2f55..fbf32690ed 100644 --- a/src-tauri/src/remote_dev.rs +++ b/src-tauri/src/remote_dev.rs @@ -479,6 +479,25 @@ fn mentions_version(path: &std::path::Path, version: &str) -> bool { std::fs::read(path).is_ok_and(|bytes| bytes.windows(version.len()).any(|w| w == version.as_bytes())) } +/// Where release servers download from: the app's update source first (CNB or GitHub), and +/// the updater key that signs them. +fn server_release_source(state: &AppState) -> ide_tools::server::ReleaseSource { + ide_tools::server::ReleaseSource { + prefer_mirror: crate::updates::configured_source(state) == ide_core::updates::UpdateSource::Cnb, + updater_pubkey: updater_pubkey(), + } +} + +/// `plugins.updater.pubkey` from tauri.conf.json. +fn updater_pubkey() -> Option { + static KEY: std::sync::OnceLock> = std::sync::OnceLock::new(); + KEY.get_or_init(|| { + let config: serde_json::Value = serde_json::from_str(include_str!("../tauri.conf.json")).ok()?; + config.pointer("/plugins/updater/pubkey")?.as_str().map(str::to_owned).filter(|k| !k.is_empty()) + }) + .clone() +} + /// The release build of the server for `os`/`arch`, downloaded once into the data dir. async fn download_server( state: &AppState, @@ -488,11 +507,20 @@ async fn download_server( progress: Arc, ) -> IdeResult { let (data, version, os, arch) = (state.local_data_dir.clone(), version.to_owned(), os.to_owned(), arch.to_owned()); + let source = server_release_source(state); tokio::task::spawn_blocking(move || { - ide_tools::server::fetch(&data, &version, &os, &arch, &ide_core::CancellationToken::new(), &|e| match e { - ide_tools::InstallEvent::Line { text } => tracing::info!("openidea-server download: {text}"), - ide_tools::InstallEvent::Progress { fraction, .. } => progress(RemoteStage::Downloading, fraction), - }) + ide_tools::server::fetch( + &data, + &version, + &os, + &arch, + &source, + &ide_core::CancellationToken::new(), + &|e| match e { + ide_tools::InstallEvent::Line { text } => tracing::info!("openidea-server download: {text}"), + ide_tools::InstallEvent::Progress { fraction, .. } => progress(RemoteStage::Downloading, fraction), + }, + ) }) .await .map_err(|e| IdeError::internal(e.to_string()))? @@ -1443,6 +1471,14 @@ async fn invoke_reply(peer: &Peer, call: Invoke, entries_timeout: std::time::Dur mod tests { use super::*; + #[test] + fn servers_verify_against_the_updater_key_from_the_app_config() { + use base64::Engine as _; + let key = updater_pubkey().expect("tauri.conf.json has plugins.updater.pubkey"); + let text = String::from_utf8(base64::engine::general_purpose::STANDARD.decode(key).unwrap()).unwrap(); + assert!(text.starts_with("untrusted comment: minisign public key"), "{text}"); + } + #[test] fn a_hand_placed_server_of_another_version_is_recognised() { let dir = tempfile::tempdir().unwrap(); diff --git a/src-tauri/src/updates.rs b/src-tauri/src/updates.rs index da05fa00c5..13a7a044b1 100644 --- a/src-tauri/src/updates.rs +++ b/src-tauri/src/updates.rs @@ -28,6 +28,16 @@ pub fn portable_target(os: &str, arch: &str, bundle: Option UpdateSource { + let settings = state.global_settings.effective(); + UpdateSource::resolve( + &settings.general.update_source, + &settings.appearance.locale, + &state.updates.system_locale.lock(), + ) +} + #[derive(Default)] pub struct Updates { started: AtomicBool, @@ -111,14 +121,7 @@ pub async fn check(app: &AppHandle, source: Option) -> IdeResult