| 1 | use std::collections::HashMap; |
| 2 | use std::io::Read; |
| 3 | use std::time::Duration; |
| 4 | |
| 5 | use anyhow::{Context, Result, anyhow, bail}; |
| 6 | use serde::Deserialize; |
| 7 | |
| 8 | pub mod autoupdate; |
| 9 | pub mod check; |
| 10 | pub mod install; |
| 11 | pub mod installs; |
| 12 | pub mod launch; |
| 13 | pub mod signing; |
| 14 | pub mod tls; |
| 15 | |
| 16 | pub use check::{SuppressionReason, UpdateCheckCache, suppression_reason}; |
| 17 | pub use install::{InstallMethod, current_install_method}; |
| 18 | pub use launch::{LaunchOutcome, VersionChange, record_launch}; |
| 19 | |
| 20 | /// Filename of the SHA-256 checksum manifest included in every release. |
| 21 | /// |
| 22 | /// Mirror directories must contain this file alongside platform binaries so |
| 23 | /// that download integrity can be verified. |
| 24 | pub const CHECKSUM_MANIFEST_ASSET: &str = "codewhale-artifacts-sha256.txt"; |
| 25 | |
| 26 | pub fn parse_checksum_manifest(text: &str) -> Result<HashMap<String, String>> { |
| 27 | let mut checksums = HashMap::new(); |
| 28 | |
| 29 | for (index, line) in text.lines().enumerate() { |
| 30 | let trimmed = line.trim(); |
| 31 | if trimmed.is_empty() { |
| 32 | continue; |
| 33 | } |
| 34 | |
| 35 | if trimmed.len() < 66 { |
| 36 | bail!("invalid SHA256 manifest line {}: {trimmed}", index + 1); |
| 37 | } |
| 38 | |
| 39 | let (hash, rest) = trimmed |
| 40 | .get(..64) |
| 41 | .zip(trimmed.get(64..)) |
| 42 | .with_context(|| format!("invalid SHA256 manifest line {}: {trimmed}", index + 1))?; |
| 43 | if !hash.chars().all(|ch| ch.is_ascii_hexdigit()) |
| 44 | || rest.is_empty() |
| 45 | || !rest.chars().next().is_some_and(char::is_whitespace) |
| 46 | { |
| 47 | bail!("invalid SHA256 manifest line {}: {trimmed}", index + 1); |
| 48 | } |
| 49 | |
| 50 | let mut asset_name = rest.trim_start(); |
| 51 | if let Some(stripped) = asset_name.strip_prefix('*') { |
| 52 | asset_name = stripped; |
| 53 | } |
| 54 | if asset_name.is_empty() { |
| 55 | bail!("invalid SHA256 manifest line {}: {trimmed}", index + 1); |
| 56 | } |
| 57 | |
| 58 | checksums.insert(asset_name.to_string(), hash.to_ascii_lowercase()); |
| 59 | } |
| 60 | |
| 61 | Ok(checksums) |
| 62 | } |
| 63 | |
| 64 | /// GitHub API URL for the single latest stable release. |
| 65 | pub const LATEST_RELEASE_URL: &str = |
| 66 | "https://api.github.com/repos/codewhale-hq/CodeWhale/releases/latest"; |
| 67 | |
| 68 | /// GitHub API URL listing recent releases (up to 100), used to find beta tags. |
| 69 | pub const RELEASES_URL: &str = |
| 70 | "https://api.github.com/repos/codewhale-hq/CodeWhale/releases?per_page=100"; |
| 71 | |
| 72 | /// Base URL of the CodeWhale repository on the CNB mirror platform. |
| 73 | pub const CNB_REPO_URL: &str = "https://cnb.cool/codewhale.net/codewhale"; |
| 74 | |
| 75 | /// Environment variable that overrides the base URL for release asset downloads. |
| 76 | pub const RELEASE_BASE_URL_ENV: &str = "CODEWHALE_RELEASE_BASE_URL"; |
| 77 | |
| 78 | /// Legacy environment variable (alias for [`RELEASE_BASE_URL_ENV`]). |
| 79 | pub const LEGACY_RELEASE_BASE_URL_ENV: &str = "DEEPSEEK_TUI_RELEASE_BASE_URL"; |
| 80 | |
| 81 | /// Legacy environment variable (alias for [`RELEASE_BASE_URL_ENV`]). |
| 82 | pub const DEEPSEEK_RELEASE_BASE_URL_ENV: &str = "DEEPSEEK_RELEASE_BASE_URL"; |
| 83 | |
| 84 | /// Environment variable that, when set, enables the CNB mirror for downloads. |
| 85 | pub const CNB_MIRROR_ENV: &str = "CODEWHALE_USE_CNB_MIRROR"; |
| 86 | |
| 87 | /// Environment variable that pins the update target version. |
| 88 | pub const UPDATE_VERSION_ENV: &str = "CODEWHALE_VERSION"; |
| 89 | |
| 90 | /// Pre-rebrand environment variable (alias for [`UPDATE_VERSION_ENV`]). |
| 91 | pub const LEGACY_TUI_UPDATE_VERSION_ENV: &str = "DEEPSEEK_TUI_VERSION"; |
| 92 | |
| 93 | /// Legacy environment variable (alias for [`UPDATE_VERSION_ENV`]). |
| 94 | pub const LEGACY_UPDATE_VERSION_ENV: &str = "DEEPSEEK_VERSION"; |
| 95 | |
| 96 | /// User-Agent header sent with release metadata requests. |
| 97 | pub const UPDATE_USER_AGENT: &str = "codewhale-updater"; |
| 98 | |
| 99 | const CNB_RELEASE_ASSET_BASE: &str = "https://cnb.cool/codewhale.net/codewhale/-/releases/download"; |
| 100 | const RELEASE_METADATA_TIMEOUT: Duration = Duration::from_secs(5); |
| 101 | const RELEASE_METADATA_MAX_BYTES: usize = 8 * 1024 * 1024; |
| 102 | const ERROR_BODY_MAX_BYTES: usize = 4 * 1024; |
| 103 | |
| 104 | pub const UPDATE_MAX_REDIRECTS: usize = 10; |
| 105 | |
| 106 | const UPDATE_GITHUB_HOSTS: &[&str] = &[ |
| 107 | "github.com", |
| 108 | "api.github.com", |
| 109 | "objects.githubusercontent.com", |
| 110 | "release-assets.githubusercontent.com", |
| 111 | "github-releases.githubusercontent.com", |
| 112 | ]; |
| 113 | |
| 114 | const UPDATE_CNB_HOST: &str = "cnb.cool"; |
| 115 | |
| 116 | pub const UPDATE_ALLOWED_HOSTS_ENV: &str = "CODEWHALE_UPDATE_ALLOWED_HOSTS"; |
| 117 | |
| 118 | #[derive(Debug, Clone)] |
| 119 | pub struct UpdateTransportPolicy { |
| 120 | extra_hosts: Vec<String>, |
| 121 | #[cfg(any(test, debug_assertions))] |
| 122 | allow_loopback_http: bool, |
| 123 | } |
| 124 | |
| 125 | pub fn redact_url(url: &reqwest::Url) -> String { |
| 126 | if url.username().is_empty() && url.password().is_none() { |
| 127 | return url.to_string(); |
| 128 | } |
| 129 | let mut sanitized = url.clone(); |
| 130 | let _ = sanitized.set_username(""); |
| 131 | let _ = sanitized.set_password(None); |
| 132 | sanitized.to_string() |
| 133 | } |
| 134 | |
| 135 | pub fn redact_url_str(raw: &str) -> String { |
| 136 | match reqwest::Url::parse(raw) { |
| 137 | Ok(url) => redact_url(&url), |
| 138 | Err(_) => "<invalid URL>".to_string(), |
| 139 | } |
| 140 | } |
| 141 | |
| 142 | impl UpdateTransportPolicy { |
| 143 | pub fn from_env() -> Self { |
| 144 | let mut policy = Self::strict(); |
| 145 | if let Some(base_url) = explicit_release_base_url_from_env() |
| 146 | && let Ok(url) = reqwest::Url::parse(&base_url) |
| 147 | && let Some(host) = url.host_str() |
| 148 | { |
| 149 | policy.extra_hosts.push(host.to_ascii_lowercase()); |
| 150 | } |
| 151 | if let Ok(hosts) = std::env::var(UPDATE_ALLOWED_HOSTS_ENV) { |
| 152 | policy.extra_hosts.extend( |
| 153 | hosts |
| 154 | .split(',') |
| 155 | .map(|host| host.trim().to_ascii_lowercase()) |
| 156 | .filter(|host| !host.is_empty()), |
| 157 | ); |
| 158 | } |
| 159 | policy |
| 160 | } |
| 161 | |
| 162 | pub fn strict() -> Self { |
| 163 | Self { |
| 164 | extra_hosts: Vec::new(), |
| 165 | #[cfg(any(test, debug_assertions))] |
| 166 | allow_loopback_http: false, |
| 167 | } |
| 168 | } |
| 169 | |
| 170 | #[cfg(any(test, debug_assertions))] |
| 171 | pub fn with_loopback_http(mut self, allow: bool) -> Self { |
| 172 | self.allow_loopback_http = allow; |
| 173 | self |
| 174 | } |
| 175 | |
| 176 | pub fn host_is_allowed(&self, host: &str) -> bool { |
| 177 | let host = host.to_ascii_lowercase(); |
| 178 | UPDATE_GITHUB_HOSTS.contains(&host.as_str()) |
| 179 | || host == UPDATE_CNB_HOST |
| 180 | || host |
| 181 | .strip_suffix(UPDATE_CNB_HOST) |
| 182 | .is_some_and(|prefix| prefix.ends_with('.')) |
| 183 | || self.extra_hosts.contains(&host) |
| 184 | } |
| 185 | |
| 186 | pub fn check_url(&self, url: &reqwest::Url) -> std::result::Result<(), String> { |
| 187 | if cfg!(debug_assertions) |
| 188 | && std::env::var_os("CODEWHALE_UPDATE_ALLOW_LOOPBACK_HTTP").is_some() |
| 189 | && url.scheme() == "http" |
| 190 | && matches!(url.host_str(), Some("127.0.0.1" | "localhost")) |
| 191 | { |
| 192 | return Ok(()); |
| 193 | } |
| 194 | #[cfg(any(test, debug_assertions))] |
| 195 | if self.allow_loopback_http |
| 196 | && url.scheme() == "http" |
| 197 | && matches!(url.host_str(), Some("127.0.0.1" | "localhost")) |
| 198 | { |
| 199 | return Ok(()); |
| 200 | } |
| 201 | if url.scheme() != "https" { |
| 202 | return Err(format!( |
| 203 | "update URL must use HTTPS, not {}: {}", |
| 204 | url.scheme(), |
| 205 | redact_url(url) |
| 206 | )); |
| 207 | } |
| 208 | let host = url.host_str().unwrap_or_default(); |
| 209 | if !self.host_is_allowed(host) { |
| 210 | return Err(format!( |
| 211 | "update host {host:?} is not an allowed release host. A private mirror's host \ |
| 212 | is allowed when it is the {RELEASE_BASE_URL_ENV} HTTPS base URL; any other host \ |
| 213 | can be added with {UPDATE_ALLOWED_HOSTS_ENV}=host1,host2" |
| 214 | )); |
| 215 | } |
| 216 | Ok(()) |
| 217 | } |
| 218 | |
| 219 | pub fn check_str(&self, url: &str) -> Result<()> { |
| 220 | let parsed = reqwest::Url::parse(url) |
| 221 | .with_context(|| format!("invalid update URL {}", redact_url_str(url)))?; |
| 222 | self.check_url(&parsed).map_err(|message| anyhow!(message)) |
| 223 | } |
| 224 | } |
| 225 | |
| 226 | pub fn update_redirect_policy(policy: UpdateTransportPolicy) -> reqwest::redirect::Policy { |
| 227 | reqwest::redirect::Policy::custom(move |attempt| { |
| 228 | if attempt.previous().len() > UPDATE_MAX_REDIRECTS { |
| 229 | return attempt.error("too many redirects"); |
| 230 | } |
| 231 | match policy.check_url(attempt.url()) { |
| 232 | Ok(()) => attempt.follow(), |
| 233 | Err(message) => attempt.error(format!("update redirect refused: {message}")), |
| 234 | } |
| 235 | }) |
| 236 | } |
| 237 | |
| 238 | pub fn release_http_client( |
| 239 | timeout: Duration, |
| 240 | policy: &UpdateTransportPolicy, |
| 241 | ) -> Result<reqwest::Client> { |
| 242 | platform_http_client_builder() |
| 243 | .user_agent(UPDATE_USER_AGENT) |
| 244 | .timeout(timeout) |
| 245 | .redirect(update_redirect_policy(policy.clone())) |
| 246 | .build() |
| 247 | .context("failed to build release check HTTP client") |
| 248 | } |
| 249 | |
| 250 | /// Build a reqwest client builder with the TLS roots appropriate for the |
| 251 | /// current platform. |
| 252 | /// |
| 253 | /// Android command-line programs such as Termux do not run inside a Java |
| 254 | /// application and therefore cannot initialize reqwest's Android platform |
| 255 | /// verifier with a `JavaVM` and `Context`. Use the Mozilla WebPKI roots there |
| 256 | /// so native CLI/TUI HTTPS works without a JNI host. Other platforms keep |
| 257 | /// reqwest's platform verifier. |
| 258 | pub fn platform_http_client_builder() -> reqwest::ClientBuilder { |
| 259 | let _ = rustls::crypto::ring::default_provider().install_default(); |
| 260 | let builder = reqwest::Client::builder(); |
| 261 | #[cfg(target_os = "android")] |
| 262 | { |
| 263 | builder.tls_backend_preconfigured(android_rustls_config()) |
| 264 | } |
| 265 | #[cfg(not(target_os = "android"))] |
| 266 | { |
| 267 | builder |
| 268 | } |
| 269 | } |
| 270 | |
| 271 | /// Blocking counterpart of [`platform_http_client_builder`]. |
| 272 | pub fn platform_blocking_http_client_builder() -> reqwest::blocking::ClientBuilder { |
| 273 | let _ = rustls::crypto::ring::default_provider().install_default(); |
| 274 | let builder = reqwest::blocking::Client::builder(); |
| 275 | #[cfg(target_os = "android")] |
| 276 | { |
| 277 | builder.tls_backend_preconfigured(android_rustls_config()) |
| 278 | } |
| 279 | #[cfg(not(target_os = "android"))] |
| 280 | { |
| 281 | builder |
| 282 | } |
| 283 | } |
| 284 | |
| 285 | #[cfg(target_os = "android")] |
| 286 | fn android_rustls_config() -> rustls::ClientConfig { |
| 287 | let mut roots = rustls::RootCertStore::empty(); |
| 288 | roots.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned()); |
| 289 | rustls::ClientConfig::builder() |
| 290 | .with_root_certificates(roots) |
| 291 | .with_no_client_auth() |
| 292 | } |
| 293 | |
| 294 | /// The release channel to query for updates. |
| 295 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 296 | pub enum ReleaseChannel { |
| 297 | /// Official stable releases only. |
| 298 | Stable, |
| 299 | /// Pre-release / beta versions. |
| 300 | Beta, |
| 301 | } |
| 302 | |
| 303 | impl ReleaseChannel { |
| 304 | /// Creates a channel from a boolean flag (`true` → [`Beta`](Self::Beta)). |
| 305 | pub fn from_beta_flag(beta: bool) -> Self { |
| 306 | if beta { Self::Beta } else { Self::Stable } |
| 307 | } |
| 308 | |
| 309 | /// Returns a lowercase human-readable label (`"stable"` or `"beta"`). |
| 310 | pub fn label(self) -> &'static str { |
| 311 | match self { |
| 312 | Self::Stable => "stable", |
| 313 | Self::Beta => "beta", |
| 314 | } |
| 315 | } |
| 316 | } |
| 317 | |
| 318 | /// Describes where to fetch release metadata from. |
| 319 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 320 | pub enum ReleaseQuery { |
| 321 | /// Use a custom mirror base URL and a pinned version. |
| 322 | Mirror { base_url: String, version: String }, |
| 323 | /// Query the GitHub single-latest-release endpoint. |
| 324 | GitHubLatest { url: &'static str }, |
| 325 | /// Query the GitHub release-list endpoint (used for beta discovery). |
| 326 | GitHubReleaseList { url: &'static str }, |
| 327 | } |
| 328 | |
| 329 | /// Determines the appropriate [`ReleaseQuery`] for the given channel, taking |
| 330 | /// environment-variable overrides (mirror URL, pinned version) into account. |
| 331 | pub fn resolve_release_query(channel: ReleaseChannel) -> ReleaseQuery { |
| 332 | let version = update_version_from_env().unwrap_or_else(|| env!("CARGO_PKG_VERSION").into()); |
| 333 | if let Some(base_url) = release_base_url_from_env(&version) { |
| 334 | return ReleaseQuery::Mirror { base_url, version }; |
| 335 | } |
| 336 | |
| 337 | match channel { |
| 338 | ReleaseChannel::Stable => ReleaseQuery::GitHubLatest { |
| 339 | url: LATEST_RELEASE_URL, |
| 340 | }, |
| 341 | ReleaseChannel::Beta => ReleaseQuery::GitHubReleaseList { url: RELEASES_URL }, |
| 342 | } |
| 343 | } |
| 344 | |
| 345 | /// Reads the release base URL from environment variables, falling back to the |
| 346 | /// CNB mirror if `CODEWHALE_USE_CNB_MIRROR=1`. Returns `None` when no override |
| 347 | /// is configured. |
| 348 | pub fn release_base_url_from_env(version: &str) -> Option<String> { |
| 349 | if let Some(base_url) = explicit_release_base_url_from_env() { |
| 350 | return Some(base_url); |
| 351 | } |
| 352 | if cnb_mirror_requested_from_env() { |
| 353 | return Some(cnb_release_base_url(version)); |
| 354 | } |
| 355 | None |
| 356 | } |
| 357 | |
| 358 | fn cnb_mirror_requested_from_env() -> bool { |
| 359 | std::env::var(CNB_MIRROR_ENV).is_ok_and(|value| value == "1") |
| 360 | } |
| 361 | |
| 362 | /// Reads an operator-supplied release base URL, ignoring the CNB mirror flag. |
| 363 | /// |
| 364 | /// Kept separate from [`release_base_url_from_env`] so callers can tell an |
| 365 | /// explicit mirror directory apart from "use the CNB mirror for this version". |
| 366 | pub fn explicit_release_base_url_from_env() -> Option<String> { |
| 367 | for env_name in [ |
| 368 | RELEASE_BASE_URL_ENV, |
| 369 | LEGACY_RELEASE_BASE_URL_ENV, |
| 370 | DEEPSEEK_RELEASE_BASE_URL_ENV, |
| 371 | ] { |
| 372 | if let Ok(value) = std::env::var(env_name) { |
| 373 | let trimmed = value.trim().to_string(); |
| 374 | if !trimmed.is_empty() { |
| 375 | return Some(trimmed); |
| 376 | } |
| 377 | } |
| 378 | } |
| 379 | None |
| 380 | } |
| 381 | |
| 382 | /// True when `CODEWHALE_USE_CNB_MIRROR` is the override actually in effect — |
| 383 | /// it is exactly `1`, and no explicit base URL outranks it. |
| 384 | pub fn cnb_mirror_override_active() -> bool { |
| 385 | explicit_release_base_url_from_env().is_none() && cnb_mirror_requested_from_env() |
| 386 | } |
| 387 | |
| 388 | /// True when the first-party CNB mirror publishes release binaries for this |
| 389 | /// target. |
| 390 | /// |
| 391 | /// The CNB tag pipeline (`.cnb.yml`) builds exactly one artifact set — Linux |
| 392 | /// x64, statically linked against musl. Every other platform is served by |
| 393 | /// canonical GitHub Releases or by an explicit |
| 394 | /// [`RELEASE_BASE_URL_ENV`] mirror, so the updater must not offer CNB there. |
| 395 | pub fn cnb_mirror_supports_target(os: &str, rust_arch: &str) -> bool { |
| 396 | os == "linux" && rust_arch == "x86_64" |
| 397 | } |
| 398 | |
| 399 | /// Constructs the CNB mirror asset URL for a given version tag. |
| 400 | pub fn cnb_release_base_url(version: &str) -> String { |
| 401 | format!( |
| 402 | "{}/v{}", |
| 403 | CNB_RELEASE_ASSET_BASE.trim_end_matches('/'), |
| 404 | version.trim_start_matches('v') |
| 405 | ) |
| 406 | } |
| 407 | |
| 408 | /// Returns the pinned update version from environment variables, or `None` |
| 409 | /// if `CODEWHALE_VERSION` and its two legacy aliases are unset or empty. |
| 410 | pub fn update_version_from_env() -> Option<String> { |
| 411 | [ |
| 412 | UPDATE_VERSION_ENV, |
| 413 | LEGACY_TUI_UPDATE_VERSION_ENV, |
| 414 | LEGACY_UPDATE_VERSION_ENV, |
| 415 | ] |
| 416 | .into_iter() |
| 417 | .find_map(|name| { |
| 418 | std::env::var(name) |
| 419 | .ok() |
| 420 | .map(|value| value.trim().trim_start_matches('v').to_string()) |
| 421 | .filter(|value| !value.is_empty()) |
| 422 | }) |
| 423 | } |
| 424 | |
| 425 | /// Joins a mirror base URL with an asset filename to produce a full download URL. |
| 426 | pub fn mirror_asset_url(base_url: &str, asset_name: &str) -> String { |
| 427 | format!("{}/{}", base_url.trim_end_matches('/'), asset_name) |
| 428 | } |
| 429 | |
| 430 | /// Returns a human-readable hint explaining how to use a mirror when GitHub |
| 431 | /// downloads are blocked or slow (e.g. on mainland China networks). |
| 432 | pub fn update_network_fallback_hint() -> String { |
| 433 | format!( |
| 434 | "GitHub release downloads may be blocked or slow on this network.\n\ |
| 435 | For mainland China, use one of these fallback paths:\n\ |
| 436 | 1. Source build from the CNB mirror, installing the shipped binary:\n\ |
| 437 | cargo install --git {CNB_REPO_URL} --tag vX.Y.Z codewhale-cli --locked --force\n\ |
| 438 | 2. Use a binary asset mirror:\n\ |
| 439 | {RELEASE_BASE_URL_ENV}=https://<mirror>/<release-assets>/ {UPDATE_VERSION_ENV}=X.Y.Z codewhale update\n\ |
| 440 | The mirror directory must contain {CHECKSUM_MANIFEST_ASSET} and the codewhale platform binary." |
| 441 | ) |
| 442 | } |
| 443 | |
| 444 | /// Fetches a release JSON payload from `url` (async). |
| 445 | /// |
| 446 | /// `description` is included in error messages to identify the request purpose. |
| 447 | pub async fn fetch_release_json_async(url: &str, description: &str) -> Result<String> { |
| 448 | fetch_release_json_async_with_policy(url, description, &UpdateTransportPolicy::from_env()).await |
| 449 | } |
| 450 | |
| 451 | async fn fetch_release_json_async_with_policy( |
| 452 | url: &str, |
| 453 | description: &str, |
| 454 | policy: &UpdateTransportPolicy, |
| 455 | ) -> Result<String> { |
| 456 | policy.check_str(url)?; |
| 457 | let safe_url = redact_url_str(url); |
| 458 | let client = release_http_client(RELEASE_METADATA_TIMEOUT, policy)?; |
| 459 | let response = client |
| 460 | .get(url) |
| 461 | .header(reqwest::header::ACCEPT, "application/vnd.github+json") |
| 462 | .send() |
| 463 | .await |
| 464 | .map_err(reqwest::Error::without_url) |
| 465 | .with_context(|| format!("failed to fetch {description} from {safe_url}"))?; |
| 466 | let status = response.status(); |
| 467 | let bytes = read_http_response(response, RELEASE_METADATA_MAX_BYTES) |
| 468 | .await |
| 469 | .with_context(|| format!("failed to read {description} response from {safe_url}"))?; |
| 470 | let body = String::from_utf8_lossy(&bytes); |
| 471 | if !status.is_success() { |
| 472 | bail!("GitHub release request failed with HTTP {status}: {body}"); |
| 473 | } |
| 474 | Ok(body.into_owned()) |
| 475 | } |
| 476 | |
| 477 | pub async fn read_http_response( |
| 478 | mut response: reqwest::Response, |
| 479 | max_bytes: usize, |
| 480 | ) -> Result<Vec<u8>> { |
| 481 | let status = response.status(); |
| 482 | let limit = update_body_limit(status, response.content_length(), max_bytes)?; |
| 483 | let mut bytes = Vec::new(); |
| 484 | while let Some(chunk) = response |
| 485 | .chunk() |
| 486 | .await |
| 487 | .map_err(reqwest::Error::without_url) |
| 488 | .context("failed to read HTTP response")? |
| 489 | { |
| 490 | let remaining = limit.saturating_add(1) - bytes.len(); |
| 491 | bytes.extend_from_slice(&chunk[..remaining.min(chunk.len())]); |
| 492 | if bytes.len() > limit { |
| 493 | break; |
| 494 | } |
| 495 | } |
| 496 | finish_update_body(bytes, status, limit) |
| 497 | } |
| 498 | |
| 499 | fn update_body_limit( |
| 500 | status: reqwest::StatusCode, |
| 501 | content_length: Option<u64>, |
| 502 | max_bytes: usize, |
| 503 | ) -> Result<usize> { |
| 504 | if !status.is_success() { |
| 505 | return Ok(max_bytes.min(ERROR_BODY_MAX_BYTES)); |
| 506 | } |
| 507 | if content_length.is_some_and(|length| length > max_bytes as u64) { |
| 508 | bail!("response exceeds the {max_bytes}-byte update limit"); |
| 509 | } |
| 510 | Ok(max_bytes) |
| 511 | } |
| 512 | |
| 513 | fn finish_update_body( |
| 514 | mut bytes: Vec<u8>, |
| 515 | status: reqwest::StatusCode, |
| 516 | limit: usize, |
| 517 | ) -> Result<Vec<u8>> { |
| 518 | let truncated = bytes.len() > limit; |
| 519 | if status.is_success() { |
| 520 | anyhow::ensure!(!truncated, "response exceeds the {limit}-byte update limit"); |
| 521 | return Ok(bytes); |
| 522 | } |
| 523 | bytes.truncate(limit); |
| 524 | let mut diagnostic = |
| 525 | codewhale_sanitize::sanitize::sanitize_text(&String::from_utf8_lossy(&bytes)); |
| 526 | if truncated { |
| 527 | diagnostic.push_str(" … [truncated]"); |
| 528 | } |
| 529 | Ok(diagnostic.into_bytes()) |
| 530 | } |
| 531 | |
| 532 | fn sanitize_blocking_read_error(err: std::io::Error) -> anyhow::Error { |
| 533 | let kind = err.kind(); |
| 534 | match err.into_inner() { |
| 535 | Some(inner) => match inner.downcast::<reqwest::Error>() { |
| 536 | Ok(req_err) => anyhow::Error::new(std::io::Error::new(kind, req_err.without_url())), |
| 537 | Err(other) => anyhow::Error::new(std::io::Error::new(kind, other)), |
| 538 | }, |
| 539 | None => anyhow::Error::new(std::io::Error::from(kind)), |
| 540 | } |
| 541 | } |
| 542 | |
| 543 | pub fn read_update_response( |
| 544 | response: reqwest::blocking::Response, |
| 545 | max_bytes: usize, |
| 546 | ) -> Result<Vec<u8>> { |
| 547 | let status = response.status(); |
| 548 | let limit = update_body_limit(status, response.content_length(), max_bytes)?; |
| 549 | let mut bytes = Vec::new(); |
| 550 | response |
| 551 | .take((limit as u64).saturating_add(1)) |
| 552 | .read_to_end(&mut bytes) |
| 553 | .map_err(sanitize_blocking_read_error)?; |
| 554 | finish_update_body(bytes, status, limit) |
| 555 | } |
| 556 | |
| 557 | pub fn read_release_metadata(response: reqwest::blocking::Response) -> Result<String> { |
| 558 | let bytes = read_update_response(response, RELEASE_METADATA_MAX_BYTES)?; |
| 559 | Ok(String::from_utf8_lossy(&bytes).into_owned()) |
| 560 | } |
| 561 | |
| 562 | pub fn parse_release_json<T: serde::de::DeserializeOwned>( |
| 563 | body: &str, |
| 564 | description: &str, |
| 565 | ) -> Result<T> { |
| 566 | serde_json::from_str(body).map_err(|error| { |
| 567 | anyhow::anyhow!( |
| 568 | "failed to parse {description} JSON from GitHub API at line {}, column {}", |
| 569 | error.line(), |
| 570 | error.column() |
| 571 | ) |
| 572 | }) |
| 573 | } |
| 574 | |
| 575 | #[derive(Deserialize)] |
| 576 | struct ReleaseTag { |
| 577 | tag_name: String, |
| 578 | } |
| 579 | |
| 580 | #[derive(Deserialize)] |
| 581 | struct ReleaseListEntry { |
| 582 | tag_name: String, |
| 583 | } |
| 584 | |
| 585 | /// Extracts the `tag_name` field from a GitHub single-release JSON response. |
| 586 | pub fn latest_tag_from_release_json(body: &str) -> Result<String> { |
| 587 | let release: ReleaseTag = parse_release_json(body, "release")?; |
| 588 | Ok(release.tag_name) |
| 589 | } |
| 590 | |
| 591 | /// Scans a GitHub release-list JSON response and returns the tag of the first |
| 592 | /// entry whose name contains `"beta"`. |
| 593 | pub fn latest_beta_tag_from_release_list_json(body: &str) -> Result<String> { |
| 594 | let releases: Vec<ReleaseListEntry> = parse_release_json(body, "release list")?; |
| 595 | releases |
| 596 | .into_iter() |
| 597 | .find(|release| is_beta_tag(&release.tag_name)) |
| 598 | .map(|release| release.tag_name) |
| 599 | .context("no beta release found in GitHub releases") |
| 600 | } |
| 601 | |
| 602 | /// Async helper that resolves the latest release tag for the given channel. |
| 603 | /// |
| 604 | /// For mirrors the version is derived from the pinned environment variable; |
| 605 | /// for GitHub channels the appropriate API endpoint is queried. |
| 606 | pub async fn latest_release_tag_async(channel: ReleaseChannel) -> Result<String> { |
| 607 | match resolve_release_query(channel) { |
| 608 | ReleaseQuery::Mirror { version, .. } => Ok(format!("v{}", version.trim_start_matches('v'))), |
| 609 | ReleaseQuery::GitHubLatest { url } => { |
| 610 | let body = fetch_release_json_async(url, "latest release").await?; |
| 611 | latest_tag_from_release_json(&body) |
| 612 | } |
| 613 | ReleaseQuery::GitHubReleaseList { url } => { |
| 614 | let body = fetch_release_json_async(url, "release list").await?; |
| 615 | latest_beta_tag_from_release_list_json(&body) |
| 616 | } |
| 617 | } |
| 618 | } |
| 619 | |
| 620 | /// Compares a current version string against a release tag using semver |
| 621 | /// ordering. Both `v` prefixes and trailing build metadata (e.g. `(abc123)`) |
| 622 | /// are stripped before comparison. |
| 623 | pub fn compare_release_versions( |
| 624 | current_version: &str, |
| 625 | latest_tag: &str, |
| 626 | ) -> Result<std::cmp::Ordering> { |
| 627 | let current = parse_release_version(current_version) |
| 628 | .with_context(|| format!("failed to parse current version {current_version:?}"))?; |
| 629 | let latest = parse_release_version(latest_tag) |
| 630 | .with_context(|| format!("failed to parse latest release tag {latest_tag:?}"))?; |
| 631 | Ok(current.cmp(&latest)) |
| 632 | } |
| 633 | |
| 634 | /// Determines whether an update is needed for the given channel. |
| 635 | /// |
| 636 | /// For [`Stable`](ReleaseChannel::Stable) an update is needed when the latest |
| 637 | /// release is strictly newer. For [`Beta`](ReleaseChannel::Beta) the logic also |
| 638 | /// allows switching from a stable release to a beta on the same release line. |
| 639 | pub fn update_is_needed( |
| 640 | channel: ReleaseChannel, |
| 641 | current_version: &str, |
| 642 | latest_tag: &str, |
| 643 | ) -> Result<bool> { |
| 644 | let current = parse_release_version(current_version) |
| 645 | .with_context(|| format!("failed to parse current version {current_version:?}"))?; |
| 646 | let latest = parse_release_version(latest_tag) |
| 647 | .with_context(|| format!("failed to parse latest release tag {latest_tag:?}"))?; |
| 648 | |
| 649 | match channel { |
| 650 | ReleaseChannel::Stable => Ok(current < latest), |
| 651 | ReleaseChannel::Beta => { |
| 652 | if current == latest { |
| 653 | return Ok(false); |
| 654 | } |
| 655 | let latest_is_beta = version_is_beta(&latest); |
| 656 | let current_is_stable = current.pre.is_empty(); |
| 657 | let same_release_line = current.major == latest.major |
| 658 | && current.minor == latest.minor |
| 659 | && current.patch == latest.patch; |
| 660 | if current > latest && !(current_is_stable && same_release_line) { |
| 661 | return Ok(false); |
| 662 | } |
| 663 | Ok(latest_is_beta) |
| 664 | } |
| 665 | } |
| 666 | } |
| 667 | |
| 668 | /// Parses a version string (with optional `v` prefix and trailing build info) |
| 669 | /// into a [`semver::Version`]. |
| 670 | pub fn parse_release_version(value: &str) -> Result<semver::Version> { |
| 671 | let version = value |
| 672 | .trim() |
| 673 | .trim_start_matches('v') |
| 674 | .split_whitespace() |
| 675 | .next() |
| 676 | .unwrap_or(""); |
| 677 | semver::Version::parse(version).with_context(|| format!("invalid semver: {value:?}")) |
| 678 | } |
| 679 | |
| 680 | /// Returns `true` if the tag name contains `"beta"` (case-insensitive). |
| 681 | pub fn is_beta_tag(tag_name: &str) -> bool { |
| 682 | tag_name.to_ascii_lowercase().contains("beta") |
| 683 | } |
| 684 | |
| 685 | fn version_is_beta(version: &semver::Version) -> bool { |
| 686 | version.pre.as_str().to_ascii_lowercase().contains("beta") |
| 687 | } |
| 688 | |
| 689 | #[cfg(test)] |
| 690 | mod tests { |
| 691 | use std::ffi::OsString; |
| 692 | use std::sync::{Mutex, MutexGuard}; |
| 693 | |
| 694 | use super::*; |
| 695 | |
| 696 | static RELEASE_ENV_LOCK: Mutex<()> = Mutex::new(()); |
| 697 | const RELEASE_ENV_VARS: &[&str] = &[ |
| 698 | RELEASE_BASE_URL_ENV, |
| 699 | LEGACY_RELEASE_BASE_URL_ENV, |
| 700 | DEEPSEEK_RELEASE_BASE_URL_ENV, |
| 701 | CNB_MIRROR_ENV, |
| 702 | UPDATE_VERSION_ENV, |
| 703 | LEGACY_TUI_UPDATE_VERSION_ENV, |
| 704 | LEGACY_UPDATE_VERSION_ENV, |
| 705 | ]; |
| 706 | |
| 707 | struct ReleaseEnvGuard { |
| 708 | previous: Vec<(&'static str, Option<OsString>)>, |
| 709 | _lock: MutexGuard<'static, ()>, |
| 710 | } |
| 711 | |
| 712 | impl ReleaseEnvGuard { |
| 713 | fn clear() -> Self { |
| 714 | let lock = RELEASE_ENV_LOCK |
| 715 | .lock() |
| 716 | .unwrap_or_else(|poisoned| poisoned.into_inner()); |
| 717 | let previous = RELEASE_ENV_VARS |
| 718 | .iter() |
| 719 | .map(|&name| (name, std::env::var_os(name))) |
| 720 | .collect(); |
| 721 | for &name in RELEASE_ENV_VARS { |
| 722 | // SAFETY: tests that mutate these process-wide vars hold RELEASE_ENV_LOCK. |
| 723 | unsafe { std::env::remove_var(name) }; |
| 724 | } |
| 725 | Self { |
| 726 | previous, |
| 727 | _lock: lock, |
| 728 | } |
| 729 | } |
| 730 | } |
| 731 | |
| 732 | impl Drop for ReleaseEnvGuard { |
| 733 | fn drop(&mut self) { |
| 734 | for (name, value) in &self.previous { |
| 735 | // SAFETY: the guard still holds RELEASE_ENV_LOCK while restoring state. |
| 736 | unsafe { |
| 737 | match value { |
| 738 | Some(value) => std::env::set_var(name, value), |
| 739 | None => std::env::remove_var(name), |
| 740 | } |
| 741 | } |
| 742 | } |
| 743 | } |
| 744 | } |
| 745 | |
| 746 | fn set_release_env(name: &str, value: &str) { |
| 747 | // SAFETY: callers hold a ReleaseEnvGuard, which serializes env mutation. |
| 748 | unsafe { std::env::set_var(name, value) }; |
| 749 | } |
| 750 | |
| 751 | #[test] |
| 752 | fn release_channel_from_beta_flag_maps_booleans() { |
| 753 | assert_eq!( |
| 754 | ReleaseChannel::from_beta_flag(false), |
| 755 | ReleaseChannel::Stable |
| 756 | ); |
| 757 | assert_eq!(ReleaseChannel::from_beta_flag(true), ReleaseChannel::Beta); |
| 758 | } |
| 759 | |
| 760 | #[test] |
| 761 | fn release_channel_label_matches_channel_names() { |
| 762 | assert_eq!(ReleaseChannel::Stable.label(), "stable"); |
| 763 | assert_eq!(ReleaseChannel::Beta.label(), "beta"); |
| 764 | } |
| 765 | |
| 766 | #[test] |
| 767 | fn is_beta_tag_detects_beta_prereleases_case_insensitively() { |
| 768 | for tag in [ |
| 769 | "beta", |
| 770 | "BETA", |
| 771 | "BeTa", |
| 772 | "v1.0.0-beta.1", |
| 773 | "v1.0.0-BETA.1", |
| 774 | "v2.0.0-beta", |
| 775 | "something-beta-something", |
| 776 | "beta-1.0", |
| 777 | ] { |
| 778 | assert!(is_beta_tag(tag), "{tag} should be beta"); |
| 779 | } |
| 780 | |
| 781 | for tag in [ |
| 782 | "", |
| 783 | "bet", |
| 784 | "alpha", |
| 785 | "rc", |
| 786 | "v1.0.0", |
| 787 | "v1.0.0-alpha.1", |
| 788 | "v1.0.0-rc.1", |
| 789 | ] { |
| 790 | assert!(!is_beta_tag(tag), "{tag} should not be beta"); |
| 791 | } |
| 792 | } |
| 793 | |
| 794 | #[test] |
| 795 | fn release_base_url_from_env_returns_none_without_overrides() { |
| 796 | let _env = ReleaseEnvGuard::clear(); |
| 797 | |
| 798 | assert_eq!(release_base_url_from_env("1.0.0"), None); |
| 799 | } |
| 800 | |
| 801 | #[test] |
| 802 | fn release_base_url_from_env_prefers_primary_override() { |
| 803 | let _env = ReleaseEnvGuard::clear(); |
| 804 | set_release_env(RELEASE_BASE_URL_ENV, "https://primary.example.com"); |
| 805 | set_release_env(LEGACY_RELEASE_BASE_URL_ENV, "https://legacy.example.com"); |
| 806 | |
| 807 | assert_eq!( |
| 808 | release_base_url_from_env("1.0.0"), |
| 809 | Some("https://primary.example.com".to_string()) |
| 810 | ); |
| 811 | } |
| 812 | |
| 813 | #[test] |
| 814 | fn release_base_url_from_env_falls_back_to_legacy_overrides() { |
| 815 | let _env = ReleaseEnvGuard::clear(); |
| 816 | set_release_env(LEGACY_RELEASE_BASE_URL_ENV, "https://legacy.example.com"); |
| 817 | set_release_env( |
| 818 | DEEPSEEK_RELEASE_BASE_URL_ENV, |
| 819 | "https://deepseek.example.com", |
| 820 | ); |
| 821 | |
| 822 | assert_eq!( |
| 823 | release_base_url_from_env("1.0.0"), |
| 824 | Some("https://legacy.example.com".to_string()) |
| 825 | ); |
| 826 | |
| 827 | set_release_env(LEGACY_RELEASE_BASE_URL_ENV, ""); |
| 828 | |
| 829 | assert_eq!( |
| 830 | release_base_url_from_env("1.0.0"), |
| 831 | Some("https://deepseek.example.com".to_string()) |
| 832 | ); |
| 833 | } |
| 834 | |
| 835 | #[test] |
| 836 | fn release_base_url_from_env_trims_and_ignores_empty_overrides() { |
| 837 | let _env = ReleaseEnvGuard::clear(); |
| 838 | set_release_env(RELEASE_BASE_URL_ENV, " https://spaced.example.com \n"); |
| 839 | |
| 840 | assert_eq!( |
| 841 | release_base_url_from_env("1.0.0"), |
| 842 | Some("https://spaced.example.com".to_string()) |
| 843 | ); |
| 844 | |
| 845 | set_release_env(RELEASE_BASE_URL_ENV, " "); |
| 846 | set_release_env(LEGACY_RELEASE_BASE_URL_ENV, ""); |
| 847 | set_release_env(DEEPSEEK_RELEASE_BASE_URL_ENV, "\n"); |
| 848 | |
| 849 | assert_eq!(release_base_url_from_env("1.0.0"), None); |
| 850 | } |
| 851 | |
| 852 | #[test] |
| 853 | fn release_base_url_from_env_uses_cnb_mirror_last() { |
| 854 | let _env = ReleaseEnvGuard::clear(); |
| 855 | set_release_env(CNB_MIRROR_ENV, "1"); |
| 856 | |
| 857 | assert_eq!( |
| 858 | release_base_url_from_env("v1.2.3"), |
| 859 | Some("https://cnb.cool/codewhale.net/codewhale/-/releases/download/v1.2.3".to_string()) |
| 860 | ); |
| 861 | |
| 862 | set_release_env(RELEASE_BASE_URL_ENV, "https://explicit.example.com"); |
| 863 | |
| 864 | assert_eq!( |
| 865 | release_base_url_from_env("1.0.0"), |
| 866 | Some("https://explicit.example.com".to_string()) |
| 867 | ); |
| 868 | |
| 869 | set_release_env(RELEASE_BASE_URL_ENV, ""); |
| 870 | set_release_env(CNB_MIRROR_ENV, "0"); |
| 871 | assert_eq!( |
| 872 | release_base_url_from_env("1.0.0"), |
| 873 | None, |
| 874 | "the Rust updater must match npm and require an exact =1 override" |
| 875 | ); |
| 876 | } |
| 877 | |
| 878 | #[test] |
| 879 | fn cnb_mirror_override_is_active_only_without_an_explicit_base_url() { |
| 880 | let _env = ReleaseEnvGuard::clear(); |
| 881 | assert!(!cnb_mirror_override_active()); |
| 882 | |
| 883 | set_release_env(CNB_MIRROR_ENV, "1"); |
| 884 | assert!(cnb_mirror_override_active()); |
| 885 | |
| 886 | set_release_env(RELEASE_BASE_URL_ENV, "https://explicit.example.com"); |
| 887 | assert!( |
| 888 | !cnb_mirror_override_active(), |
| 889 | "an explicit base URL outranks the CNB flag" |
| 890 | ); |
| 891 | |
| 892 | set_release_env(RELEASE_BASE_URL_ENV, ""); |
| 893 | for disabled in ["", "0", "true", "yes", " 1 "] { |
| 894 | set_release_env(CNB_MIRROR_ENV, disabled); |
| 895 | assert!( |
| 896 | !cnb_mirror_override_active(), |
| 897 | "only CODEWHALE_USE_CNB_MIRROR=1 may force CNB, got {disabled:?}" |
| 898 | ); |
| 899 | } |
| 900 | } |
| 901 | |
| 902 | #[test] |
| 903 | fn cnb_mirror_publishes_linux_x64_only() { |
| 904 | assert!(cnb_mirror_supports_target("linux", "x86_64")); |
| 905 | |
| 906 | for (os, arch) in [ |
| 907 | ("linux", "aarch64"), |
| 908 | ("linux", "riscv64"), |
| 909 | ("macos", "x86_64"), |
| 910 | ("macos", "aarch64"), |
| 911 | ("windows", "x86_64"), |
| 912 | ("windows", "aarch64"), |
| 913 | ("android", "aarch64"), |
| 914 | ] { |
| 915 | assert!( |
| 916 | !cnb_mirror_supports_target(os, arch), |
| 917 | "CNB must not claim {os}/{arch}" |
| 918 | ); |
| 919 | } |
| 920 | } |
| 921 | |
| 922 | #[test] |
| 923 | fn update_version_from_env_prefers_primary_then_legacy() { |
| 924 | { |
| 925 | let _env = ReleaseEnvGuard::clear(); |
| 926 | set_release_env(UPDATE_VERSION_ENV, " v1.2.3 "); |
| 927 | |
| 928 | assert_eq!(update_version_from_env().as_deref(), Some("1.2.3")); |
| 929 | } |
| 930 | |
| 931 | { |
| 932 | let _env = ReleaseEnvGuard::clear(); |
| 933 | set_release_env(LEGACY_UPDATE_VERSION_ENV, "v1.2.4"); |
| 934 | |
| 935 | assert_eq!(update_version_from_env().as_deref(), Some("1.2.4")); |
| 936 | } |
| 937 | } |
| 938 | |
| 939 | #[test] |
| 940 | fn update_version_from_env_ignores_missing_or_empty_values() { |
| 941 | let _env = ReleaseEnvGuard::clear(); |
| 942 | assert_eq!(update_version_from_env(), None); |
| 943 | |
| 944 | set_release_env(UPDATE_VERSION_ENV, " "); |
| 945 | set_release_env(LEGACY_UPDATE_VERSION_ENV, ""); |
| 946 | |
| 947 | assert_eq!(update_version_from_env(), None); |
| 948 | } |
| 949 | |
| 950 | #[test] |
| 951 | fn canonical_version_pin_outranks_both_preserved_legacy_aliases() { |
| 952 | let _env = ReleaseEnvGuard::clear(); |
| 953 | set_release_env("CODEWHALE_VERSION", "v0.9.11"); |
| 954 | set_release_env("DEEPSEEK_TUI_VERSION", "v0.9.10"); |
| 955 | set_release_env("DEEPSEEK_VERSION", "v0.9.9"); |
| 956 | assert_eq!(update_version_from_env().as_deref(), Some("0.9.11")); |
| 957 | set_release_env("CODEWHALE_VERSION", " "); |
| 958 | assert_eq!(update_version_from_env().as_deref(), Some("0.9.10")); |
| 959 | set_release_env("DEEPSEEK_TUI_VERSION", " "); |
| 960 | assert_eq!(update_version_from_env().as_deref(), Some("0.9.9")); |
| 961 | } |
| 962 | |
| 963 | #[test] |
| 964 | fn update_network_fallback_hint_mentions_required_mirror_inputs() { |
| 965 | let hint = update_network_fallback_hint(); |
| 966 | |
| 967 | assert!(hint.contains(CNB_REPO_URL), "hint missing CNB_REPO_URL"); |
| 968 | assert!( |
| 969 | hint.contains(RELEASE_BASE_URL_ENV), |
| 970 | "hint missing RELEASE_BASE_URL_ENV" |
| 971 | ); |
| 972 | assert!( |
| 973 | hint.contains(UPDATE_VERSION_ENV), |
| 974 | "hint missing UPDATE_VERSION_ENV" |
| 975 | ); |
| 976 | assert!( |
| 977 | hint.contains(CHECKSUM_MANIFEST_ASSET), |
| 978 | "hint missing CHECKSUM_MANIFEST_ASSET" |
| 979 | ); |
| 980 | assert!( |
| 981 | hint.contains("codewhale platform binary"), |
| 982 | "hint must describe the sole implementation asset" |
| 983 | ); |
| 984 | assert!( |
| 985 | !hint.contains("codewhale-tui"), |
| 986 | "hint must not request the removed TUI implementation asset" |
| 987 | ); |
| 988 | } |
| 989 | |
| 990 | #[test] |
| 991 | fn mirror_asset_url_trims_trailing_base_slashes() { |
| 992 | for base_url in [ |
| 993 | "https://example.com/assets", |
| 994 | "https://example.com/assets/", |
| 995 | "https://example.com/assets//", |
| 996 | ] { |
| 997 | assert_eq!( |
| 998 | mirror_asset_url(base_url, "file.zip"), |
| 999 | "https://example.com/assets/file.zip", |
| 1000 | "{base_url} should join with a single slash" |
| 1001 | ); |
| 1002 | } |
| 1003 | assert_eq!(mirror_asset_url("", "file.zip"), "/file.zip"); |
| 1004 | } |
| 1005 | |
| 1006 | #[test] |
| 1007 | fn resolve_release_query_uses_github_without_overrides() { |
| 1008 | let _env = ReleaseEnvGuard::clear(); |
| 1009 | |
| 1010 | assert_eq!( |
| 1011 | resolve_release_query(ReleaseChannel::Stable), |
| 1012 | ReleaseQuery::GitHubLatest { |
| 1013 | url: LATEST_RELEASE_URL |
| 1014 | } |
| 1015 | ); |
| 1016 | assert_eq!( |
| 1017 | resolve_release_query(ReleaseChannel::Beta), |
| 1018 | ReleaseQuery::GitHubReleaseList { url: RELEASES_URL } |
| 1019 | ); |
| 1020 | } |
| 1021 | |
| 1022 | #[test] |
| 1023 | fn resolve_release_query_uses_release_base_url_overrides() { |
| 1024 | let default_version = env!("CARGO_PKG_VERSION").to_string(); |
| 1025 | |
| 1026 | for (env_name, expected_url) in [ |
| 1027 | (RELEASE_BASE_URL_ENV, "https://primary.example.com/mirror"), |
| 1028 | ( |
| 1029 | LEGACY_RELEASE_BASE_URL_ENV, |
| 1030 | "https://legacy.example.com/mirror", |
| 1031 | ), |
| 1032 | ( |
| 1033 | DEEPSEEK_RELEASE_BASE_URL_ENV, |
| 1034 | "https://deepseek.example.com/mirror", |
| 1035 | ), |
| 1036 | ] { |
| 1037 | let _env = ReleaseEnvGuard::clear(); |
| 1038 | set_release_env(env_name, expected_url); |
| 1039 | |
| 1040 | assert_eq!( |
| 1041 | resolve_release_query(ReleaseChannel::Stable), |
| 1042 | ReleaseQuery::Mirror { |
| 1043 | base_url: expected_url.to_string(), |
| 1044 | version: default_version.clone(), |
| 1045 | }, |
| 1046 | "{env_name} should drive mirror query" |
| 1047 | ); |
| 1048 | } |
| 1049 | } |
| 1050 | |
| 1051 | #[test] |
| 1052 | fn resolve_release_query_uses_cnb_mirror_override() { |
| 1053 | let _env = ReleaseEnvGuard::clear(); |
| 1054 | let default_version = env!("CARGO_PKG_VERSION").to_string(); |
| 1055 | set_release_env(CNB_MIRROR_ENV, "1"); |
| 1056 | |
| 1057 | assert_eq!( |
| 1058 | resolve_release_query(ReleaseChannel::Stable), |
| 1059 | ReleaseQuery::Mirror { |
| 1060 | base_url: cnb_release_base_url(&default_version), |
| 1061 | version: default_version, |
| 1062 | } |
| 1063 | ); |
| 1064 | } |
| 1065 | |
| 1066 | #[test] |
| 1067 | fn resolve_release_query_uses_pinned_release_versions_for_mirrors() { |
| 1068 | { |
| 1069 | let _env = ReleaseEnvGuard::clear(); |
| 1070 | set_release_env(RELEASE_BASE_URL_ENV, "https://example.com/mirror"); |
| 1071 | set_release_env(UPDATE_VERSION_ENV, "v1.2.3"); |
| 1072 | |
| 1073 | assert_eq!( |
| 1074 | resolve_release_query(ReleaseChannel::Stable), |
| 1075 | ReleaseQuery::Mirror { |
| 1076 | base_url: "https://example.com/mirror".to_string(), |
| 1077 | version: "1.2.3".to_string(), |
| 1078 | } |
| 1079 | ); |
| 1080 | } |
| 1081 | |
| 1082 | { |
| 1083 | let _env = ReleaseEnvGuard::clear(); |
| 1084 | set_release_env(RELEASE_BASE_URL_ENV, "https://example.com/mirror"); |
| 1085 | set_release_env(LEGACY_UPDATE_VERSION_ENV, "v1.2.3-legacy"); |
| 1086 | |
| 1087 | assert_eq!( |
| 1088 | resolve_release_query(ReleaseChannel::Stable), |
| 1089 | ReleaseQuery::Mirror { |
| 1090 | base_url: "https://example.com/mirror".to_string(), |
| 1091 | version: "1.2.3-legacy".to_string(), |
| 1092 | } |
| 1093 | ); |
| 1094 | } |
| 1095 | } |
| 1096 | |
| 1097 | #[test] |
| 1098 | fn cnb_release_base_url_includes_tag_directory() { |
| 1099 | assert_eq!( |
| 1100 | cnb_release_base_url("0.8.47"), |
| 1101 | "https://cnb.cool/codewhale.net/codewhale/-/releases/download/v0.8.47" |
| 1102 | ); |
| 1103 | assert_eq!( |
| 1104 | cnb_release_base_url("v0.8.47"), |
| 1105 | "https://cnb.cool/codewhale.net/codewhale/-/releases/download/v0.8.47" |
| 1106 | ); |
| 1107 | } |
| 1108 | |
| 1109 | #[test] |
| 1110 | fn stable_update_is_needed_only_when_latest_is_newer() { |
| 1111 | assert!(update_is_needed(ReleaseChannel::Stable, "0.8.45", "v0.8.46").unwrap()); |
| 1112 | assert!(update_is_needed(ReleaseChannel::Stable, "0.8.45", "v0.9.0-beta.1").unwrap()); |
| 1113 | assert!(!update_is_needed(ReleaseChannel::Stable, "0.8.45", "v0.8.45").unwrap()); |
| 1114 | assert!(!update_is_needed(ReleaseChannel::Stable, "0.9.0", "v0.9.0-beta.1").unwrap()); |
| 1115 | assert!( |
| 1116 | !update_is_needed(ReleaseChannel::Stable, "0.9.0-beta.2", "v0.9.0-beta.1").unwrap() |
| 1117 | ); |
| 1118 | } |
| 1119 | |
| 1120 | #[test] |
| 1121 | fn beta_update_allows_switching_from_same_stable_to_beta() { |
| 1122 | assert!(update_is_needed(ReleaseChannel::Beta, "1.0.0", "v1.0.0-beta.2").unwrap()); |
| 1123 | assert!(!update_is_needed(ReleaseChannel::Beta, "1.0.0-beta.2", "v1.0.0-beta.2").unwrap()); |
| 1124 | assert!(!update_is_needed(ReleaseChannel::Beta, "1.0.0-beta.3", "v1.0.0-beta.2").unwrap()); |
| 1125 | assert!(update_is_needed(ReleaseChannel::Beta, "1.0.0-beta.2", "v1.0.0-beta.3").unwrap()); |
| 1126 | assert!(!update_is_needed(ReleaseChannel::Beta, "2.0.0", "v1.0.0-beta.3").unwrap()); |
| 1127 | assert!(!update_is_needed(ReleaseChannel::Beta, "1.0.0-rc.1", "v1.0.0-beta.3").unwrap()); |
| 1128 | } |
| 1129 | |
| 1130 | #[test] |
| 1131 | fn parse_release_version_accepts_tags_and_build_suffixes() { |
| 1132 | assert_eq!( |
| 1133 | parse_release_version("v0.9.0-beta.1").unwrap(), |
| 1134 | semver::Version::parse("0.9.0-beta.1").unwrap() |
| 1135 | ); |
| 1136 | assert_eq!( |
| 1137 | parse_release_version("0.8.45 (abcdef123456)").unwrap(), |
| 1138 | semver::Version::parse("0.8.45").unwrap() |
| 1139 | ); |
| 1140 | } |
| 1141 | |
| 1142 | #[test] |
| 1143 | fn release_version_compare_ignores_v_prefix_and_build_sha() { |
| 1144 | assert_eq!( |
| 1145 | compare_release_versions("0.8.39 (eeccf7d)", "v0.8.39").unwrap(), |
| 1146 | std::cmp::Ordering::Equal |
| 1147 | ); |
| 1148 | assert_eq!( |
| 1149 | compare_release_versions("0.8.39", "v0.8.40").unwrap(), |
| 1150 | std::cmp::Ordering::Less |
| 1151 | ); |
| 1152 | assert_eq!( |
| 1153 | compare_release_versions("0.8.40", "v0.8.39").unwrap(), |
| 1154 | std::cmp::Ordering::Greater |
| 1155 | ); |
| 1156 | } |
| 1157 | |
| 1158 | #[test] |
| 1159 | fn latest_beta_tag_selects_first_beta_release() { |
| 1160 | let body = r#"[ |
| 1161 | { "tag_name": "v0.9.0" }, |
| 1162 | { "tag_name": "v0.9.0-rc.1" }, |
| 1163 | { "tag_name": "v0.9.0-beta.2" }, |
| 1164 | { "tag_name": "v0.9.0-beta.1" } |
| 1165 | ]"#; |
| 1166 | assert_eq!( |
| 1167 | latest_beta_tag_from_release_list_json(body).unwrap(), |
| 1168 | "v0.9.0-beta.2" |
| 1169 | ); |
| 1170 | } |
| 1171 | |
| 1172 | #[test] |
| 1173 | fn latest_beta_tag_reports_missing_beta() { |
| 1174 | let body = r#"[{ "tag_name": "v0.9.0" }]"#; |
| 1175 | let err = latest_beta_tag_from_release_list_json(body).expect_err("missing beta"); |
| 1176 | assert!( |
| 1177 | err.to_string().contains("no beta release found"), |
| 1178 | "unexpected error: {err:#}" |
| 1179 | ); |
| 1180 | } |
| 1181 | |
| 1182 | #[tokio::test] |
| 1183 | async fn fetch_release_json_async_refuses_http_and_unlisted_hosts_without_connecting() { |
| 1184 | let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind"); |
| 1185 | listener.set_nonblocking(true).expect("nonblocking"); |
| 1186 | let addr = listener.local_addr().expect("addr"); |
| 1187 | let plain_url = format!("http://{addr}/releases/latest"); |
| 1188 | let err = fetch_release_json_async(&plain_url, "latest release") |
| 1189 | .await |
| 1190 | .expect_err("plain HTTP must be refused"); |
| 1191 | assert!(format!("{err:#}").contains("HTTPS"), "{err:#}"); |
| 1192 | assert!(listener.accept().is_err(), "refused URL must not connect"); |
| 1193 | |
| 1194 | let closed_listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind"); |
| 1195 | let closed_addr = closed_listener.local_addr().expect("addr"); |
| 1196 | drop(closed_listener); |
| 1197 | let loopback_policy = UpdateTransportPolicy { |
| 1198 | extra_hosts: vec!["127.0.0.1".to_string()], |
| 1199 | allow_loopback_http: false, |
| 1200 | }; |
| 1201 | let secret_url = format!("https://user:secret@{closed_addr}/test"); |
| 1202 | let err = |
| 1203 | fetch_release_json_async_with_policy(&secret_url, "latest release", &loopback_policy) |
| 1204 | .await |
| 1205 | .expect_err("closed loopback HTTPS target must error without leaking userinfo"); |
| 1206 | let secret_err_text = format!("{err:#}"); |
| 1207 | assert!( |
| 1208 | secret_err_text.contains("failed to fetch"), |
| 1209 | "{secret_err_text}" |
| 1210 | ); |
| 1211 | assert!(!secret_err_text.contains("secret"), "{secret_err_text}"); |
| 1212 | assert!(!secret_err_text.contains("user:"), "{secret_err_text}"); |
| 1213 | |
| 1214 | let err = fetch_release_json_async( |
| 1215 | "http://user:secret@unlisted.example.test/releases/latest", |
| 1216 | "latest release", |
| 1217 | ) |
| 1218 | .await |
| 1219 | .expect_err("HTTP with userinfo must be refused"); |
| 1220 | let text = format!("{err:#}"); |
| 1221 | assert!(text.contains("HTTPS"), "{text}"); |
| 1222 | assert!(!text.contains("secret"), "{text}"); |
| 1223 | |
| 1224 | let err = fetch_release_json_async( |
| 1225 | "https://unlisted.example.test/releases/latest", |
| 1226 | "latest release", |
| 1227 | ) |
| 1228 | .await |
| 1229 | .expect_err("unlisted host must be refused"); |
| 1230 | assert!( |
| 1231 | format!("{err:#}").contains("not an allowed release host"), |
| 1232 | "{err:#}" |
| 1233 | ); |
| 1234 | } |
| 1235 | |
| 1236 | #[tokio::test] |
| 1237 | async fn release_http_client_refuses_redirect_to_http_or_unlisted_host() { |
| 1238 | use tokio::io::{AsyncReadExt, AsyncWriteExt}; |
| 1239 | |
| 1240 | let target_listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind"); |
| 1241 | target_listener.set_nonblocking(true).expect("nonblocking"); |
| 1242 | let target_url = format!( |
| 1243 | "http://{}/next", |
| 1244 | target_listener.local_addr().expect("addr") |
| 1245 | ); |
| 1246 | |
| 1247 | for location in [target_url.as_str(), "https://download.evil.example/next"] { |
| 1248 | let listener = tokio::net::TcpListener::bind("127.0.0.1:0") |
| 1249 | .await |
| 1250 | .expect("bind"); |
| 1251 | let addr = listener.local_addr().expect("addr"); |
| 1252 | let location = location.to_string(); |
| 1253 | let server = tokio::spawn(async move { |
| 1254 | let (mut stream, _) = listener.accept().await.expect("accept"); |
| 1255 | let mut buf = [0_u8; 2048]; |
| 1256 | let _ = stream.read(&mut buf).await.expect("read"); |
| 1257 | let reply = format!( |
| 1258 | "HTTP/1.1 302 Found\r\nLocation: {location}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n" |
| 1259 | ); |
| 1260 | stream.write_all(reply.as_bytes()).await.expect("write"); |
| 1261 | }); |
| 1262 | |
| 1263 | let client = |
| 1264 | release_http_client(Duration::from_secs(5), &UpdateTransportPolicy::strict()) |
| 1265 | .expect("client"); |
| 1266 | let err = client |
| 1267 | .get(format!("http://{addr}/start")) |
| 1268 | .send() |
| 1269 | .await |
| 1270 | .expect_err("redirect must be refused"); |
| 1271 | let mut text = err.to_string(); |
| 1272 | let mut source = std::error::Error::source(&err); |
| 1273 | while let Some(cause) = source { |
| 1274 | text.push_str(&format!(": {cause}")); |
| 1275 | source = cause.source(); |
| 1276 | } |
| 1277 | assert!(text.contains("update redirect refused"), "{text}"); |
| 1278 | server.await.expect("server task"); |
| 1279 | } |
| 1280 | |
| 1281 | assert!( |
| 1282 | target_listener.accept().is_err(), |
| 1283 | "refused redirect target must never be contacted" |
| 1284 | ); |
| 1285 | } |
| 1286 | } |
| 1287 |