Файли
openidea/crates/ide-tools/src/server.rs
T
l0ng-ai cf6d8fa510 fix(remote): download the server from the update source and verify its signature (#6860)
Remote development fetched openidea-server from GitHub only, even when the app updates from the CNB mirror. The server now comes from the configured update source first, then the other host. Releases sign every server archive with the updater key in a dedicated server-signatures job, the only one given the key, and the app verifies the archive against the updater public key from tauri.conf.json, so a signed archive is trusted from either host. Releases without signatures keep the GitHub download checked against its .sha256. When a signature exists but no host serves a matching archive, the download fails instead of falling back to an unverified binary.

Fixes #6747
2026-11-29 22:54:25 +08:00

291 рядки
12 KiB
Rust
Неформатований Анотація Історія

Цей файл містить неоднозначні символи Юнікоду
Цей файл містить символи Юнікоду, які можна сплутати з іншими символами. Якщо ви вважаєте, що це зроблено навмисно, можете сміливо ігнорувати це попередження. Щоб показати їх, скористайтеся кнопкою Escape.
//! `openidea-server` builds for remote development: the release of this
//! version publishes one per supported host platform (see `release-build.yml`).
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<String>,
}
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)] =
&[("linux", "x86_64"), ("linux", "aarch64"), ("macos", "aarch64"), ("macos", "x86_64")];
/// The release asset of the server for `os`-`arch` (gzip-compressed binary).
pub fn asset_name(os: &str, arch: &str) -> String {
format!("openidea-server-{os}-{arch}.gz")
}
/// Where a downloaded server of `version` is kept.
pub fn cached_path(app_data: &Path, version: &str, os: &str, arch: &str) -> PathBuf {
app_data.join("server").join(version).join(format!("{os}-{arch}")).join("openidea-server")
}
/// The server of `version` for `os`-`arch`: the cached download, or the release
/// 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<PathBuf> {
let dest = cached_path(app_data, version, os, arch);
if dest.is_file() {
return Ok(dest);
}
if !PLATFORMS.contains(&(os, arch)) {
return Err(IdeError::unavailable(format!("remote development does not support {os}-{arch} hosts")));
}
let name = asset_name(os, arch);
let url = format!("{RELEASES}/v{version}/{name}");
let dir = dest.parent().expect("cached path has a parent");
std::fs::create_dir_all(dir)?;
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)
.ok_or_else(|| IdeError::unavailable(format!("no SHA-256 for {name} at {checksum_url}")))?;
let dl = sources::Download {
version: version.to_owned(),
checksum_url: None,
name,
url,
size: None,
sha256: Some(sha256),
};
// 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)?;
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<Option<PathBuf>> {
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<PathBuf> {
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<Vec<u8>> {
let archive = binary.with_extension("gz");
let binary_size = binary.metadata().ok()?.len();
let meta = archive.metadata().ok()?;
if !meta.is_file() || meta.len() >= binary_size {
return None;
}
let mut packed = Vec::with_capacity(meta.len().try_into().ok()?);
std::fs::File::open(archive).ok()?.take(binary_size).read_to_end(&mut packed).ok()?;
if packed.len() as u64 >= binary_size {
return None;
}
// The receiver decodes every gzip member. Read one byte past the expected size
// so a correct-sized stream still has its trailer and any remaining input checked.
let gzip = flate2::read::MultiGzDecoder::new(packed.as_slice());
let mut hash = blake3::Hasher::new();
let decoded_size = std::io::copy(&mut gzip.take(binary_size.checked_add(1)?), &mut hash).ok()?;
(decoded_size == binary_size && hash.finalize() == expected).then_some(packed)
}
fn tempfile_dir(parent: &Path) -> IdeResult<PathBuf> {
// Unique per call: two windows of this process may download at once.
static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
let n = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let dir = parent.join(format!(".download-{}-{n}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir)?;
Ok(dir)
}
#[cfg(test)]
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");
let p = cached_path(Path::new("/data"), "1.2.3", "linux", "aarch64");
assert_eq!(p, Path::new("/data/server/1.2.3/linux-aarch64/openidea-server"));
}
#[test]
fn cached_archive_must_decode_to_the_selected_build() {
use std::io::Write as _;
let pack = |bytes: &[u8]| {
let mut gzip = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::best());
gzip.write_all(bytes).unwrap();
gzip.finish().unwrap()
};
let tmp = tempfile::tempdir().unwrap();
let binary = tmp.path().join("openidea-server");
let archive = binary.with_extension("gz");
let payload = [b'a'; 4096];
let expected = blake3::hash(&payload);
std::fs::write(&binary, payload).unwrap();
assert!(matching_archive(&binary, expected).is_none());
let gzip = pack(&payload);
std::fs::write(&archive, &gzip).unwrap();
assert_eq!(matching_archive(&binary, expected), Some(gzip.clone()));
let extra_member = pack(b"extra output");
for invalid in [
pack(&[b'b'; 4096]),
gzip[..gzip.len() - 1].to_vec(),
[gzip.as_slice(), &extra_member].concat(),
[gzip.as_slice(), b"trailing junk"].concat(),
] {
std::fs::write(&archive, &invalid).unwrap();
assert!(matching_archive(&binary, expected).is_none());
}
}
#[test]
fn unsupported_hosts_are_refused_without_downloading() {
let tmp = tempfile::tempdir().unwrap();
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:?}");
}
}