Skip to main content

rpi_cli/
updates.rs

1//! Lightweight update discovery and update commands.
2//!
3//! Startup checks are deliberately best-effort: callers decide when to run
4//! them, each registry request uses a short timeout, and cached values are
5//! retained only as a fallback for temporary registry failures.
6
7use std::collections::{BTreeMap, BTreeSet};
8use std::fs::{File, OpenOptions};
9use std::future::Future;
10use std::path::{Path, PathBuf};
11#[cfg(windows)]
12use std::process::Stdio;
13use std::time::{SystemTime, UNIX_EPOCH};
14
15use futures::{stream, StreamExt};
16use serde::{Deserialize, Serialize};
17
18const CACHE_FILE: &str = "update-check.json";
19const CACHE_FALLBACK_MAX_AGE_MS: i64 = 6 * 60 * 60 * 1000;
20const REQUEST_TIMEOUT_MS: u64 = 1800;
21const UPDATE_CHECK_CONCURRENCY: usize = 4;
22const GITHUB_RELEASES_API: &str =
23    "https://api.github.com/repos/bigfish1913/pi-rust/releases?per_page=100";
24/// The single-release endpoint for the newest non-draft, non-prerelease tag.
25/// Authoritative version source for the stable CLI channel.
26const GITHUB_RELEASES_LATEST_API: &str =
27    "https://api.github.com/repos/bigfish1913/pi-rust/releases/latest";
28const STAGED_RPI_CHECK_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);
29const MAX_STAGED_RPI_OUTPUT_BYTES: usize = 4 * 1024;
30const MAX_SELF_UPDATE_STATUS_BYTES: u64 = 64 * 1024;
31const MAX_SELF_UPDATE_STATUS_MESSAGE_CHARS: usize = 2 * 1024;
32/// How long a running self-update may stay in a non-terminal state before a
33/// later process treats it as debris and prunes it. A `cargo install` compiles
34/// from source, so the window is generous; a helper that outlives it is stuck,
35/// not slow.
36const STALE_SELF_UPDATE_STATUS_TTL_MS: i64 = 60 * 60 * 1000;
37/// How long a completed update keeps its status record. `rpi update` prints
38/// that path, so the file has to outlive the command that named it by long
39/// enough to actually be read; after that it is just clutter.
40const COMPLETED_SELF_UPDATE_STATUS_TTL_MS: i64 = 24 * 60 * 60 * 1000;
41static SELF_UPDATE_STATUS_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
42
43#[derive(Debug, Clone, PartialEq, Eq)]
44pub struct UpdateNotice {
45    pub name: String,
46    pub current: String,
47    pub latest: String,
48    pub command: String,
49}
50
51#[derive(Debug, Clone, PartialEq, Eq)]
52pub struct UpdateWarning {
53    pub message: String,
54    pub command: String,
55}
56
57#[derive(Debug, Clone, Default, PartialEq, Eq)]
58pub struct UpdateReport {
59    pub notices: Vec<UpdateNotice>,
60    pub warnings: Vec<UpdateWarning>,
61}
62
63impl UpdateReport {
64    pub fn is_empty(&self) -> bool {
65        self.notices.is_empty() && self.warnings.is_empty()
66    }
67}
68
69#[derive(Debug, Clone, Serialize, Deserialize, Default)]
70#[serde(rename_all = "camelCase")]
71struct UpdateCache {
72    /// Legacy aggregate timestamp retained for backward-compatible cache reads.
73    checked_at: i64,
74    #[serde(default)]
75    last_successful_check_at: i64,
76    rpi_latest: Option<String>,
77    #[serde(default)]
78    native_packages: BTreeMap<String, String>,
79    #[serde(default)]
80    freshness: UpdateCacheFreshness,
81}
82
83#[derive(Debug, Clone, Serialize, Deserialize, Default)]
84#[serde(rename_all = "camelCase")]
85struct UpdateCacheFreshness {
86    rpi: i64,
87    #[serde(default)]
88    native_packages: BTreeMap<String, i64>,
89}
90
91type RegistryCacheUpdate = (BTreeMap<String, String>, BTreeMap<String, i64>);
92
93#[derive(Debug, Deserialize)]
94struct CratesResponse {
95    #[serde(rename = "crate")]
96    crate_info: CrateInfo,
97}
98
99#[derive(Debug, Deserialize)]
100struct CrateInfo {
101    max_version: String,
102}
103
104#[derive(Debug, Deserialize)]
105struct GithubRelease {
106    tag_name: String,
107    #[serde(default)]
108    draft: bool,
109    #[serde(default)]
110    prerelease: bool,
111}
112
113#[derive(Debug, Clone, Copy, PartialEq, Eq)]
114enum UpdateChannel {
115    Stable,
116    Preview,
117}
118
119const HOMEBREW_UPGRADE_COMMAND: &str = "brew upgrade rpi";
120
121fn current_homebrew_keg() -> Option<PathBuf> {
122    homebrew_keg_for_exe(&std::env::current_exe().ok()?)
123}
124
125/// Resolve Homebrew's `bin/rpi` symlink to `Cellar/rpi/<version>/bin/rpi`.
126/// The receipt distinguishes a Homebrew keg from a similarly named directory.
127fn homebrew_keg_for_exe(exe: &Path) -> Option<PathBuf> {
128    let exe = exe.canonicalize().ok()?;
129    let bin = exe.parent()?;
130    let keg = bin.parent()?;
131    let formula = keg.parent()?;
132    if exe.file_name()? == crate::APP_NAME
133        && bin.file_name()? == "bin"
134        && formula.file_name()? == crate::APP_NAME
135        && formula.parent()?.file_name()? == "Cellar"
136        && keg.join("INSTALL_RECEIPT.json").is_file()
137    {
138        return Some(keg.to_path_buf());
139    }
140    None
141}
142
143#[derive(Debug, Deserialize)]
144#[serde(rename_all = "camelCase")]
145struct SelfUpdateStatus {
146    state: String,
147    #[serde(default)]
148    message: String,
149    /// The staging directory this update was installed into. Written by the
150    /// Windows helper; the older `preparing` records lack it, which is why an
151    /// unmapped staging directory is aged out instead of matched by name.
152    #[serde(default)]
153    staging: Option<PathBuf>,
154    #[serde(default)]
155    updated_at_ms: i64,
156}
157
158#[derive(Debug, Clone, PartialEq, Eq)]
159enum RegistryLookup {
160    Found(String),
161    Missing,
162    TransientFailure,
163}
164
165/// Best-effort startup check for the rpi release and installed Rust extensions.
166pub async fn check_startup(cwd: &Path) -> UpdateReport {
167    let _ = cwd;
168    check_rpi_startup().await
169}
170
171/// Check the rpi release and every installed Rust cdylib extension.
172///
173/// Native-only: the npm/Git package halves of the old scope went away with the
174/// Pi compatibility layer, so this never shells out to a package manager.
175pub async fn check_rpi_startup() -> UpdateReport {
176    if update_checks_disabled() {
177        return report_without_remote_checks();
178    }
179    check_startup_with_client(startup_http_client()).await
180}
181
182fn update_checks_disabled() -> bool {
183    crate::args::offline_env_enabled() || std::env::var_os("RPI_DISABLE_UPDATE_CHECK").is_some()
184}
185
186/// Report the outcome of a self-update that ran in a previous process.
187fn report_without_remote_checks() -> UpdateReport {
188    let warnings = crate::config::agent_dir()
189        .ok()
190        .map(|agent_dir| consume_self_update_statuses(&agent_dir))
191        .unwrap_or_default();
192    UpdateReport {
193        notices: Vec::new(),
194        warnings,
195    }
196}
197
198fn startup_http_client() -> Option<reqwest::Client> {
199    let mut builder = reqwest::Client::builder()
200        .timeout(std::time::Duration::from_millis(REQUEST_TIMEOUT_MS))
201        .user_agent(format!("rpi/{}", crate::VERSION));
202    // The saved Web proxy is a fallback for this client. Keep explicit
203    // environment settings and leave the process environment alone.
204    if let Some(saved) = crate::settings::load_settings()
205        .ok()
206        .and_then(|settings| settings.http_proxy)
207    {
208        let configured_proxy = |upper, lower, parse: fn(String) -> Result<_, _>| {
209            [upper, lower, "ALL_PROXY", "all_proxy"]
210                .into_iter()
211                .filter_map(|key| std::env::var(key).ok())
212                .chain([saved.clone()])
213                .filter(|url| !url.is_empty())
214                .find_map(|url| parse(url).ok())
215        };
216        let no_proxy = reqwest::NoProxy::from_env();
217        // Update endpoints use HTTPS. An unusable HTTP proxy must not disable
218        // that route, and an unusable HTTPS route must not fall back to direct.
219        let https = configured_proxy("HTTPS_PROXY", "https_proxy", reqwest::Proxy::https)?;
220        if let Some(http) = configured_proxy("HTTP_PROXY", "http_proxy", reqwest::Proxy::http) {
221            builder = builder.proxy(http.no_proxy(no_proxy.clone()));
222        }
223        builder = builder.proxy(https.no_proxy(no_proxy));
224    }
225    builder.build().ok()
226}
227
228async fn check_startup_with_client(client: Option<reqwest::Client>) -> UpdateReport {
229    let agent_dir = match crate::config::agent_dir() {
230        Ok(dir) => dir,
231        Err(_) => return UpdateReport::default(),
232    };
233    let warnings = consume_self_update_statuses(&agent_dir);
234    let cache = refresh_update_cache(&agent_dir, client).await;
235    let mut report = report_from_cache(&cache);
236    report.warnings = warnings;
237    report
238}
239
240async fn refresh_update_cache(agent_dir: &Path, client: Option<reqwest::Client>) -> UpdateCache {
241    let cache_path = agent_dir.join(CACHE_FILE);
242
243    // Installed Rust extensions come from `rpi install`'s registry, so this
244    // path stays independent of any Pi package resource discovery.
245    let native_checks = crate::install::installed_native_packages()
246        .into_iter()
247        .filter(|package| package.supports_registry_update())
248        .map(|package| {
249            let client = client.clone();
250            async move {
251                let latest = match client.as_ref() {
252                    Some(client) if package.prebuilt.is_some() => {
253                        match crate::prebuilt_extensions::latest_compatible_version(
254                            client, &package,
255                        )
256                        .await
257                        {
258                            Ok(Some(version)) => RegistryLookup::Found(version),
259                            Ok(None) => RegistryLookup::Missing,
260                            Err(_) => RegistryLookup::TransientFailure,
261                        }
262                    }
263                    Some(client) => fetch_crates_latest(client, &package.name).await,
264                    None => RegistryLookup::TransientFailure,
265                };
266                (native_cache_key(&package), latest)
267            }
268        });
269    let rpi_check = async {
270        match client.as_ref() {
271            Some(client) => fetch_rpi_latest(client).await,
272            None => RegistryLookup::TransientFailure,
273        }
274    };
275    let (rpi_result, native_results) = tokio::join!(rpi_check, collect_bounded(native_checks));
276
277    merge_and_write_cache(&cache_path, rpi_result, native_results)
278}
279
280async fn collect_bounded<I, F, T>(checks: I) -> Vec<T>
281where
282    I: IntoIterator<Item = F>,
283    F: Future<Output = T>,
284{
285    stream::iter(checks)
286        .buffer_unordered(UPDATE_CHECK_CONCURRENCY)
287        .collect()
288        .await
289}
290
291fn rpi_cache_checked_at(cache: &UpdateCache) -> i64 {
292    if cache.freshness.rpi > 0 {
293        cache.freshness.rpi
294    } else {
295        cache.checked_at
296    }
297}
298
299fn entry_cache_checked_at(
300    freshness: Option<&BTreeMap<String, i64>>,
301    key: &str,
302    legacy_checked_at: i64,
303) -> i64 {
304    freshness
305        .and_then(|values| values.get(key).copied())
306        .filter(|checked_at| *checked_at > 0)
307        .unwrap_or(legacy_checked_at)
308}
309
310fn timestamp_is_fresh(checked_at: i64, now: i64) -> bool {
311    let age = now.saturating_sub(checked_at);
312    checked_at > 0 && (0..=CACHE_FALLBACK_MAX_AGE_MS).contains(&age)
313}
314
315fn resolved_checked_at(
316    value: Option<&str>,
317    used_fallback: bool,
318    cached_at: i64,
319    checked_at: i64,
320) -> i64 {
321    if value.is_none() {
322        0
323    } else if used_fallback {
324        cached_at
325    } else {
326        checked_at
327    }
328}
329
330fn results_with_individual_cache_fallback(
331    results: Vec<(String, RegistryLookup)>,
332    cached: Option<&BTreeMap<String, String>>,
333    freshness: Option<&BTreeMap<String, i64>>,
334    legacy_checked_at: i64,
335    checked_at: i64,
336) -> RegistryCacheUpdate {
337    let mut values = BTreeMap::new();
338    let mut checked_at_values = BTreeMap::new();
339    for (name, result) in results {
340        let cached_value = cached.and_then(|cached| cached.get(&name).map(String::as_str));
341        let cached_at = entry_cache_checked_at(freshness, &name, legacy_checked_at);
342        let (latest, used_fallback) = lookup_with_cache_fallback(
343            result,
344            cached_value,
345            timestamp_is_fresh(cached_at, checked_at),
346        );
347        if let Some(latest) = latest {
348            checked_at_values.insert(
349                name.clone(),
350                resolved_checked_at(Some(&latest), used_fallback, cached_at, checked_at),
351            );
352            values.insert(name, latest);
353        }
354    }
355    (values, checked_at_values)
356}
357
358fn merge_and_write_cache(
359    path: &Path,
360    rpi_result: RegistryLookup,
361    native_results: Vec<(String, RegistryLookup)>,
362) -> UpdateCache {
363    let lock = try_lock_update_cache(path);
364    // A different refresh can publish while this one is awaiting registry
365    // replies. Resolve fallback against the cache that exists at commit time.
366    let mut cache = read_cache(path).unwrap_or_default();
367    let checked_at = now_ms();
368    let checked_successfully = !matches!(rpi_result, RegistryLookup::TransientFailure)
369        || native_results
370            .iter()
371            .any(|(_, result)| !matches!(result, RegistryLookup::TransientFailure));
372    let cached_at = rpi_cache_checked_at(&cache);
373    let (latest, used_fallback) = lookup_with_cache_fallback(
374        rpi_result,
375        cache.rpi_latest.as_deref(),
376        timestamp_is_fresh(cached_at, checked_at),
377    );
378    let (native_packages, native_freshness) = results_with_individual_cache_fallback(
379        native_results,
380        Some(&cache.native_packages),
381        Some(&cache.freshness.native_packages),
382        cache.checked_at,
383        checked_at,
384    );
385    // Preserve the newest legacy observation even when an entry expires or
386    // is removed. A failed refresh does not count as a registry observation.
387    cache.last_successful_check_at = last_successful_update_check(&cache);
388    if checked_successfully {
389        cache.last_successful_check_at = cache.last_successful_check_at.max(checked_at);
390        if cache.checked_at <= 0 {
391            cache.checked_at = checked_at;
392        }
393    }
394    cache.freshness.rpi =
395        resolved_checked_at(latest.as_deref(), used_fallback, cached_at, checked_at);
396    cache.rpi_latest = latest;
397    cache.native_packages = native_packages;
398    cache.freshness.native_packages = native_freshness;
399    if lock.is_some() {
400        let _ = write_cache(path, &cache);
401    }
402    cache
403}
404
405struct UpdateCacheLock(File);
406
407impl Drop for UpdateCacheLock {
408    fn drop(&mut self) {
409        // A concurrent fork can briefly retain the descriptor until exec.
410        let _ = fs2::FileExt::unlock(&self.0);
411    }
412}
413
414fn try_lock_update_cache(path: &Path) -> Option<UpdateCacheLock> {
415    std::fs::create_dir_all(path.parent()?).ok()?;
416    // A sibling lock stays valid when atomic_write replaces the cache file.
417    // A busy cache can be read immediately and this refresh can skip writing.
418    let file = OpenOptions::new()
419        .read(true)
420        .write(true)
421        .create(true)
422        .truncate(false)
423        .open(path.with_extension("lock"))
424        .ok()?;
425    fs2::FileExt::try_lock_exclusive(&file).ok()?;
426    Some(UpdateCacheLock(file))
427}
428
429fn last_successful_update_check(cache: &UpdateCache) -> i64 {
430    [
431        cache.last_successful_check_at,
432        cache.checked_at,
433        cache.freshness.rpi,
434    ]
435    .into_iter()
436    .chain(cache.freshness.native_packages.values().copied())
437    .max()
438    .unwrap_or_default()
439}
440
441fn lookup_with_cache_fallback(
442    result: RegistryLookup,
443    cached: Option<&str>,
444    fallback_allowed: bool,
445) -> (Option<String>, bool) {
446    match result {
447        RegistryLookup::Found(version) => (Some(version), false),
448        RegistryLookup::Missing => (None, false),
449        RegistryLookup::TransientFailure if fallback_allowed => {
450            (cached.map(str::to_owned), cached.is_some())
451        }
452        RegistryLookup::TransientFailure => (None, false),
453    }
454}
455fn native_cache_key(package: &crate::install::InstalledNativePackage) -> String {
456    match &package.prebuilt {
457        Some(source) => format!(
458            "prebuilt:{}:{}#{}:{}",
459            if source.custom_repository {
460                "github"
461            } else {
462                "crates"
463            },
464            source.repository,
465            package.name,
466            source.target
467        ),
468        None => package.name.clone(),
469    }
470}
471
472fn report_from_cache(cache: &UpdateCache) -> UpdateReport {
473    let mut notices = Vec::new();
474    if let Some(latest) = cache.rpi_latest.as_deref() {
475        if is_newer(crate::VERSION, latest) {
476            notices.push(UpdateNotice {
477                name: "rpi".into(),
478                current: crate::VERSION.into(),
479                latest: latest.into(),
480                command: if current_homebrew_keg().is_some() {
481                    HOMEBREW_UPGRADE_COMMAND.into()
482                } else {
483                    "rpi update".into()
484                },
485            });
486        }
487    }
488    for package in crate::install::installed_native_packages() {
489        if !package.supports_registry_update() {
490            continue;
491        }
492        let Some(latest) = cache.native_packages.get(&native_cache_key(&package)) else {
493            continue;
494        };
495        if is_newer(&package.version, latest) {
496            notices.push(UpdateNotice {
497                name: package.name.clone(),
498                current: package.version,
499                latest: latest.clone(),
500                command: format!("rpi extension update {}", package.name),
501            });
502        }
503    }
504    UpdateReport {
505        notices,
506        warnings: Vec::new(),
507    }
508}
509
510fn normalize_windows_path(path: PathBuf) -> PathBuf {
511    if cfg!(windows) {
512        let text = path.to_string_lossy();
513        if let Some(unc) = text.strip_prefix(r"\\?\UNC\") {
514            return PathBuf::from(format!(r"\\{unc}"));
515        }
516        if let Some(local) = text.strip_prefix(r"\\?\") {
517            return PathBuf::from(local);
518        }
519    }
520    path
521}
522
523fn windows_paths_equal(left: &Path, right: &Path) -> bool {
524    let left = normalize_windows_path(left.to_path_buf());
525    let right = normalize_windows_path(right.to_path_buf());
526    if cfg!(windows) {
527        left.to_string_lossy()
528            .replace('/', "\\")
529            .eq_ignore_ascii_case(&right.to_string_lossy().replace('/', "\\"))
530    } else {
531        left == right
532    }
533}
534
535async fn fetch_rpi_latest(client: &reqwest::Client) -> RegistryLookup {
536    fetch_stable_from_github(client, GITHUB_RELEASES_LATEST_API).await
537}
538
539/// The stable version a `/releases/latest` body names, or `None` when the body
540/// is not a usable stable release.
541///
542/// `/releases/latest` already excludes drafts and prereleases, but the flags are
543/// re-checked here so a GitHub API behaviour change cannot silently hand the
544/// stable channel a prerelease. This is deliberately separate from
545/// `latest_preview_version`, which selects prereleases from the full list.
546fn stable_version_from_release(release: &GithubRelease) -> Option<String> {
547    if release.prerelease || release.draft {
548        return None;
549    }
550    let version = release.tag_name.strip_prefix('v')?;
551    let parsed = semver::Version::parse(version).ok()?;
552    parsed.pre.is_empty().then(|| version.to_string())
553}
554
555async fn fetch_stable_from_github(client: &reqwest::Client, url: &str) -> RegistryLookup {
556    let response = match client
557        .get(url)
558        .header(reqwest::header::ACCEPT, "application/vnd.github+json")
559        .send()
560        .await
561    {
562        Ok(response) => response,
563        Err(_) => return RegistryLookup::TransientFailure,
564    };
565    // Missing, unavailable or malformed release metadata must not invalidate
566    // a fresh cached answer. A release may be temporarily unavailable while
567    // publishing; offline/cache age policy stays with the caller.
568    if !response.status().is_success() {
569        return RegistryLookup::TransientFailure;
570    }
571    let release = match response.json::<GithubRelease>().await {
572        Ok(release) => release,
573        Err(_) => return RegistryLookup::TransientFailure,
574    };
575    // A body that is not a usable stable release is an unanswered lookup too,
576    // for the same reason: keep a fresh cache able to serve the request.
577    match stable_version_from_release(&release) {
578        Some(version) => RegistryLookup::Found(version),
579        None => RegistryLookup::TransientFailure,
580    }
581}
582
583fn latest_preview_version(releases: impl IntoIterator<Item = GithubRelease>) -> RegistryLookup {
584    releases
585        .into_iter()
586        .filter(|release| release.prerelease && !release.draft)
587        .filter_map(|release| {
588            let version = release.tag_name.strip_prefix('v')?.to_string();
589            let parsed = semver::Version::parse(&version).ok()?;
590            (!parsed.pre.is_empty()).then_some((parsed, version))
591        })
592        .max_by(|left, right| left.0.cmp(&right.0))
593        .map(|(_, version)| RegistryLookup::Found(version))
594        .unwrap_or(RegistryLookup::Missing)
595}
596
597async fn fetch_rpi_preview_latest(client: &reqwest::Client) -> RegistryLookup {
598    let response = match client
599        .get(GITHUB_RELEASES_API)
600        .header(reqwest::header::ACCEPT, "application/vnd.github+json")
601        .send()
602        .await
603    {
604        Ok(response) => response,
605        Err(_) => return RegistryLookup::TransientFailure,
606    };
607    if response.status() == reqwest::StatusCode::NOT_FOUND {
608        return RegistryLookup::Missing;
609    }
610    if !response.status().is_success() {
611        return RegistryLookup::TransientFailure;
612    }
613    let releases = match response.json::<Vec<GithubRelease>>().await {
614        Ok(releases) => releases,
615        Err(_) => return RegistryLookup::TransientFailure,
616    };
617    latest_preview_version(releases)
618}
619
620async fn fetch_crates_latest(client: &reqwest::Client, name: &str) -> RegistryLookup {
621    fetch_crates_url(client, &format!("https://crates.io/api/v1/crates/{name}")).await
622}
623
624async fn fetch_crates_url(client: &reqwest::Client, url: &str) -> RegistryLookup {
625    let response = match client.get(url).send().await {
626        Ok(response) => response,
627        Err(_) => return RegistryLookup::TransientFailure,
628    };
629    if matches!(
630        response.status(),
631        reqwest::StatusCode::NOT_FOUND | reqwest::StatusCode::GONE
632    ) {
633        return RegistryLookup::Missing;
634    }
635    if !response.status().is_success() {
636        return RegistryLookup::TransientFailure;
637    }
638    match response.json::<CratesResponse>().await {
639        Ok(response) => RegistryLookup::Found(response.crate_info.max_version),
640        Err(_) => RegistryLookup::TransientFailure,
641    }
642}
643
644/// Compare complete semantic versions, including prerelease precedence.
645pub fn is_newer(current: &str, latest: &str) -> bool {
646    let parse = |value: &str| semver::Version::parse(value.trim().trim_start_matches('v')).ok();
647    match (parse(current), parse(latest)) {
648        (Some(current), Some(latest)) => latest.cmp_precedence(&current).is_gt(),
649        _ => false,
650    }
651}
652
653fn read_cache(path: &Path) -> Option<UpdateCache> {
654    serde_json::from_str(&std::fs::read_to_string(path).ok()?).ok()
655}
656
657fn write_cache(path: &Path, cache: &UpdateCache) -> Result<(), String> {
658    if let Some(parent) = path.parent() {
659        std::fs::create_dir_all(parent).map_err(|error| error.to_string())?;
660    }
661    let data = serde_json::to_vec_pretty(cache).map_err(|error| error.to_string())?;
662    crate::config::atomic_write(path, &data).map_err(|error| error.to_string())
663}
664
665fn now_ms() -> i64 {
666    SystemTime::now()
667        .duration_since(UNIX_EPOCH)
668        .map(|duration| duration.as_millis() as i64)
669        .unwrap_or(0)
670}
671
672pub fn print_startup_notices(report: &UpdateReport) {
673    for warning in &report.warnings {
674        eprintln!("warning: {} Run `{}`.", warning.message, warning.command);
675    }
676    for notice in &report.notices {
677        eprintln!(
678            "Update available: {} {} -> {}. Run `{}`.",
679            notice.name, notice.current, notice.latest, notice.command
680        );
681    }
682}
683
684#[derive(Debug, Clone, PartialEq, Eq)]
685enum SelfUpdateArgs {
686    Help,
687    Run {
688        force: bool,
689        build: bool,
690        channel: UpdateChannel,
691        cdn_base: Option<reqwest::Url>,
692    },
693    Usage,
694}
695
696/// Parse `rpi update`'s own arguments after the global `--offline` flag has been
697/// stripped.
698fn parse_self_update_args(args: &[String]) -> SelfUpdateArgs {
699    let mut force = false;
700    let mut build = false;
701    let mut channel = UpdateChannel::Stable;
702    let mut cdn = None;
703    let mut i = 0;
704    while i < args.len() {
705        match args[i].as_str() {
706            "--help" | "-h" => return SelfUpdateArgs::Help,
707            "--force" | "-f" => force = true,
708            "--build" => build = true,
709            "--cdn" => {
710                i += 1;
711                let Some(value) = args.get(i).filter(|value| !value.starts_with('-')) else {
712                    return SelfUpdateArgs::Usage;
713                };
714                cdn = Some(value.as_str());
715            }
716            "preview" if channel == UpdateChannel::Stable => channel = UpdateChannel::Preview,
717            _ => return SelfUpdateArgs::Usage,
718        }
719        i += 1;
720    }
721    let cdn_base = match crate::cdn::resolve_base(cdn) {
722        Ok(base) => base,
723        Err(_) => return SelfUpdateArgs::Usage,
724    };
725    SelfUpdateArgs::Run {
726        force,
727        build,
728        channel,
729        cdn_base,
730    }
731}
732
733fn print_self_update_help() {
734    println!(
735        "Usage: rpi update [preview] [--force] [--offline] [--build] [--cdn <URL>]\n\n\
736         Update the rpi CLI using verified GitHub prebuilt releases.\n\
737         The optional `preview` channel installs the latest GitHub prerelease;\n\
738         it is never selected by the normal update check.\n\n\
739         Options:\n  \
740         preview    use the GitHub prerelease channel instead of stable releases\n  \
741         --build    explicitly compile with Cargo instead of downloading a prebuilt binary\n  \
742         --force    reinstall even when this rpi is already the latest release\n  \
743         --offline  do not touch the network; report the last known answer only\n\n\
744         A Homebrew install is upgraded with `brew upgrade rpi`; `rpi update`\n\
745         refuses to overwrite the binary Homebrew owns."
746    );
747}
748
749/// The latest release this process already knows about.
750///
751/// `registry_lookup: true` means a live request just answered *in this process*
752/// from the official GitHub release channel, so using it to short-circuit
753/// cannot hide a newer release. A value read from the
754/// 6-hour cache is only trusted for the offline report, where there is no
755/// alternative and the output says so.
756fn known_latest_rpi(registry_lookup: Option<&str>, cached: Option<&str>) -> Option<(String, bool)> {
757    registry_lookup
758        .map(|latest| (latest.to_string(), false))
759        .or_else(|| cached.map(|latest| (latest.to_string(), true)))
760}
761
762async fn lookup_latest_rpi() -> Option<(String, bool)> {
763    lookup_latest_rpi_from(GITHUB_RELEASES_LATEST_API).await
764}
765
766/// Resolve the latest stable version and report whether it came from a live
767/// answer.
768///
769/// The endpoint is a parameter so the whole decision — including `verified`
770/// and the cache fallback — can be exercised offline.
771async fn lookup_latest_rpi_from(github_latest_url: &str) -> Option<(String, bool)> {
772    let cache_path = crate::config::agent_dir()
773        .ok()
774        .map(|dir| dir.join(CACHE_FILE));
775    let cached = cache_path.as_deref().and_then(read_cache);
776    let result = match reqwest::Client::builder()
777        .timeout(std::time::Duration::from_secs(15))
778        .user_agent(format!("rpi/{}", crate::VERSION))
779        .build()
780    {
781        Ok(client) => fetch_stable_from_github(&client, github_latest_url).await,
782        Err(_) => RegistryLookup::TransientFailure,
783    };
784    // Only a live answer from an authoritative source counts as verified; a
785    // value that came back from the cache means every request failed and the
786    // version is up to six hours old. Only GitHub supplies live CLI versions.
787    let verified = matches!(result, RegistryLookup::Found(_));
788    let previous = cached
789        .as_ref()
790        .filter(|cache| timestamp_is_fresh(rpi_cache_checked_at(cache), now_ms()))
791        .and_then(|cache| cache.rpi_latest.as_deref());
792    let (latest, _) = lookup_with_cache_fallback(result, previous, true);
793    latest.map(|latest| (latest, verified))
794}
795
796/// `rpi update` is synchronous, so its registry lookup runs on its own thread and
797/// current-thread runtime. That also keeps it safe to call from inside a Tokio
798/// runtime, which is where the CLI enters it.
799fn lookup_latest_rpi_blocking() -> Option<(String, bool)> {
800    std::thread::Builder::new()
801        .name("rpi-update-latest-lookup".to_string())
802        .spawn(|| {
803            let runtime = tokio::runtime::Builder::new_current_thread()
804                .enable_all()
805                .build()
806                .ok()?;
807            runtime.block_on(lookup_latest_rpi())
808        })
809        .ok()?
810        .join()
811        .ok()?
812}
813
814async fn lookup_latest_preview() -> Option<(String, bool)> {
815    let result = match reqwest::Client::builder()
816        .timeout(std::time::Duration::from_secs(15))
817        .user_agent(format!("rpi/{}", crate::VERSION))
818        .build()
819    {
820        Ok(client) => fetch_rpi_preview_latest(&client).await,
821        Err(_) => RegistryLookup::TransientFailure,
822    };
823    let verified = matches!(result, RegistryLookup::Found(_));
824    match result {
825        RegistryLookup::Found(version) => Some((version, verified)),
826        _ => None,
827    }
828}
829
830fn lookup_latest_preview_blocking() -> Option<(String, bool)> {
831    std::thread::Builder::new()
832        .name("rpi-update-preview-lookup".to_string())
833        .spawn(|| {
834            let runtime = tokio::runtime::Builder::new_current_thread()
835                .enable_all()
836                .build()
837                .ok()?;
838            runtime.block_on(lookup_latest_preview())
839        })
840        .ok()?
841        .join()
842        .ok()?
843}
844
845/// The newest version already staged in a `pending-*` directory.
846///
847/// A staged update is a fully validated binary waiting for the running process
848/// to exit. Re-running `rpi update` while one is queued must not start a second
849/// compile, so the staged version joins the up-to-date comparison.
850fn staged_pending_version(update_root: &Path, channel: UpdateChannel) -> Option<semver::Version> {
851    let entries = std::fs::read_dir(update_root).ok()?;
852    let mut newest: Option<semver::Version> = None;
853    for entry in entries.flatten() {
854        let name = entry.file_name();
855        let Some(name) = name.to_str() else {
856            continue;
857        };
858        let Some(suffix) = name.strip_prefix("pending-") else {
859            continue;
860        };
861        // `tempfile` builds the name from `[A-Za-z0-9]`; anything else is not
862        // ours, so it is left alone rather than probed.
863        if suffix.is_empty() || !suffix.bytes().all(|byte| byte.is_ascii_alphanumeric()) {
864            continue;
865        }
866        let staging = update_root.join(name);
867        if validated_real_directory(&staging, "self-update staging directory").is_err() {
868            continue;
869        }
870        let Ok(version) = validate_rpi_executable_version(
871            &staging.join("bin").join(staged_rpi_file_name()),
872            update_root,
873            crate::VERSION,
874            "staged rpi",
875        ) else {
876            continue;
877        };
878        if (channel == UpdateChannel::Stable && !version.pre.is_empty())
879            || (channel == UpdateChannel::Preview && version.pre.is_empty())
880        {
881            continue;
882        }
883        if newest.as_ref().is_none_or(|newest| version > *newest) {
884            newest = Some(version);
885        }
886    }
887    newest
888}
889
890fn staged_rpi_file_name() -> &'static str {
891    if cfg!(windows) {
892        "rpi.exe"
893    } else {
894        crate::APP_NAME
895    }
896}
897
898/// Reclaim debris and surface a previous run's failure, without a network
899/// round trip.
900///
901/// `rpi update` is the command that creates `self-update` records and staging
902/// directories, so it is also the right place to clean them up: leaving it to
903/// the startup check means a machine that only ever runs `rpi chat` keeps the
904/// debris from every interrupted update until the next start.
905fn reclaim_self_update_artifacts() {
906    let Ok(agent_dir) = crate::config::agent_dir() else {
907        return;
908    };
909    for warning in consume_self_update_statuses(&agent_dir) {
910        eprintln!("warning: {} Run `{}`.", warning.message, warning.command);
911    }
912}
913
914/// Download a verified CLI release by default; --build explicitly selects Cargo.
915/// Both paths use the same staging validation and transactional replacement.
916pub fn run_self_update(args: &[String]) -> i32 {
917    let offline = crate::args::normalize_offline_mode(args);
918    let args = crate::args::without_offline_flag(args);
919    let (force, build, channel, cdn_base) = match parse_self_update_args(&args) {
920        SelfUpdateArgs::Help => {
921            print_self_update_help();
922            return 0;
923        }
924        SelfUpdateArgs::Run {
925            force,
926            build,
927            channel,
928            cdn_base,
929        } => (force, build, channel, cdn_base),
930        SelfUpdateArgs::Usage => {
931            eprintln!(
932                "error: `rpi update` accepts only `preview`, `--force`, `--offline`, `--build` and `--cdn <URL>`"
933            );
934            return 2;
935        }
936    };
937
938    if let Some(keg) = current_homebrew_keg() {
939        eprintln!(
940            "error: Homebrew manages this rpi installation ({}).\n\
941             Run `{HOMEBREW_UPGRADE_COMMAND}` to update it.",
942            keg.display()
943        );
944        return 1;
945    }
946
947    if offline {
948        reclaim_self_update_artifacts();
949        if channel == UpdateChannel::Preview {
950            println!(
951                "rpi preview update skipped: offline mode is enabled;\n\
952                 run `rpi update preview` without --offline to query GitHub."
953            );
954            return 0;
955        }
956        // The cache is the only source available without a network round trip,
957        // so it may be stale — say so rather than assert a version.
958        match known_latest_rpi(None, cached_latest_rpi().as_deref()) {
959            Some((latest, true)) if is_newer(crate::VERSION, &latest) => println!(
960                "rpi {} -> {} is available (offline: last known, not verified)\n\
961                 Run `rpi update` without --offline to install it.",
962                crate::VERSION,
963                latest
964            ),
965            Some(_) => println!(
966                "rpi is up to date with the last known release ({})\n\
967                 Offline mode is enabled; the registry was not contacted.",
968                crate::VERSION
969            ),
970            None => println!(
971                "rpi update skipped: offline mode is enabled and no cached release is known"
972            ),
973        }
974        return 0;
975    }
976
977    // Without this gate `rpi update` at the newest release still runs a full
978    // `cargo install` and schedules a binary replacement for the version that
979    // is already installed — which is exactly what makes a working update look
980    // broken. `--force` keeps an explicit reinstall available.
981    let release = if !build || !force {
982        match channel {
983            UpdateChannel::Stable => lookup_latest_rpi_blocking(),
984            UpdateChannel::Preview => lookup_latest_preview_blocking(),
985        }
986    } else {
987        None
988    };
989    if !force {
990        reclaim_self_update_artifacts();
991        let staged = pending_staged_version(channel);
992        let (latest, verified) = match release.clone() {
993            Some(found) => found,
994            None if staged.is_some() => {
995                println!(
996                    "could not reach the latest {} release; using the already staged update",
997                    if channel == UpdateChannel::Preview {
998                        "preview"
999                    } else {
1000                        "stable"
1001                    }
1002                );
1003                (crate::VERSION.to_string(), false)
1004            }
1005            None => {
1006                println!(
1007                    "could not reach the latest {} release\n\
1008                     Retry later, or use `rpi update --build --force` for an explicit Cargo build.",
1009                    if channel == UpdateChannel::Preview {
1010                        "preview"
1011                    } else {
1012                        "stable"
1013                    }
1014                );
1015                return 1;
1016            }
1017        };
1018        // A staged update counts as "already going to happen": it is a fully
1019        // validated binary waiting only for this process to exit, so compiling
1020        // a second one buys nothing. It only counts when it is at least as new
1021        // as the release the registry just reported.
1022        let staged_wins = staged
1023            .as_ref()
1024            .filter(|staged| !is_newer(&staged.to_string(), &latest))
1025            .map(std::string::ToString::to_string);
1026        let target = staged_wins.clone().unwrap_or_else(|| latest.clone());
1027        let needs_update = match channel {
1028            UpdateChannel::Stable => is_newer(crate::VERSION, &target),
1029            // Explicitly selecting preview is allowed from a stable install;
1030            // a preview channel is intentionally independent of the stable channel's
1031            // stable precedence ordering.
1032            UpdateChannel::Preview => {
1033                let current = semver::Version::parse(crate::VERSION).ok();
1034                current.is_some_and(|current| current.pre.is_empty())
1035                    || is_newer(crate::VERSION, &target)
1036            }
1037        };
1038        if !needs_update {
1039            if staged_wins.is_some() {
1040                println!(
1041                    "rpi {target} is already staged; quit this rpi and it will be applied\n\
1042                     Run `rpi update --force` to stage it again."
1043                );
1044            } else if verified {
1045                println!(
1046                    "rpi is up to date ({} is the latest release)\n\
1047                     Run `rpi update --force` to reinstall anyway.",
1048                    crate::VERSION
1049                );
1050            } else {
1051                println!(
1052                    "rpi is up to date ({}; last known release {latest}, unverified)\n\
1053                     Run `rpi update --force` to reinstall anyway.",
1054                    crate::VERSION
1055                );
1056            }
1057            return 0;
1058        }
1059    }
1060
1061    if !build && release.is_none() {
1062        eprintln!(
1063            "error: could not resolve the {} release version; retry later or select --build explicitly",
1064            if channel == UpdateChannel::Preview {
1065                "preview"
1066            } else {
1067                "stable"
1068            }
1069        );
1070        return 1;
1071    }
1072    let version = release.as_ref().map(|(version, _)| version.as_str());
1073    let code = {
1074        #[cfg(windows)]
1075        {
1076            run_windows_self_update(build, version, cdn_base.as_ref())
1077        }
1078        #[cfg(not(windows))]
1079        {
1080            run_direct_self_update(build, version, cdn_base.as_ref())
1081        }
1082    };
1083    if code == 0 {
1084        clear_cached_latest_rpi();
1085    }
1086    code
1087}
1088
1089fn pending_staged_version(channel: UpdateChannel) -> Option<semver::Version> {
1090    let agent_dir = crate::config::agent_dir().ok()?;
1091    let update_root = agent_dir.join("self-update");
1092    staged_pending_version(&update_root, channel)
1093}
1094
1095fn cached_latest_rpi() -> Option<String> {
1096    let agent_dir = crate::config::agent_dir().ok()?;
1097    let cache = read_cache(&agent_dir.join(CACHE_FILE))?;
1098    cache.rpi_latest
1099}
1100
1101/// A self-update just changed the binary on disk, so the cached release is the
1102/// version being replaced. Dropping it stops the next startup (and the next
1103/// `rpi update`) from announcing an update that is already installed; the
1104/// following registry check refills it.
1105fn clear_cached_latest_rpi() {
1106    let Ok(agent_dir) = crate::config::agent_dir() else {
1107        return;
1108    };
1109    let path = agent_dir.join(CACHE_FILE);
1110    let Some(_lock) = try_lock_update_cache(&path) else {
1111        return;
1112    };
1113    let Some(mut cache) = read_cache(&path) else {
1114        return;
1115    };
1116    cache.last_successful_check_at = last_successful_update_check(&cache);
1117    cache.rpi_latest = None;
1118    cache.freshness.rpi = 0;
1119    let _ = write_cache(&path, &cache);
1120}
1121
1122fn cargo_install_command(
1123    staging_root: Option<&Path>,
1124    isolated_cwd: &Path,
1125) -> Result<std::process::Command, String> {
1126    let isolated_cwd = validated_self_update_command_dir(isolated_cwd)?;
1127    let mut command = std::process::Command::new("cargo");
1128    command.arg("install").current_dir(isolated_cwd);
1129    for variable in [
1130        "RUSTC_WRAPPER",
1131        "RUSTC_WORKSPACE_WRAPPER",
1132        "CARGO_BUILD_RUSTC_WRAPPER",
1133        "CARGO_BUILD_RUSTC_WORKSPACE_WRAPPER",
1134    ] {
1135        command.env_remove(variable);
1136    }
1137    if let Some(staging_root) = staging_root {
1138        command.arg("--root").arg(staging_root);
1139    }
1140    // `--quiet` suppresses cargo's trailing advice to add the install root to
1141    // PATH. Here that advice is actively wrong: the staging root is a temp
1142    // directory that the atomic replace consumes, so a user who follows it
1143    // adds a path that will not exist a second later. Errors still print.
1144    command.args(["rpi-cli", "--locked", "--force", "--quiet"]);
1145    Ok(command)
1146}
1147
1148/// Both distribution paths feed the same validated staging/atomic replacement.
1149/// Cargo is only reached when the user explicitly selects --build.
1150fn prepare_self_update(
1151    staging: &Path,
1152    build: bool,
1153    version: Option<&str>,
1154    cdn_base: Option<&reqwest::Url>,
1155) -> Result<(), String> {
1156    if build {
1157        let command_dir = create_self_update_command_dir()?;
1158        let status = cargo_install_command(Some(staging), command_dir.path())?
1159            .status()
1160            .map_err(|e| format!("could not run Cargo: {e}"))?;
1161        return if status.success() {
1162            Ok(())
1163        } else {
1164            Err(format!("cargo install exited with {status}"))
1165        };
1166    }
1167    let version = version
1168        .ok_or("no verified release version is available")?
1169        .to_string();
1170    let staging = staging.to_path_buf();
1171    let cdn_base = cdn_base.cloned();
1172    std::thread::Builder::new()
1173        .name("rpi-prebuilt-update".into())
1174        .spawn(move || {
1175            let runtime = tokio::runtime::Builder::new_current_thread()
1176                .enable_all()
1177                .build()
1178                .map_err(|e| e.to_string())?;
1179            runtime.block_on(crate::prebuilt_release::download_to(
1180                &version,
1181                &staging,
1182                cdn_base.as_ref(),
1183            ))
1184        })
1185        .map_err(|e| e.to_string())?
1186        .join()
1187        .map_err(|_| "prebuilt update worker failed".to_string())?
1188}
1189
1190pub(crate) fn validate_downloaded_rpi(
1191    path: &Path,
1192    staging: &Path,
1193    expected: &str,
1194) -> Result<(), String> {
1195    let found = validate_rpi_executable_version(path, staging, crate::VERSION, "downloaded rpi")?;
1196    if found.to_string() != expected {
1197        return Err(format!(
1198            "downloaded rpi version {found} does not match manifest {expected}"
1199        ));
1200    }
1201    Ok(())
1202}
1203
1204/// Cargo discovers `.cargo/config.toml` from its working directory upward.
1205/// Put update commands directly below the user's home directory so neither an
1206/// untrusted project, a project-local `CARGO_HOME`, nor a world-writable system
1207/// temp directory can join that discovery chain. Cargo still reads its
1208/// explicitly configured user-level home through its normal environment.
1209fn create_self_update_command_dir() -> Result<tempfile::TempDir, String> {
1210    let configured_root =
1211        dirs::home_dir().ok_or_else(|| "could not resolve the user home directory".to_string())?;
1212    if !configured_root.is_absolute() {
1213        return Err("user home must be absolute for self-update".to_string());
1214    }
1215    let canonical_root = std::fs::canonicalize(&configured_root)
1216        .map(normalize_windows_path)
1217        .map_err(|error| format!("could not canonicalize user home: {error}"))?;
1218    let metadata = std::fs::symlink_metadata(&canonical_root)
1219        .map_err(|error| format!("could not inspect user home: {error}"))?;
1220    if !metadata.is_dir() || metadata.file_type().is_symlink() {
1221        return Err("user home does not resolve to a real directory".to_string());
1222    }
1223    let current = std::env::current_dir()
1224        .and_then(std::fs::canonicalize)
1225        .map(normalize_windows_path)
1226        .map_err(|error| format!("could not validate the caller directory: {error}"))?;
1227    let project_root = current
1228        .ancestors()
1229        .find(|ancestor| std::fs::symlink_metadata(ancestor.join(".git")).is_ok())
1230        .map(Path::to_path_buf);
1231    validate_configured_cargo_home(project_root.as_deref())?;
1232    if project_root.as_deref().is_some_and(|root| {
1233        !windows_paths_equal(&canonical_root, root) && path_is_within(&canonical_root, root)
1234    }) {
1235        return Err(
1236            "refusing to create a self-update command directory inside the caller project"
1237                .to_string(),
1238        );
1239    }
1240    let directory = tempfile::Builder::new()
1241        .prefix("rpi-self-update-command-")
1242        .tempdir_in(&canonical_root)
1243        .map_err(|error| format!("could not allocate Cargo command directory: {error}"))?;
1244    validated_self_update_command_dir(directory.path())?;
1245    #[cfg(unix)]
1246    {
1247        use std::os::unix::fs::{MetadataExt, PermissionsExt};
1248
1249        let directory_metadata = std::fs::symlink_metadata(directory.path())
1250            .map_err(|error| format!("could not inspect Cargo command directory: {error}"))?;
1251        if metadata.uid() != directory_metadata.uid() || metadata.permissions().mode() & 0o022 != 0
1252        {
1253            return Err("user home is not private to the current account".to_string());
1254        }
1255    }
1256    Ok(directory)
1257}
1258
1259fn path_is_within(candidate: &Path, ancestor: &Path) -> bool {
1260    candidate
1261        .ancestors()
1262        .any(|component| windows_paths_equal(component, ancestor))
1263}
1264
1265fn validate_configured_cargo_home(project_root: Option<&Path>) -> Result<(), String> {
1266    let Some(configured) = std::env::var_os("CARGO_HOME") else {
1267        return Ok(());
1268    };
1269    let configured = PathBuf::from(configured);
1270    if !configured.is_absolute() {
1271        return Err("CARGO_HOME must be absolute for self-update".to_string());
1272    }
1273    let project_local = match project_root {
1274        Some(root) => cargo_home_is_project_local(&configured, root)?,
1275        None => {
1276            canonicalize_allow_missing(&configured, "CARGO_HOME")?;
1277            false
1278        }
1279    };
1280    if project_local {
1281        return Err("refusing project-local CARGO_HOME during self-update".to_string());
1282    }
1283    Ok(())
1284}
1285
1286fn cargo_home_is_project_local(configured: &Path, project_root: &Path) -> Result<bool, String> {
1287    if !configured.is_absolute() {
1288        return Err("CARGO_HOME must be absolute for self-update".to_string());
1289    }
1290    let configured = canonicalize_allow_missing(configured, "CARGO_HOME")?;
1291    Ok(path_is_within(&configured, project_root))
1292}
1293
1294fn canonicalize_allow_missing(path: &Path, label: &str) -> Result<PathBuf, String> {
1295    if path.components().any(|component| {
1296        matches!(
1297            component,
1298            std::path::Component::CurDir | std::path::Component::ParentDir
1299        )
1300    }) {
1301        return Err(format!("{label} contains relative path components"));
1302    }
1303    let mut existing = path;
1304    let mut missing = Vec::new();
1305    loop {
1306        match std::fs::symlink_metadata(existing) {
1307            Ok(_) => break,
1308            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
1309                let name = existing
1310                    .file_name()
1311                    .ok_or_else(|| format!("could not resolve {label}"))?;
1312                missing.push(name.to_os_string());
1313                existing = existing
1314                    .parent()
1315                    .ok_or_else(|| format!("could not resolve {label}"))?;
1316            }
1317            Err(error) => return Err(format!("could not inspect {label}: {error}")),
1318        }
1319    }
1320    let mut canonical = std::fs::canonicalize(existing)
1321        .map(normalize_windows_path)
1322        .map_err(|error| format!("could not canonicalize {label}: {error}"))?;
1323    for component in missing.into_iter().rev() {
1324        canonical.push(component);
1325    }
1326    Ok(canonical)
1327}
1328
1329fn canonical_display(path: &Path) -> String {
1330    std::fs::canonicalize(path)
1331        .map(normalize_windows_path)
1332        .map(|path| path.display().to_string())
1333        .unwrap_or_else(|_| "<unresolvable>".to_string())
1334}
1335
1336fn validated_self_update_command_dir(path: &Path) -> Result<PathBuf, String> {
1337    if !path.is_absolute() {
1338        return Err("self-update command directory must be absolute".to_string());
1339    }
1340    let metadata = std::fs::symlink_metadata(path)
1341        .map_err(|error| format!("could not inspect self-update command directory: {error}"))?;
1342    if !metadata.is_dir() || metadata.file_type().is_symlink() {
1343        return Err("self-update command directory is not a real directory".to_string());
1344    }
1345    let canonical = std::fs::canonicalize(path)
1346        .map(normalize_windows_path)
1347        .map_err(|error| {
1348            format!("could not canonicalize self-update command directory: {error}")
1349        })?;
1350    Ok(canonical)
1351}
1352
1353#[cfg(not(windows))]
1354#[derive(Debug, Clone)]
1355struct DirectUpdatePlan {
1356    staging_dir: PathBuf,
1357    staged_exe: PathBuf,
1358    target_exe: PathBuf,
1359    replacement_temp: PathBuf,
1360    backup_file: PathBuf,
1361}
1362
1363#[cfg(not(windows))]
1364fn run_direct_self_update(
1365    build: bool,
1366    version: Option<&str>,
1367    cdn_base: Option<&reqwest::Url>,
1368) -> i32 {
1369    let staging = match create_self_update_staging_directory() {
1370        Ok(directory) => directory,
1371        Err(error) => {
1372            eprintln!("error: could not create self-update staging directory: {error}");
1373            return 1;
1374        }
1375    };
1376    if let Err(error) = prepare_self_update(staging.path(), build, version, cdn_base) {
1377        eprintln!("error: {error}");
1378        return 1;
1379    }
1380
1381    let current_exe = match std::env::current_exe() {
1382        Ok(path) => path,
1383        Err(error) => {
1384            eprintln!("error: could not resolve the current rpi executable: {error}");
1385            return 1;
1386        }
1387    };
1388    let plan = match build_direct_update_plan(staging.path(), &current_exe) {
1389        Ok(plan) => plan,
1390        Err(error) => {
1391            eprintln!("error: {error}");
1392            return 1;
1393        }
1394    };
1395    match activate_direct_update(&plan) {
1396        Ok(version) => {
1397            println!("rpi updated successfully to {version}");
1398            0
1399        }
1400        Err(error) => {
1401            eprintln!("error: {error}");
1402            1
1403        }
1404    }
1405}
1406
1407fn create_self_update_staging_directory() -> Result<tempfile::TempDir, String> {
1408    let agent = crate::config::agent_dir().map_err(|error| error.to_string())?;
1409    if !agent.is_absolute() {
1410        return Err("agent directory must be absolute".to_string());
1411    }
1412    std::fs::create_dir_all(&agent)
1413        .map_err(|error| format!("could not create {}: {error}", agent.display()))?;
1414    let agent = validated_real_directory(&agent, "agent directory")?;
1415    let update_root = agent.join("self-update");
1416    std::fs::create_dir_all(&update_root)
1417        .map_err(|error| format!("could not create {}: {error}", update_root.display()))?;
1418    let update_root = validated_real_directory(&update_root, "self-update root")?;
1419    let staging = tempfile::Builder::new()
1420        .prefix("pending-")
1421        .tempdir_in(&update_root)
1422        .map_err(|error| format!("could not allocate staging directory: {error}"))?;
1423    validated_real_directory(staging.path(), "self-update staging directory")?;
1424    Ok(staging)
1425}
1426
1427#[cfg(not(windows))]
1428fn build_direct_update_plan(
1429    staging_dir: &Path,
1430    target_exe: &Path,
1431) -> Result<DirectUpdatePlan, String> {
1432    let staging_dir = validated_real_directory(staging_dir, "self-update staging directory")?;
1433    let staged_exe = validated_regular_file(
1434        &staging_dir.join("bin").join(crate::APP_NAME),
1435        "staged rpi executable",
1436    )?;
1437    let target_exe = validated_regular_file(target_exe, "current rpi executable")?;
1438    let target_dir = validated_real_directory(
1439        target_exe
1440            .parent()
1441            .ok_or_else(|| "current executable has no parent directory".to_string())?,
1442        "current executable directory",
1443    )?;
1444    if target_exe.parent() != Some(target_dir.as_path()) {
1445        return Err("current executable is not a direct child of its validated directory".into());
1446    }
1447    let token = uuid::Uuid::new_v4().simple().to_string();
1448    let replacement_temp = target_dir.join(format!(".rpi-update-{token}.new"));
1449    let backup_file = target_dir.join(format!(".rpi-update-{token}.old"));
1450    if replacement_temp.exists() || backup_file.exists() {
1451        return Err("self-update replacement path collision".to_string());
1452    }
1453    Ok(DirectUpdatePlan {
1454        staging_dir,
1455        staged_exe,
1456        target_exe,
1457        replacement_temp,
1458        backup_file,
1459    })
1460}
1461
1462#[cfg(not(windows))]
1463fn activate_direct_update(plan: &DirectUpdatePlan) -> Result<semver::Version, String> {
1464    let staged_version = validate_rpi_executable_version(
1465        &plan.staged_exe,
1466        &plan.staging_dir,
1467        crate::VERSION,
1468        "staged rpi",
1469    )?;
1470    preflight_direct_replacement(plan)?;
1471
1472    let result = (|| {
1473        std::fs::copy(&plan.staged_exe, &plan.replacement_temp).map_err(|error| {
1474            format!("could not copy staged rpi beside the current executable: {error}")
1475        })?;
1476        validated_regular_file(&plan.replacement_temp, "replacement rpi executable")?;
1477        let copied_version = validate_rpi_executable_version(
1478            &plan.replacement_temp,
1479            plan.target_exe
1480                .parent()
1481                .ok_or_else(|| "current executable has no parent directory".to_string())?,
1482            crate::VERSION,
1483            "replacement rpi",
1484        )?;
1485        if copied_version != staged_version
1486            || !files_are_identical(&plan.staged_exe, &plan.replacement_temp)?
1487        {
1488            return Err(
1489                "replacement rpi does not match the validated staged executable".to_string(),
1490            );
1491        }
1492
1493        std::fs::hard_link(&plan.target_exe, &plan.backup_file)
1494            .map_err(|error| format!("could not preserve the current rpi executable: {error}"))?;
1495        let installed_version = validate_rpi_executable_version(
1496            &plan.backup_file,
1497            plan.target_exe
1498                .parent()
1499                .ok_or_else(|| "current executable has no parent directory".to_string())?,
1500            crate::VERSION,
1501            "current rpi",
1502        )?;
1503        if staged_version < installed_version {
1504            return Err(format!(
1505                "refusing to replace rpi {installed_version} with older version {staged_version}"
1506            ));
1507        }
1508        if !files_are_identical(&plan.target_exe, &plan.backup_file)? {
1509            return Err("current rpi executable changed while preparing the update".to_string());
1510        }
1511
1512        std::fs::rename(&plan.replacement_temp, &plan.target_exe).map_err(|error| {
1513            format!("could not atomically replace the current rpi executable: {error}")
1514        })?;
1515        Ok(())
1516    })();
1517
1518    if let Err(error) = result {
1519        let _ = remove_file_if_exists(&plan.replacement_temp);
1520        let _ = remove_file_if_exists(&plan.backup_file);
1521        return Err(error);
1522    }
1523
1524    let validation = (|| {
1525        if !files_are_identical(&plan.staged_exe, &plan.target_exe)? {
1526            return Err("updated rpi executable does not match the staged executable".to_string());
1527        }
1528        let updated_version = validate_rpi_executable_version(
1529            &plan.target_exe,
1530            plan.target_exe
1531                .parent()
1532                .ok_or_else(|| "current executable has no parent directory".to_string())?,
1533            crate::VERSION,
1534            "updated rpi",
1535        )?;
1536        if updated_version != staged_version {
1537            return Err(format!(
1538                "updated rpi reported version {updated_version}, expected {staged_version}"
1539            ));
1540        }
1541        Ok(())
1542    })();
1543
1544    if let Err(error) = validation {
1545        return Err(rollback_direct_update(plan, &error));
1546    }
1547    let _ = remove_file_if_exists(&plan.backup_file);
1548    Ok(staged_version)
1549}
1550
1551#[cfg(not(windows))]
1552fn preflight_direct_replacement(plan: &DirectUpdatePlan) -> Result<(), String> {
1553    for path in [&plan.replacement_temp, &plan.backup_file] {
1554        if path.exists() {
1555            return Err(format!(
1556                "self-update path already exists: {}",
1557                path.display()
1558            ));
1559        }
1560        let file = std::fs::OpenOptions::new()
1561            .write(true)
1562            .create_new(true)
1563            .open(path)
1564            .map_err(|error| format!("cannot write beside the current executable: {error}"))?;
1565        drop(file);
1566        std::fs::remove_file(path)
1567            .map_err(|error| format!("could not remove self-update probe: {error}"))?;
1568    }
1569    Ok(())
1570}
1571
1572#[cfg(not(windows))]
1573fn rollback_direct_update(plan: &DirectUpdatePlan, failure: &str) -> String {
1574    let _ = remove_file_if_exists(&plan.replacement_temp);
1575    match std::fs::rename(&plan.backup_file, &plan.target_exe) {
1576        Ok(()) => format!("{failure}; restored the previous rpi executable"),
1577        Err(rollback) => format!(
1578            "{failure}; automatic rollback failed ({rollback}); the previous executable remains at {}",
1579            plan.backup_file.display()
1580        ),
1581    }
1582}
1583
1584fn remove_file_if_exists(path: &Path) -> Result<(), String> {
1585    match std::fs::remove_file(path) {
1586        Ok(()) => Ok(()),
1587        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
1588        Err(error) => Err(error.to_string()),
1589    }
1590}
1591
1592#[cfg(windows)]
1593#[derive(Debug, Clone)]
1594struct WindowsUpdatePlan {
1595    staging_dir: PathBuf,
1596    staged_exe: PathBuf,
1597    target_exe: PathBuf,
1598    helper_script: PathBuf,
1599    status_file: PathBuf,
1600    replacement_temp: PathBuf,
1601    backup_file: PathBuf,
1602    rollback_displaced_file: PathBuf,
1603}
1604
1605#[cfg(windows)]
1606struct WindowsUpdateStaging {
1607    directory: tempfile::TempDir,
1608    status_file: PathBuf,
1609}
1610
1611#[cfg(windows)]
1612const WINDOWS_UPDATE_HELPER: &str = r#"param(
1613    [Parameter(Mandatory = $true)][long] $ParentPid,
1614    [Parameter(Mandatory = $true)][string] $StagingPath,
1615    [Parameter(Mandatory = $true)][string] $StagedPath,
1616    [Parameter(Mandatory = $true)][string] $StagedVersion,
1617    [Parameter(Mandatory = $true)][string] $TargetPath,
1618    [Parameter(Mandatory = $true)][string] $TempPath,
1619    [Parameter(Mandatory = $true)][string] $BackupPath,
1620    [Parameter(Mandatory = $true)][string] $RollbackDisplacedPath,
1621    [Parameter(Mandatory = $true)][string] $StatusPath
1622)
1623
1624Set-StrictMode -Version Latest
1625$ErrorActionPreference = 'Stop'
1626
1627function Write-UpdateStatus {
1628    param([string] $State, [string] $Message)
1629    $record = [ordered]@{
1630        state = $State
1631        message = $Message
1632        parentPid = $ParentPid
1633        staging = $StagingPath
1634        target = $TargetPath
1635        staged = $StagedPath
1636        stagedVersion = $StagedVersion
1637        backup = $BackupPath
1638        rollbackDisplaced = $RollbackDisplacedPath
1639        updatedAt = [DateTime]::UtcNow.ToString('o')
1640    }
1641    $json = $record | ConvertTo-Json -Compress
1642    $statusTemp = $StatusPath + '.tmp'
1643    [IO.File]::WriteAllText($statusTemp, $json, [Text.UTF8Encoding]::new($false))
1644    Move-Item -LiteralPath $statusTemp -Destination $StatusPath -Force
1645}
1646
1647function Assert-RegularFile {
1648    param([string] $Path, [string] $Label)
1649    $item = Get-Item -LiteralPath $Path -Force
1650    if ($item.PSIsContainer -or $item.Length -le 0 -or
1651        (($item.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0)) {
1652        throw "$Label is not a non-empty regular file"
1653    }
1654}
1655
1656function Assert-WindowsExecutable {
1657    param([string] $Path, [string] $Label)
1658    Assert-RegularFile -Path $Path -Label $Label
1659    $stream = [IO.File]::OpenRead($Path)
1660    try {
1661        if ($stream.ReadByte() -ne 77 -or $stream.ReadByte() -ne 90) {
1662            throw "$Label is not a Windows executable"
1663        }
1664    } finally {
1665        $stream.Dispose()
1666    }
1667}
1668
1669function Assert-RealDirectory {
1670    param([string] $Path, [string] $Label)
1671    $item = Get-Item -LiteralPath $Path -Force
1672    if (-not $item.PSIsContainer -or
1673        (($item.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0)) {
1674        throw "$Label is not a real directory"
1675    }
1676}
1677
1678function Get-FileSha256 {
1679    param([string] $Path)
1680    $stream = [IO.File]::OpenRead($Path)
1681    try {
1682        $sha256 = [Security.Cryptography.SHA256]::Create()
1683        try {
1684            return ([BitConverter]::ToString($sha256.ComputeHash($stream))).Replace('-', '')
1685        } finally {
1686            $sha256.Dispose()
1687        }
1688    } finally {
1689        $stream.Dispose()
1690    }
1691}
1692
1693function Remove-StagingPayload {
1694    try {
1695        $root = [IO.Path]::GetFullPath($StagingPath)
1696        Assert-RealDirectory -Path $root -Label 'self-update staging directory'
1697        $bin = [IO.Path]::Combine($root, 'bin')
1698        $helper = [IO.Path]::Combine($root, 'apply-update.ps1')
1699        foreach ($file in @(
1700            $StagedPath,
1701            [IO.Path]::Combine($root, '.crates.toml'),
1702            [IO.Path]::Combine($root, '.crates2.json'),
1703            $helper
1704        )) {
1705            if ([IO.File]::Exists($file)) {
1706                [IO.File]::Delete($file)
1707            }
1708        }
1709        if ([IO.Directory]::Exists($bin) -and
1710            [IO.Directory]::GetFileSystemEntries($bin).Length -eq 0) {
1711            [IO.Directory]::Delete($bin, $false)
1712        }
1713        if ([IO.Directory]::Exists($root) -and
1714            [IO.Directory]::GetFileSystemEntries($root).Length -eq 0) {
1715            [IO.Directory]::Delete($root, $false)
1716        }
1717    } catch {
1718        # Cleanup is best-effort; update status and recovery files stay intact.
1719    }
1720}
1721
1722$replaced = $false
1723try {
1724    $stagingFull = [IO.Path]::GetFullPath($StagingPath)
1725    $stagedFull = [IO.Path]::GetFullPath($StagedPath)
1726    $targetFull = [IO.Path]::GetFullPath($TargetPath)
1727    $tempFull = [IO.Path]::GetFullPath($TempPath)
1728    $backupFull = [IO.Path]::GetFullPath($BackupPath)
1729    $rollbackDisplacedFull = [IO.Path]::GetFullPath($RollbackDisplacedPath)
1730    $helperFull = [IO.Path]::Combine($stagingFull, 'apply-update.ps1')
1731    $statusFull = [IO.Path]::GetFullPath($StatusPath)
1732    $targetDirectory = [IO.Path]::GetDirectoryName($targetFull)
1733    if (-not [StringComparer]::OrdinalIgnoreCase.Equals(
1734            [IO.Path]::GetDirectoryName([IO.Path]::GetDirectoryName($stagedFull)), $stagingFull) -or
1735        -not [StringComparer]::OrdinalIgnoreCase.Equals(
1736            [IO.Path]::GetDirectoryName($helperFull), $stagingFull) -or
1737        -not [StringComparer]::OrdinalIgnoreCase.Equals(
1738            [IO.Path]::GetFullPath($PSScriptRoot), $stagingFull) -or
1739        -not [StringComparer]::OrdinalIgnoreCase.Equals(
1740            [IO.Path]::GetDirectoryName($statusFull), [IO.Path]::GetDirectoryName($stagingFull)) -or
1741        [string]::IsNullOrWhiteSpace($targetDirectory) -or
1742        -not [StringComparer]::OrdinalIgnoreCase.Equals(
1743            [IO.Path]::GetDirectoryName($tempFull), $targetDirectory) -or
1744        -not [StringComparer]::OrdinalIgnoreCase.Equals(
1745            [IO.Path]::GetDirectoryName($backupFull), $targetDirectory) -or
1746        -not [StringComparer]::OrdinalIgnoreCase.Equals(
1747            [IO.Path]::GetDirectoryName($rollbackDisplacedFull), $targetDirectory)) {
1748        throw 'self-update paths are outside their validated staging or target directories'
1749    }
1750
1751    Assert-RealDirectory -Path $stagingFull -Label 'self-update staging directory'
1752    Assert-RealDirectory -Path $targetDirectory -Label 'target directory'
1753    Assert-WindowsExecutable -Path $stagedFull -Label 'staged executable'
1754    Assert-WindowsExecutable -Path $targetFull -Label 'current executable'
1755    $expectedHash = Get-FileSha256 -Path $stagedFull
1756    $originalTargetHash = Get-FileSha256 -Path $targetFull
1757    if ([IO.File]::Exists($tempFull) -or [IO.File]::Exists($backupFull) -or
1758        [IO.File]::Exists($rollbackDisplacedFull)) {
1759        throw 'replacement, backup, or rollback path already exists'
1760    }
1761
1762    Write-UpdateStatus -State 'waiting' -Message 'waiting for the current rpi process to exit'
1763    if ($ParentPid -lt 1 -or $ParentPid -gt [int]::MaxValue) {
1764        throw 'parent process id is outside the supported Windows range'
1765    }
1766    $parentProcess = $null
1767    try {
1768        $candidate = [Diagnostics.Process]::GetProcessById([int]$ParentPid)
1769        try {
1770            $candidatePath = [IO.Path]::GetFullPath($candidate.MainModule.FileName)
1771            if ([StringComparer]::OrdinalIgnoreCase.Equals($candidatePath, $targetFull)) {
1772                $parentProcess = $candidate
1773            } else {
1774                $candidate.Dispose()
1775            }
1776        } catch {
1777            if ($candidate.HasExited) {
1778                $candidate.Dispose()
1779            } else {
1780                throw
1781            }
1782        }
1783    } catch [ArgumentException] {
1784        # The invoking process exited before the helper acquired its handle.
1785    }
1786    if ($null -ne $parentProcess) {
1787        try {
1788            if (-not $parentProcess.WaitForExit(600000)) {
1789                throw 'timed out waiting for the current rpi process to exit'
1790            }
1791        } finally {
1792            $parentProcess.Dispose()
1793        }
1794    }
1795
1796    Assert-RealDirectory -Path $targetDirectory -Label 'target directory'
1797    Assert-WindowsExecutable -Path $stagedFull -Label 'staged executable'
1798    Assert-WindowsExecutable -Path $targetFull -Label 'current executable'
1799    if ((Get-FileSha256 -Path $stagedFull) -ne $expectedHash) {
1800        throw 'staged executable changed while waiting for rpi to exit'
1801    }
1802    if ((Get-FileSha256 -Path $targetFull) -ne $originalTargetHash) {
1803        throw 'current executable changed while waiting for rpi to exit'
1804    }
1805    if ([IO.File]::Exists($tempFull) -or [IO.File]::Exists($backupFull) -or
1806        [IO.File]::Exists($rollbackDisplacedFull)) {
1807        throw 'replacement, backup, or rollback path appeared while waiting for rpi to exit'
1808    }
1809
1810    [IO.File]::Copy($stagedFull, $tempFull, $false)
1811    Assert-WindowsExecutable -Path $tempFull -Label 'replacement executable'
1812    if ((Get-FileSha256 -Path $tempFull) -ne $expectedHash) {
1813        throw 'replacement executable hash mismatch'
1814    }
1815
1816    [IO.File]::Replace($tempFull, $targetFull, $backupFull, $true)
1817    $replaced = $true
1818    Assert-WindowsExecutable -Path $targetFull -Label 'updated executable'
1819    if ((Get-FileSha256 -Path $targetFull) -ne $expectedHash) {
1820        throw 'updated executable hash mismatch'
1821    }
1822} catch {
1823    $failureMessage = $_.Exception.Message
1824    $recoveryMessage = ''
1825    if ($replaced -and [IO.File]::Exists($BackupPath)) {
1826        try {
1827            [IO.File]::Copy($BackupPath, $TempPath, $false)
1828            Assert-WindowsExecutable -Path $TempPath -Label 'rollback executable'
1829            if ((Get-FileSha256 -Path $TempPath) -ne $originalTargetHash) {
1830                throw 'rollback executable hash mismatch'
1831            }
1832            [IO.File]::Replace($TempPath, $TargetPath, $RollbackDisplacedPath, $true)
1833            Assert-WindowsExecutable -Path $TargetPath -Label 'restored executable'
1834            if ((Get-FileSha256 -Path $TargetPath) -ne $originalTargetHash) {
1835                throw 'restored executable hash mismatch'
1836            }
1837            $replaced = $false
1838            try { [IO.File]::Delete($BackupPath) } catch {}
1839            try { [IO.File]::Delete($RollbackDisplacedPath) } catch {}
1840        } catch {
1841            $rollbackFailure = $_.Exception.Message
1842            if ([IO.File]::Exists($BackupPath)) {
1843                $recoveryMessage = "; automatic rollback failed ($rollbackFailure); the original executable remains at $BackupPath"
1844            } else {
1845                $recoveryMessage = "; automatic rollback failed ($rollbackFailure) and no verified recovery backup remains"
1846            }
1847        }
1848    }
1849    if ([IO.File]::Exists($TempPath)) {
1850        try { Remove-Item -LiteralPath $TempPath -Force } catch {}
1851    }
1852    try { Write-UpdateStatus -State 'failed' -Message ($failureMessage + $recoveryMessage) } catch {}
1853    Remove-StagingPayload
1854    exit 1
1855}
1856
1857try { Write-UpdateStatus -State 'succeeded' -Message 'rpi executable replaced successfully' } catch {}
1858if ([IO.File]::Exists($BackupPath)) {
1859    try { Remove-Item -LiteralPath $BackupPath -Force } catch {}
1860}
1861Remove-StagingPayload
1862exit 0
1863"#;
1864
1865#[cfg(windows)]
1866fn run_windows_self_update(
1867    build: bool,
1868    version: Option<&str>,
1869    cdn_base: Option<&reqwest::Url>,
1870) -> i32 {
1871    let staging = match create_windows_update_staging() {
1872        Ok(staging) => staging,
1873        Err(error) => {
1874            eprintln!("error: could not create self-update staging directory: {error}");
1875            return 1;
1876        }
1877    };
1878    let staging_dir = staging.directory.path().to_path_buf();
1879    let status_file = staging.status_file.clone();
1880    let _ = write_windows_update_status(
1881        &status_file,
1882        "preparing",
1883        "installing the update into staging",
1884    );
1885
1886    let current_exe = match std::env::current_exe() {
1887        Ok(path) => path,
1888        Err(error) => {
1889            let message = format!("could not resolve the current rpi executable: {error}");
1890            let _ = write_windows_update_status(&status_file, "failed", &message);
1891            eprintln!("error: {message}");
1892            return 1;
1893        }
1894    };
1895    let powershell = match system_powershell_path() {
1896        Ok(path) => path,
1897        Err(error) => {
1898            let _ = write_windows_update_status(&status_file, "failed", &error);
1899            eprintln!("error: {error}");
1900            return 1;
1901        }
1902    };
1903
1904    if let Err(error) = prepare_self_update(&staging_dir, build, version, cdn_base) {
1905        let _ = write_windows_update_status(&status_file, "failed", &error);
1906        eprintln!("error: {error}");
1907        return 1;
1908    }
1909
1910    let plan = match build_windows_update_plan(&staging_dir, &current_exe, &status_file) {
1911        Ok(plan) => plan,
1912        Err(error) => {
1913            let _ = write_windows_update_status(&status_file, "failed", &error);
1914            eprintln!("error: {error}");
1915            return 1;
1916        }
1917    };
1918    let staged_version = match validate_staged_rpi(&plan) {
1919        Ok(version) => version,
1920        Err(error) => {
1921            let _ = write_windows_update_status(&plan.status_file, "failed", &error);
1922            eprintln!("error: {error}");
1923            return 1;
1924        }
1925    };
1926    if let Err(error) = preflight_windows_replacement(&plan) {
1927        let _ = write_windows_update_status(&plan.status_file, "failed", &error);
1928        eprintln!("error: {error}");
1929        return 1;
1930    }
1931    if let Err(error) = std::fs::write(&plan.helper_script, WINDOWS_UPDATE_HELPER.as_bytes()) {
1932        let message = format!("could not write the self-update helper: {error}");
1933        let _ = write_windows_update_status(&plan.status_file, "failed", &message);
1934        eprintln!("error: {message}");
1935        return 1;
1936    }
1937    if validated_regular_file(&plan.helper_script, "self-update helper").is_err() {
1938        let message = "self-update helper did not pass regular-file validation";
1939        let _ = write_windows_update_status(&plan.status_file, "failed", message);
1940        eprintln!("error: {message}");
1941        return 1;
1942    }
1943    let _ = write_windows_update_status(
1944        &plan.status_file,
1945        "scheduled",
1946        &format!("validated rpi {staged_version}; waiting to replace rpi after this process exits"),
1947    );
1948    let mut command = windows_update_helper_command(
1949        &powershell,
1950        &plan,
1951        std::process::id(),
1952        &staged_version.to_string(),
1953    );
1954    use std::os::windows::process::CommandExt;
1955    command.creation_flags(0x0800_0000); // CREATE_NO_WINDOW
1956    match command.spawn() {
1957        Ok(_) => {
1958            let persisted_staging = staging.directory.keep();
1959            println!(
1960                "rpi {staged_version} staged; quit this rpi and it will be applied.\n\
1961                 Status: {}",
1962                plan.status_file.display()
1963            );
1964            debug_assert!(windows_paths_equal(&persisted_staging, &plan.staging_dir));
1965            0
1966        }
1967        Err(error) => {
1968            let message = format!("could not start the self-update helper: {error}");
1969            let _ = write_windows_update_status(&plan.status_file, "failed", &message);
1970            eprintln!("error: {message}");
1971            1
1972        }
1973    }
1974}
1975
1976#[cfg(windows)]
1977fn create_windows_update_staging() -> Result<WindowsUpdateStaging, String> {
1978    let staging = create_self_update_staging_directory()?;
1979    let update_root = staging
1980        .path()
1981        .parent()
1982        .ok_or_else(|| "self-update staging directory has no parent".to_string())?;
1983    let status_file = update_root.join(format!("status-{}.json", uuid::Uuid::new_v4().simple()));
1984    if status_file.exists() {
1985        return Err("self-update status path collision".to_string());
1986    }
1987    Ok(WindowsUpdateStaging {
1988        directory: staging,
1989        status_file,
1990    })
1991}
1992
1993#[cfg(windows)]
1994fn build_windows_update_plan(
1995    staging_dir: &Path,
1996    target_exe: &Path,
1997    status_file: &Path,
1998) -> Result<WindowsUpdatePlan, String> {
1999    let staging_dir = validated_real_directory(staging_dir, "self-update staging directory")?;
2000    if !status_file.is_absolute() {
2001        return Err("self-update status path must be absolute".to_string());
2002    }
2003    let status_parent = validated_real_directory(
2004        status_file
2005            .parent()
2006            .ok_or_else(|| "self-update status path has no parent".to_string())?,
2007        "self-update status directory",
2008    )?;
2009    if staging_dir.parent() != Some(status_parent.as_path()) {
2010        return Err("self-update status file is outside the staging parent".to_string());
2011    }
2012    let status_name = status_file
2013        .file_name()
2014        .ok_or_else(|| "self-update status file has no name".to_string())?;
2015    if !is_self_update_status_name(status_name) {
2016        return Err("self-update status file has an invalid name".to_string());
2017    }
2018    if status_file.exists() {
2019        validated_regular_file(status_file, "self-update status file")?;
2020    }
2021    let staged_exe = validated_windows_executable(
2022        &staging_dir.join("bin").join("rpi.exe"),
2023        "staged rpi executable",
2024    )?;
2025    let target_exe = validated_windows_executable(target_exe, "current rpi executable")?;
2026    let target_dir = validated_real_directory(
2027        target_exe
2028            .parent()
2029            .ok_or_else(|| "current executable has no parent directory".to_string())?,
2030        "current executable directory",
2031    )?;
2032    if target_exe.parent() != Some(target_dir.as_path()) {
2033        return Err("current executable is not a direct child of its validated directory".into());
2034    }
2035    let token = uuid::Uuid::new_v4().simple().to_string();
2036    let replacement_temp = target_dir.join(format!(".rpi-update-{token}.new.exe"));
2037    let backup_file = target_dir.join(format!(".rpi-update-{token}.old.exe"));
2038    let rollback_displaced_file = target_dir.join(format!(".rpi-update-{token}.rollback-new.exe"));
2039    if replacement_temp.exists() || backup_file.exists() || rollback_displaced_file.exists() {
2040        return Err("self-update replacement path collision".to_string());
2041    }
2042
2043    Ok(WindowsUpdatePlan {
2044        staging_dir: staging_dir.clone(),
2045        staged_exe,
2046        target_exe,
2047        helper_script: staging_dir.join("apply-update.ps1"),
2048        status_file: status_file.to_path_buf(),
2049        replacement_temp,
2050        backup_file,
2051        rollback_displaced_file,
2052    })
2053}
2054
2055#[cfg(windows)]
2056fn preflight_windows_replacement(plan: &WindowsUpdatePlan) -> Result<(), String> {
2057    for path in [
2058        &plan.replacement_temp,
2059        &plan.backup_file,
2060        &plan.rollback_displaced_file,
2061    ] {
2062        if path.exists() {
2063            return Err(format!(
2064                "self-update path already exists: {}",
2065                path.display()
2066            ));
2067        }
2068        let file = std::fs::OpenOptions::new()
2069            .write(true)
2070            .create_new(true)
2071            .open(path)
2072            .map_err(|error| format!("cannot write beside the current executable: {error}"))?;
2073        drop(file);
2074        std::fs::remove_file(path)
2075            .map_err(|error| format!("could not remove self-update probe: {error}"))?;
2076    }
2077    Ok(())
2078}
2079
2080#[cfg(windows)]
2081fn validate_staged_rpi(plan: &WindowsUpdatePlan) -> Result<semver::Version, String> {
2082    let cwd = plan
2083        .helper_script
2084        .parent()
2085        .ok_or_else(|| "self-update staging directory is missing".to_string())?;
2086    validate_rpi_executable_version(&plan.staged_exe, cwd, crate::VERSION, "staged rpi")
2087}
2088
2089/// Captured output of a bounded self-update probe.
2090struct BoundedProcessOutput {
2091    status: std::process::ExitStatus,
2092    stdout: Vec<u8>,
2093    stderr: Vec<u8>,
2094}
2095
2096/// Run a short-lived probe under both a wall-clock and an output cap.
2097///
2098/// The child runs on its own thread and current-thread runtime so this stays
2099/// safe when `rpi update` is entered from inside a Tokio runtime. The old
2100/// implementation reused the npm bridge's process runner, which went away with
2101/// the Pi compatibility layer.
2102fn run_bounded_process_blocking(
2103    program: &str,
2104    args: &[String],
2105    cwd: &Path,
2106    timeout: std::time::Duration,
2107    max_output_bytes: usize,
2108) -> Result<BoundedProcessOutput, String> {
2109    let program = program.to_string();
2110    let args = args.to_vec();
2111    let cwd = cwd.to_path_buf();
2112    std::thread::Builder::new()
2113        .name("rpi-bounded-version-probe".to_string())
2114        .spawn(move || {
2115            let runtime = tokio::runtime::Builder::new_current_thread()
2116                .enable_all()
2117                .build()
2118                .map_err(|error| format!("probe runtime failed: {error}"))?;
2119            runtime.block_on(async move {
2120                let mut command = tokio::process::Command::new(&program);
2121                command
2122                    .args(&args)
2123                    .current_dir(&cwd)
2124                    .stdin(std::process::Stdio::null())
2125                    .stdout(std::process::Stdio::piped())
2126                    .stderr(std::process::Stdio::piped())
2127                    .kill_on_drop(true);
2128                #[cfg(unix)]
2129                let child = {
2130                    let mut result = command.spawn();
2131                    // A concurrent fork can inherit the copy's writable file descriptor
2132                    // briefly, even after the copying thread has closed it.
2133                    for _ in 0..5 {
2134                        if !matches!(&result, Err(error) if error.raw_os_error() == Some(nix::errno::Errno::ETXTBSY as i32)) {
2135                            break;
2136                        }
2137                        tokio::time::sleep(std::time::Duration::from_millis(10)).await;
2138                        result = command.spawn();
2139                    }
2140                    result
2141                };
2142                #[cfg(not(unix))]
2143                let child = command.spawn();
2144                let child = child.map_err(|error| format!("spawn failed: {error}"))?;
2145                let output = match tokio::time::timeout(timeout, child.wait_with_output()).await {
2146                    Ok(result) => result.map_err(|error| format!("wait failed: {error}"))?,
2147                    // Dropping the future drops the child, which `kill_on_drop`
2148                    // turns into a kill.
2149                    Err(_) => return Err(format!("timed out after {timeout:?}")),
2150                };
2151                Ok(BoundedProcessOutput {
2152                    status: output.status,
2153                    stdout: cap_bytes(output.stdout, max_output_bytes),
2154                    stderr: cap_bytes(output.stderr, max_output_bytes),
2155                })
2156            })
2157        })
2158        .map_err(|error| format!("probe thread failed: {error}"))?
2159        .join()
2160        .map_err(|_| "probe worker panicked".to_string())?
2161}
2162
2163fn cap_bytes(bytes: Vec<u8>, limit: usize) -> Vec<u8> {
2164    if bytes.len() <= limit {
2165        bytes
2166    } else {
2167        bytes[..limit].to_vec()
2168    }
2169}
2170
2171/// Byte-for-byte comparison, used to prove a copied or replaced rpi binary is
2172/// the one that was validated.
2173#[cfg(not(windows))]
2174fn files_are_identical(left: &Path, right: &Path) -> Result<bool, String> {
2175    use std::io::{BufReader, Read};
2176
2177    let left_file = std::fs::File::open(left)
2178        .map_err(|error| format!("could not open {}: {error}", left.display()))?;
2179    let right_file = std::fs::File::open(right)
2180        .map_err(|error| format!("could not open {}: {error}", right.display()))?;
2181    if left_file
2182        .metadata()
2183        .map_err(|error| error.to_string())?
2184        .len()
2185        != right_file
2186            .metadata()
2187            .map_err(|error| error.to_string())?
2188            .len()
2189    {
2190        return Ok(false);
2191    }
2192    let mut left = BufReader::new(left_file);
2193    let mut right = BufReader::new(right_file);
2194    let mut left_buffer = [0u8; 64 * 1024];
2195    let mut right_buffer = [0u8; 64 * 1024];
2196    loop {
2197        let left_read = left
2198            .read(&mut left_buffer)
2199            .map_err(|error| error.to_string())?;
2200        let right_read = right
2201            .read(&mut right_buffer)
2202            .map_err(|error| error.to_string())?;
2203        if left_read != right_read || left_buffer[..left_read] != right_buffer[..right_read] {
2204            return Ok(false);
2205        }
2206        if left_read == 0 {
2207            return Ok(true);
2208        }
2209    }
2210}
2211
2212fn validate_rpi_executable_version(
2213    executable: &Path,
2214    cwd: &Path,
2215    current: &str,
2216    label: &str,
2217) -> Result<semver::Version, String> {
2218    let program = executable
2219        .to_str()
2220        .ok_or_else(|| format!("{label} path cannot be represented as Unicode"))?;
2221    let args = vec!["--version".to_string()];
2222    let output = run_bounded_process_blocking(
2223        program,
2224        &args,
2225        cwd,
2226        STAGED_RPI_CHECK_TIMEOUT,
2227        MAX_STAGED_RPI_OUTPUT_BYTES,
2228    )
2229    .map_err(|error| format!("{label} version check failed: {error}"))?;
2230    if !output.status.success() {
2231        return Err(format!("{label} --version exited with {}", output.status));
2232    }
2233    validate_staged_rpi_version_output(&output.stdout, &output.stderr, current)
2234}
2235
2236fn validate_staged_rpi_version_output(
2237    stdout: &[u8],
2238    stderr: &[u8],
2239    current: &str,
2240) -> Result<semver::Version, String> {
2241    if !stderr.is_empty() {
2242        return Err("staged rpi --version wrote unexpected stderr output".to_string());
2243    }
2244    let staged = parse_rpi_version_output(stdout)
2245        .ok_or_else(|| "staged rpi returned an invalid --version response".to_string())?;
2246    let current = semver::Version::parse(current)
2247        .map_err(|_| "the running rpi version is not valid semantic versioning".to_string())?;
2248    if staged < current {
2249        return Err(format!(
2250            "refusing to replace rpi {current} with older version {staged}"
2251        ));
2252    }
2253    Ok(staged)
2254}
2255
2256fn parse_rpi_version_output(output: &[u8]) -> Option<semver::Version> {
2257    let output = std::str::from_utf8(output).ok()?;
2258    let line = output
2259        .strip_suffix("\r\n")
2260        .or_else(|| output.strip_suffix('\n'))
2261        .unwrap_or(output);
2262    if line.contains(['\r', '\n']) {
2263        return None;
2264    }
2265    let version = line.strip_prefix(crate::APP_NAME)?.strip_prefix(' ')?;
2266    if version.is_empty() || version.chars().any(char::is_whitespace) {
2267        return None;
2268    }
2269    semver::Version::parse(version).ok()
2270}
2271
2272/// A real directory *by its own entry*: the leaf is not a link, so the update
2273/// is free to write into it. Links further up are resolved rather than
2274/// refused — a launch path such as `C:\tools\current\rpi.exe` where `current`
2275/// is a junction names the real install directory, which is exactly what an
2276/// update should rewrite.
2277fn validated_real_directory(path: &Path, label: &str) -> Result<PathBuf, String> {
2278    if !path.is_absolute() {
2279        return Err(format!("{label} must be absolute"));
2280    }
2281    let metadata = std::fs::symlink_metadata(path)
2282        .map_err(|error| format!("could not inspect {label}: {error}"))?;
2283    if metadata.file_type().is_symlink() {
2284        return Err(format!(
2285            "{label} is a link or junction, not a real directory ({} -> {})",
2286            path.display(),
2287            canonical_display(path),
2288        ));
2289    }
2290    if !metadata.is_dir() {
2291        return Err(format!("{label} is not a real directory"));
2292    }
2293    std::fs::canonicalize(path)
2294        .map(normalize_windows_path)
2295        .map_err(|error| format!("could not canonicalize {label}: {error}"))
2296}
2297
2298/// A non-empty regular file *by its own entry*: a link to a file is refused
2299/// with both paths named, because replacing the link would leave the real
2300/// target stale. Ancestor links are resolved, as in
2301/// [`validated_real_directory`].
2302fn validated_regular_file(path: &Path, label: &str) -> Result<PathBuf, String> {
2303    if !path.is_absolute() {
2304        return Err(format!("{label} must be absolute"));
2305    }
2306    let metadata = std::fs::symlink_metadata(path)
2307        .map_err(|error| format!("could not inspect {label}: {error}"))?;
2308    if metadata.file_type().is_symlink() {
2309        return Err(format!(
2310            "{label} is a link or junction, not a non-empty regular file ({} -> {})",
2311            path.display(),
2312            canonical_display(path),
2313        ));
2314    }
2315    if !metadata.is_file() || metadata.len() == 0 {
2316        return Err(format!("{label} is not a non-empty regular file"));
2317    }
2318    std::fs::canonicalize(path)
2319        .map(normalize_windows_path)
2320        .map_err(|error| format!("could not canonicalize {label}: {error}"))
2321}
2322
2323fn is_self_update_status_name(name: &std::ffi::OsStr) -> bool {
2324    let Some(name) = name.to_str() else {
2325        return false;
2326    };
2327    let Some(token) = name
2328        .strip_prefix("status-")
2329        .and_then(|name| name.strip_suffix(".json"))
2330    else {
2331        return false;
2332    };
2333    token.len() == 32 && token.bytes().all(|byte| byte.is_ascii_hexdigit())
2334}
2335
2336/// `tempfile::Builder::new().prefix("pending-")` mints the rest of the name
2337/// from `[A-Za-z0-9]`. Requiring that shape keeps the pruning from ever
2338/// pointing `remove_dir_all` at a directory this tool did not create.
2339fn is_self_update_staging_name(name: &str) -> bool {
2340    let Some(suffix) = name.strip_prefix("pending-") else {
2341        return false;
2342    };
2343    !suffix.is_empty() && suffix.bytes().all(|byte| byte.is_ascii_alphanumeric())
2344}
2345
2346fn validated_self_update_status_file(update_root: &Path, path: &Path) -> Result<PathBuf, String> {
2347    if !path.is_absolute() || path.parent() != Some(update_root) {
2348        return Err("self-update status file is outside the update root".to_string());
2349    }
2350    if !path.file_name().is_some_and(is_self_update_status_name) {
2351        return Err("self-update status file has an invalid name".to_string());
2352    }
2353    let path = validated_regular_file(path, "self-update status file")?;
2354    let length = std::fs::metadata(&path)
2355        .map_err(|error| format!("could not inspect self-update status file: {error}"))?
2356        .len();
2357    if length > MAX_SELF_UPDATE_STATUS_BYTES {
2358        return Err("self-update status file is too large".to_string());
2359    }
2360    Ok(path)
2361}
2362
2363fn read_self_update_status(path: &Path) -> Option<SelfUpdateStatus> {
2364    use std::io::Read;
2365
2366    let file = std::fs::File::open(path).ok()?;
2367    let mut data = Vec::with_capacity(
2368        usize::try_from(MAX_SELF_UPDATE_STATUS_BYTES)
2369            .unwrap_or_default()
2370            .min(8 * 1024),
2371    );
2372    file.take(MAX_SELF_UPDATE_STATUS_BYTES.saturating_add(1))
2373        .read_to_end(&mut data)
2374        .ok()?;
2375    if data.len() as u64 > MAX_SELF_UPDATE_STATUS_BYTES {
2376        return None;
2377    }
2378    serde_json::from_slice(&data).ok()
2379}
2380
2381fn sanitized_self_update_status_message(message: &str) -> String {
2382    let mut sanitized = String::new();
2383    let mut pending_space = false;
2384    let mut truncated = false;
2385    for character in message.trim().chars() {
2386        if character.is_control() || character.is_whitespace() {
2387            pending_space = !sanitized.is_empty();
2388            continue;
2389        }
2390        if sanitized.chars().count() >= MAX_SELF_UPDATE_STATUS_MESSAGE_CHARS {
2391            truncated = true;
2392            break;
2393        }
2394        if pending_space {
2395            sanitized.push(' ');
2396            pending_space = false;
2397        }
2398        sanitized.push(character);
2399    }
2400    if sanitized.is_empty() {
2401        return "no diagnostic message was recorded".to_string();
2402    }
2403    if truncated {
2404        sanitized.push_str("...");
2405    }
2406    sanitized
2407}
2408
2409fn consume_self_update_statuses(agent_dir: &Path) -> Vec<UpdateWarning> {
2410    let _guard = SELF_UPDATE_STATUS_LOCK
2411        .lock()
2412        .unwrap_or_else(std::sync::PoisonError::into_inner);
2413    let agent_dir = match validated_real_directory(agent_dir, "agent directory") {
2414        Ok(path) => path,
2415        Err(_) => return Vec::new(),
2416    };
2417    let update_root = match validated_real_directory(
2418        &agent_dir.join("self-update"),
2419        "self-update status directory",
2420    ) {
2421        Ok(path) if path.parent() == Some(agent_dir.as_path()) => path,
2422        _ => return Vec::new(),
2423    };
2424    let entries = match std::fs::read_dir(&update_root) {
2425        Ok(entries) => entries,
2426        Err(_) => return Vec::new(),
2427    };
2428
2429    let now = now_ms();
2430    let mut warnings = Vec::new();
2431    // Every staging directory a live status file still claims.
2432    let mut claimed = BTreeSet::new();
2433    // Staging directories a status file proved to be debris: the helper that
2434    // would have installed from them is gone, so their on-disk age — which can
2435    // look recent when a run died early — does not have to vouch for them.
2436    let mut obsolete = BTreeSet::new();
2437    // Non-terminal records young enough that the writer is probably still
2438    // alive. Reconciled after the scan, once a terminal record could have
2439    // claimed the same directory.
2440    let mut undecided = Vec::new();
2441    for entry in entries.flatten() {
2442        if !is_self_update_status_name(&entry.file_name()) {
2443            continue;
2444        }
2445        let path = match validated_self_update_status_file(&update_root, &entry.path()) {
2446            Ok(path) => path,
2447            Err(_) => continue,
2448        };
2449        let Some(status) = read_self_update_status(&path) else {
2450            continue;
2451        };
2452        if !matches!(status.state.as_str(), "failed" | "succeeded") {
2453            // A record with no usable timestamp has an unknown age. Leaving it
2454            // alone is the safe reading: the alternative deletes a status file
2455            // that a live helper may still be writing.
2456            let stale = status.updated_at_ms > 0
2457                && now.saturating_sub(status.updated_at_ms) > STALE_SELF_UPDATE_STATUS_TTL_MS;
2458            if stale {
2459                if let Some(staging) = status.staging.as_deref() {
2460                    obsolete.insert(staging.to_path_buf());
2461                }
2462                let _ = remove_file_if_exists(&path);
2463            } else {
2464                undecided.push((path, status));
2465            }
2466            continue;
2467        }
2468        if let Some(staging) = status.staging.as_deref() {
2469            claimed.insert(staging.to_path_buf());
2470        }
2471
2472        if status.state == "succeeded" {
2473            // Kept as the durable record of what was installed. The path is
2474            // printed by `rpi update`, so deleting the file on the next start
2475            // made a finished update look like it had never run. It ages out
2476            // with the rest of the record set instead.
2477            let old = status.updated_at_ms > 0
2478                && now.saturating_sub(status.updated_at_ms) > COMPLETED_SELF_UPDATE_STATUS_TTL_MS;
2479            if old {
2480                if let Some(staging) = status.staging.as_deref() {
2481                    claimed.remove(staging);
2482                    obsolete.insert(staging.to_path_buf());
2483                }
2484                let _ = remove_file_if_exists(&path);
2485            }
2486            continue;
2487        }
2488
2489        match std::fs::remove_file(&path) {
2490            Ok(()) => {}
2491            Err(error) if error.kind() == std::io::ErrorKind::NotFound => continue,
2492            // A failure is still actionable even when cleanup is denied. Keep
2493            // the file so a later startup can retry consumption.
2494            Err(_) => {}
2495        }
2496        warnings.push(UpdateWarning {
2497            message: format!(
2498                "The previously scheduled rpi update failed: {}",
2499                sanitized_self_update_status_message(&status.message)
2500            ),
2501            command: "rpi update".to_string(),
2502        });
2503    }
2504
2505    // A non-terminal record whose staging directory a terminal record already
2506    // owns is a leftover of a completed run, not a live one.
2507    for (path, status) in undecided {
2508        let staging = status.staging.clone();
2509        if staging
2510            .as_deref()
2511            .is_some_and(|staging| claimed.contains(staging))
2512        {
2513            let _ = remove_file_if_exists(&path);
2514            continue;
2515        }
2516        if let Some(staging) = staging {
2517            claimed.insert(staging);
2518        }
2519    }
2520
2521    prune_self_update_staging(&update_root, &claimed, &obsolete, now);
2522    warnings
2523}
2524
2525/// Delete staging directories no live status file references.
2526///
2527/// A Windows update persists its staging directory (`TempDir::keep`) so the
2528/// helper can install from it after the parent exits. When the helper dies
2529/// first — a reboot at the wrong moment, a machine-wide `taskkill` — the
2530/// directory stays behind forever: nothing else in the update path removes it,
2531/// and because its status file was still `preparing` the next start never
2532/// looked at it either. Those are the directories that pile up in
2533/// `~/.rpi/agent/self-update`.
2534///
2535/// A directory a status file already proved dead (`obsolete`) goes as soon as
2536/// its name validates. Otherwise the evidence has to come from the directory
2537/// itself: empty debris goes unconditionally, because no update can be
2538/// mid-install in a directory with nothing in it, while a populated one waits
2539/// for the TTL. That keeps a staging directory whose record was just consumed —
2540/// and which a helper may still be reading — from being deleted underneath it.
2541fn prune_self_update_staging(
2542    update_root: &Path,
2543    claimed: &BTreeSet<PathBuf>,
2544    obsolete: &BTreeSet<PathBuf>,
2545    now: i64,
2546) {
2547    let Ok(entries) = std::fs::read_dir(update_root) else {
2548        return;
2549    };
2550    for entry in entries.flatten() {
2551        let name = entry.file_name();
2552        let Some(name) = name.to_str() else {
2553            continue;
2554        };
2555        if !is_self_update_staging_name(name) {
2556            continue;
2557        }
2558        let path = update_root.join(name);
2559        if claimed.contains(&path) {
2560            continue;
2561        }
2562        if validated_real_directory(&path, "self-update staging directory").is_err() {
2563            continue;
2564        }
2565        let aged_out = directory_age_ms(
2566            entry.metadata().ok().and_then(|meta| meta.modified().ok()),
2567            now,
2568        )
2569        .is_some_and(|age| age >= STALE_SELF_UPDATE_STATUS_TTL_MS);
2570        if obsolete.contains(&path) || !staging_holds_payload(&path) || aged_out {
2571            let _ = std::fs::remove_dir_all(&path);
2572        }
2573    }
2574}
2575
2576/// Whether a staging directory still holds something an install could use.
2577///
2578/// `cargo install --root <dir>` leaves zero-byte `.crates.toml` / `.crates2.json`
2579/// bookkeeping files behind even when it produced no binary, and the helper's
2580/// own cleanup deletes the payload first. So the presence of *a* file proves
2581/// nothing — a directory whose only contents are empty files is debris that can
2582/// never be installed from, and waiting out the TTL for it just keeps garbage
2583/// around. Only a non-empty file does, and the payload lives one level down in
2584/// `bin/`.
2585fn staging_holds_payload(path: &Path) -> bool {
2586    let Ok(entries) = std::fs::read_dir(path) else {
2587        return false;
2588    };
2589    for entry in entries.flatten() {
2590        let Ok(metadata) = entry.metadata() else {
2591            continue;
2592        };
2593        if metadata.is_file() {
2594            if metadata.len() > 0 {
2595                return true;
2596            }
2597            continue;
2598        }
2599        if metadata.is_dir()
2600            && std::fs::read_dir(entry.path()).is_ok_and(|nested| {
2601                nested.flatten().any(|nested| {
2602                    nested
2603                        .metadata()
2604                        .is_ok_and(|metadata| metadata.is_file() && metadata.len() > 0)
2605                })
2606            })
2607        {
2608            return true;
2609        }
2610    }
2611    false
2612}
2613
2614fn directory_age_ms(modified: Option<SystemTime>, now: i64) -> Option<i64> {
2615    let modified = modified?;
2616    let millis = modified.duration_since(UNIX_EPOCH).ok()?.as_millis();
2617    i64::try_from(millis).ok().map(|at| now.saturating_sub(at))
2618}
2619
2620#[cfg(windows)]
2621fn validated_windows_executable(path: &Path, label: &str) -> Result<PathBuf, String> {
2622    use std::io::Read;
2623
2624    let path = validated_regular_file(path, label)?;
2625    let mut file =
2626        std::fs::File::open(&path).map_err(|error| format!("could not open {label}: {error}"))?;
2627    let mut magic = [0u8; 2];
2628    file.read_exact(&mut magic)
2629        .map_err(|error| format!("could not read {label}: {error}"))?;
2630    if magic != *b"MZ" {
2631        return Err(format!("{label} is not a Windows executable"));
2632    }
2633    Ok(path)
2634}
2635
2636#[cfg(windows)]
2637fn system_powershell_path() -> Result<PathBuf, String> {
2638    use std::ffi::OsString;
2639    use std::os::windows::ffi::OsStringExt;
2640    use windows_sys::Win32::System::SystemInformation::GetWindowsDirectoryW;
2641
2642    let mut buffer = vec![0u16; 260];
2643    let system_root = loop {
2644        let length = unsafe {
2645            GetWindowsDirectoryW(
2646                buffer.as_mut_ptr(),
2647                u32::try_from(buffer.len()).unwrap_or(u32::MAX),
2648            )
2649        };
2650        if length == 0 {
2651            return Err(format!(
2652                "could not locate the Windows system directory: {}",
2653                std::io::Error::last_os_error()
2654            ));
2655        }
2656        let length = usize::try_from(length)
2657            .map_err(|error| format!("invalid Windows system directory length: {error}"))?;
2658        if length < buffer.len() {
2659            buffer.truncate(length);
2660            break PathBuf::from(OsString::from_wide(&buffer));
2661        }
2662        buffer.resize(length.saturating_add(1), 0);
2663    };
2664    let system_root = validated_real_directory(&system_root, "Windows system root")?;
2665    let powershell = validated_windows_executable(
2666        &system_root.join("System32/WindowsPowerShell/v1.0/powershell.exe"),
2667        "Windows PowerShell",
2668    )?;
2669    powershell
2670        .strip_prefix(&system_root)
2671        .map_err(|_| "Windows PowerShell is outside SystemRoot".to_string())?;
2672    Ok(powershell)
2673}
2674
2675#[cfg(windows)]
2676fn windows_update_helper_command(
2677    powershell: &Path,
2678    plan: &WindowsUpdatePlan,
2679    parent_pid: u32,
2680    staged_version: &str,
2681) -> std::process::Command {
2682    let mut command = std::process::Command::new(powershell);
2683    let powershell_modules = powershell
2684        .parent()
2685        .expect("validated PowerShell path has a parent")
2686        .join("Modules");
2687    command
2688        .args([
2689            "-NoLogo",
2690            "-NoProfile",
2691            "-NonInteractive",
2692            "-ExecutionPolicy",
2693            "Bypass",
2694            "-File",
2695        ])
2696        .arg(&plan.helper_script)
2697        .arg("-ParentPid")
2698        .arg(parent_pid.to_string())
2699        .arg("-StagingPath")
2700        .arg(&plan.staging_dir)
2701        .arg("-StagedPath")
2702        .arg(&plan.staged_exe)
2703        .arg("-StagedVersion")
2704        .arg(staged_version)
2705        .arg("-TargetPath")
2706        .arg(&plan.target_exe)
2707        .arg("-TempPath")
2708        .arg(&plan.replacement_temp)
2709        .arg("-BackupPath")
2710        .arg(&plan.backup_file)
2711        .arg("-RollbackDisplacedPath")
2712        .arg(&plan.rollback_displaced_file)
2713        .arg("-StatusPath")
2714        .arg(&plan.status_file)
2715        .current_dir(
2716            plan.status_file
2717                .parent()
2718                .expect("validated status path has an update-root parent"),
2719        )
2720        .env("PSModulePath", powershell_modules)
2721        .stdin(Stdio::null())
2722        .stdout(Stdio::null())
2723        .stderr(Stdio::null());
2724    command
2725}
2726
2727#[cfg(windows)]
2728fn write_windows_update_status(path: &Path, state: &str, message: &str) -> Result<(), String> {
2729    let data = serde_json::to_vec_pretty(&serde_json::json!({
2730        "state": state,
2731        "message": message,
2732        "parentPid": std::process::id(),
2733        "currentVersion": crate::VERSION,
2734        "updatedAtMs": now_ms(),
2735    }))
2736    .map_err(|error| error.to_string())?;
2737    std::fs::write(path, data)
2738        .map_err(|error| format!("could not write update status {}: {error}", path.display()))
2739}
2740
2741/// Machine-readable update inventory for the web UI.
2742///
2743/// The web UI needs the same answer as the startup notice without parsing
2744/// human-readable CLI output: installed versions, latest versions, and
2745/// whether each target can be updated from this install.
2746#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
2747#[serde(rename_all = "camelCase")]
2748pub struct UpdateInventory {
2749    pub current_version: String,
2750    /// Latest known registry observation. Failed refreshes do not advance it.
2751    pub last_checked_at: i64,
2752    pub host: UpdateInventoryEntry,
2753    pub extensions: Vec<UpdateInventoryEntry>,
2754}
2755
2756#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
2757#[serde(rename_all = "camelCase")]
2758pub struct UpdateInventoryEntry {
2759    pub name: String,
2760    pub current: String,
2761    #[serde(skip_serializing_if = "Option::is_none")]
2762    pub latest: Option<String>,
2763    pub updatable: bool,
2764    #[serde(skip_serializing_if = "Option::is_none")]
2765    pub reason: Option<String>,
2766}
2767
2768/// `rpi updates check --json`. Currently JSON is the only supported format so
2769/// callers get a stable contract; the command rejects other arguments rather
2770/// than silently inventing output.
2771pub async fn run_updates(args: &[String]) -> i32 {
2772    let refresh = match args {
2773        [command, flag] if command == "check" && flag == "--json" => false,
2774        [command, flag] if command == "refresh" && flag == "--json" => true,
2775        _ => {
2776            eprintln!("error: `rpi updates` accepts `check --json` or `refresh --json`");
2777            return 2;
2778        }
2779    };
2780    if refresh && !update_checks_disabled() {
2781        if let Ok(agent_dir) = crate::config::agent_dir() {
2782            refresh_update_cache(&agent_dir, startup_http_client()).await;
2783        }
2784    }
2785    let inventory = build_inventory_from_cache();
2786    match serde_json::to_string_pretty(&inventory) {
2787        Ok(json) => {
2788            println!("{json}");
2789            0
2790        }
2791        Err(error) => {
2792            eprintln!("error: could not serialize update inventory: {error}");
2793            1
2794        }
2795    }
2796}
2797
2798fn build_inventory_from_cache() -> UpdateInventory {
2799    let cache = crate::config::agent_dir()
2800        .ok()
2801        .and_then(|dir| read_cache(&dir.join(CACHE_FILE)))
2802        .unwrap_or_default();
2803    let host_latest = cache
2804        .rpi_latest
2805        .as_ref()
2806        .filter(|latest| is_newer(crate::VERSION, latest))
2807        .cloned();
2808    UpdateInventory {
2809        current_version: crate::VERSION.to_owned(),
2810        last_checked_at: last_successful_update_check(&cache),
2811        host: UpdateInventoryEntry {
2812            name: "rpi".into(),
2813            current: crate::VERSION.into(),
2814            updatable: host_latest.is_some(),
2815            latest: host_latest,
2816            reason: None,
2817        },
2818        extensions: installed_extension_inventory(
2819            &cache,
2820            crate::install::installed_native_packages(),
2821        ),
2822    }
2823}
2824
2825fn installed_extension_inventory(
2826    cache: &UpdateCache,
2827    packages: impl IntoIterator<Item = crate::install::InstalledNativePackage>,
2828) -> Vec<UpdateInventoryEntry> {
2829    packages
2830        .into_iter()
2831        .map(|package| {
2832            let supports_update = package.supports_registry_update();
2833            let latest = cache
2834                .native_packages
2835                .get(&native_cache_key(&package))
2836                .filter(|latest| supports_update && is_newer(&package.version, latest))
2837                .cloned();
2838            UpdateInventoryEntry {
2839                name: package.name.clone(),
2840                current: package.version,
2841                updatable: latest.is_some(),
2842                latest,
2843                reason: (!supports_update).then(|| "local-install".into()),
2844            }
2845        })
2846        .collect()
2847}
2848
2849#[cfg(test)]
2850mod tests {
2851    #[test]
2852    fn inventory_timestamp_advances_only_on_authoritative_checks() {
2853        let agent = real_tempdir();
2854        let path = agent.path().join(super::CACHE_FILE);
2855        let cached = serde_json::from_value(serde_json::json!({
2856            "checkedAt": 1000,
2857            "rpiLatest": "1.0.0",
2858            "nativePackages": {"demo":"2.0.0"},
2859            "freshness":{"rpi":2000,"nativePackages":{"demo":3000}}
2860        }))
2861        .unwrap();
2862        super::write_cache(&path, &cached).unwrap();
2863        assert_eq!(super::last_successful_update_check(&cached), 3000);
2864
2865        let failed = super::merge_and_write_cache(
2866            &path,
2867            super::RegistryLookup::TransientFailure,
2868            vec![("demo".into(), super::RegistryLookup::TransientFailure)],
2869        );
2870        assert_eq!(super::last_successful_update_check(&failed), 3000);
2871        assert!(failed.rpi_latest.is_none());
2872        assert!(failed.native_packages.is_empty());
2873        let before_check = super::now_ms();
2874        let checked =
2875            super::merge_and_write_cache(&path, super::RegistryLookup::Missing, Vec::new());
2876        assert_eq!(checked.checked_at, 1000);
2877        assert!(super::last_successful_update_check(&checked) >= before_check);
2878        let persisted = super::read_cache(&path).unwrap();
2879        assert_eq!(
2880            super::last_successful_update_check(&persisted),
2881            super::last_successful_update_check(&checked)
2882        );
2883    }
2884
2885    #[test]
2886    fn failed_refresh_uses_the_committed_cache_and_respects_concurrent_writes() {
2887        let agent = real_tempdir();
2888        let path = agent.path().join(super::CACHE_FILE);
2889        let host_observed_at = super::now_ms() - 200;
2890        let extension_observed_at = host_observed_at + 100;
2891        let cached = serde_json::from_value(serde_json::json!({
2892            "checkedAt": 1000,
2893            "rpiLatest": "1.0.0",
2894            "nativePackages": {"demo":"2.0.0"},
2895            "freshness": {"rpi":host_observed_at,"nativePackages":{"demo":extension_observed_at}}
2896        }))
2897        .unwrap();
2898        super::write_cache(&path, &cached).unwrap();
2899
2900        let report = super::merge_and_write_cache(
2901            &path,
2902            super::RegistryLookup::TransientFailure,
2903            vec![("demo".into(), super::RegistryLookup::TransientFailure)],
2904        );
2905        assert_eq!(report.rpi_latest.as_deref(), Some("1.0.0"));
2906        assert_eq!(report.native_packages["demo"], "2.0.0");
2907        assert_eq!(report.freshness.rpi, host_observed_at);
2908        assert_eq!(
2909            report.freshness.native_packages["demo"],
2910            extension_observed_at
2911        );
2912
2913        let _writer = super::try_lock_update_cache(&path).unwrap();
2914        let report = super::merge_and_write_cache(
2915            &path,
2916            super::RegistryLookup::Found("1.1.0".into()),
2917            Vec::new(),
2918        );
2919        assert_eq!(report.rpi_latest.as_deref(), Some("1.1.0"));
2920        let persisted = super::read_cache(&path).unwrap();
2921        assert_eq!(persisted.rpi_latest.as_deref(), Some("1.0.0"));
2922        assert_eq!(persisted.native_packages["demo"], "2.0.0");
2923    }
2924
2925    #[tokio::test]
2926    async fn invalid_http_proxy_does_not_disable_a_valid_https_update_proxy() {
2927        let _guard = crate::config::test_support::env_lock().lock().unwrap();
2928        let agent = real_tempdir();
2929        let _restore_config = RestoreConfigDir(std::env::var_os(crate::config::CONFIG_DIR_ENV));
2930        let keys = [
2931            "HTTP_PROXY",
2932            "http_proxy",
2933            "HTTPS_PROXY",
2934            "https_proxy",
2935            "ALL_PROXY",
2936            "all_proxy",
2937        ];
2938        let _restore_proxies = keys.map(RestoreEnv::capture);
2939        for key in keys {
2940            std::env::remove_var(key);
2941        }
2942        std::env::set_var(crate::config::CONFIG_DIR_ENV, agent.path());
2943        std::fs::write(
2944            agent.path().join("settings.json"),
2945            r#"{"httpProxy":"http://["}"#,
2946        )
2947        .unwrap();
2948        std::env::set_var("HTTP_PROXY", "http://[");
2949        std::env::set_var("HTTPS_PROXY", "http://127.0.0.1:1234");
2950        assert!(super::startup_http_client().is_some());
2951
2952        std::env::remove_var("HTTPS_PROXY");
2953        assert!(super::startup_http_client().is_none());
2954    }
2955
2956    #[test]
2957    fn update_inventory_reports_registry_updates_and_skips_local_installs() {
2958        let registry = crate::install::InstalledNativePackage {
2959            name: "registry-ext".into(),
2960            version: "1.0.0".into(),
2961            source: None,
2962            prebuilt: None,
2963            artifacts: Vec::new(),
2964        };
2965        let local = crate::install::InstalledNativePackage {
2966            name: "local-ext".into(),
2967            version: "1.0.0".into(),
2968            source: Some("local:preview".into()),
2969            prebuilt: None,
2970            artifacts: Vec::new(),
2971        };
2972        let cache = super::UpdateCache {
2973            native_packages: std::collections::BTreeMap::from([
2974                ("registry-ext".into(), "1.2.0".into()),
2975                ("local-ext".into(), "2.0.0".into()),
2976            ]),
2977            ..super::UpdateCache::default()
2978        };
2979        let entries = super::installed_extension_inventory(&cache, vec![registry, local]);
2980        assert_eq!(entries.len(), 2);
2981        assert_eq!(entries[0].name, "registry-ext");
2982        assert_eq!(entries[0].latest.as_deref(), Some("1.2.0"));
2983        assert!(entries[0].updatable);
2984        assert_eq!(entries[0].reason, None);
2985        assert_eq!(entries[1].name, "local-ext");
2986        assert_eq!(entries[1].reason.as_deref(), Some("local-install"));
2987        assert!(!entries[1].updatable);
2988    }
2989
2990    #[test]
2991    fn extension_update_notices_unify_commands_and_separate_source_caches() {
2992        let _guard = crate::config::test_support::env_lock()
2993            .lock()
2994            .unwrap_or_else(|p| p.into_inner());
2995        let agent = tempfile::tempdir().unwrap();
2996        let _restore = RestoreConfigDir(std::env::var_os(crate::config::CONFIG_DIR_ENV));
2997        std::env::set_var(crate::config::CONFIG_DIR_ENV, agent.path());
2998        let record: crate::install::InstalledNativePackage = serde_json::from_value(serde_json::json!({
2999            "name":"demo", "version":"1.0.0", "source":"prebuilt:https://github.com/owner/repo", "artifacts":["custom.dll"],
3000            "prebuilt":{"repository":"https://github.com/owner/repo","target":"x86_64-pc-windows-msvc",
3001                "manifest_sha256":"a".repeat(64),"source_commit":"b".repeat(40),"sdk_version":"0.3.23","plugin_abi":4,
3002                "archive_sha256":"c".repeat(64),"library_sha256":"d".repeat(64),"custom_repository":true}
3003        })).unwrap();
3004        std::fs::write(
3005            agent.path().join("native-packages.json"),
3006            serde_json::to_vec(&[record.clone()]).unwrap(),
3007        )
3008        .unwrap();
3009        let mut cache = super::UpdateCache::default();
3010        cache.native_packages.insert("demo".into(), "99.0.0".into()); // old Cargo source cannot supply a prebuilt update
3011        assert!(super::report_from_cache(&cache).notices.is_empty());
3012        cache
3013            .native_packages
3014            .insert(super::native_cache_key(&record), "2.0.0".into());
3015        let report = super::report_from_cache(&cache);
3016        assert_eq!(report.notices.len(), 1);
3017        assert_eq!(report.notices[0].latest, "2.0.0");
3018        assert_eq!(report.notices[0].command, "rpi extension update demo");
3019        let mut other = record.clone();
3020        other.prebuilt.as_mut().unwrap().repository = "https://github.com/another/repo".into();
3021        assert_ne!(
3022            super::native_cache_key(&record),
3023            super::native_cache_key(&other)
3024        );
3025
3026        // A successful install updates the registry. A cached remote version
3027        // must no longer advertise an update after that version is installed.
3028        let mut updated = record.clone();
3029        updated.version = "2.0.0".into();
3030        std::fs::write(
3031            agent.path().join("native-packages.json"),
3032            serde_json::to_vec(&[updated]).unwrap(),
3033        )
3034        .unwrap();
3035        assert!(super::report_from_cache(&cache).notices.is_empty());
3036        other = record.clone();
3037        other.prebuilt.as_mut().unwrap().custom_repository = false;
3038        assert_ne!(
3039            super::native_cache_key(&record),
3040            super::native_cache_key(&other)
3041        );
3042        let mut cargo = record.clone();
3043        cargo.source = None;
3044        cargo.prebuilt = None;
3045        for (package, command) in [
3046            (other, "rpi extension update demo"),
3047            (cargo, "rpi extension update demo"),
3048        ] {
3049            cache
3050                .native_packages
3051                .insert(super::native_cache_key(&package), "2.0.0".into());
3052            std::fs::write(
3053                agent.path().join("native-packages.json"),
3054                serde_json::to_vec(&[package]).unwrap(),
3055            )
3056            .unwrap();
3057            let report = super::report_from_cache(&cache);
3058            assert_eq!(report.notices.len(), 1);
3059            assert_eq!(report.notices[0].command, command);
3060        }
3061    }
3062
3063    /// Fixtures may live under an ambient TEMP that is itself a junction
3064    /// (e.g. `D:\Temp` on some Windows hosts). Ancestor links are resolved by
3065    /// the path validation rather than refused, so a plain `tempdir()` is a
3066    /// valid fixture — and using one keeps these tests honest about that.
3067    fn real_tempdir() -> tempfile::TempDir {
3068        tempfile::Builder::new()
3069            .prefix("rpi-update-test-")
3070            .tempdir()
3071            .unwrap()
3072    }
3073
3074    /// The path a fixture resolves to once production validation has seen it.
3075    ///
3076    /// Every validated call site canonicalizes and normalizes a path before it
3077    /// stores or compares it, so a test asserting against a production-derived
3078    /// path has to resolve its own fixture the same way. `real_tempdir()` stays
3079    /// unresolved on purpose — that is what keeps these tests honest about an
3080    /// ambient temp root that is itself a link — but on macOS `/var` is a link
3081    /// to `/private/var`, so the raw fixture path and the resolved production
3082    /// path are different strings for the same directory. Comparing them
3083    /// directly fails for a reason that has nothing to do with the code under
3084    /// test, and does so only on hosts whose temp root is reached through a
3085    /// link, which is why a Linux-only CI never saw it.
3086    fn as_production_resolves(path: &Path) -> std::path::PathBuf {
3087        super::normalize_windows_path(std::fs::canonicalize(path).unwrap())
3088    }
3089
3090    use std::collections::BTreeMap;
3091    use std::ffi::OsString;
3092    use std::path::Path;
3093    use std::sync::atomic::{AtomicUsize, Ordering};
3094    use std::sync::Arc;
3095
3096    #[cfg(unix)]
3097    use super::{activate_direct_update, build_direct_update_plan};
3098    #[cfg(windows)]
3099    use super::{
3100        build_windows_update_plan, preflight_windows_replacement, system_powershell_path,
3101        windows_update_helper_command, write_windows_update_status, WINDOWS_UPDATE_HELPER,
3102    };
3103    use super::{
3104        cargo_home_is_project_local, cargo_install_command, collect_bounded,
3105        create_self_update_command_dir, fetch_crates_url, is_newer, parse_rpi_version_output,
3106        path_is_within, results_with_individual_cache_fallback, validate_staged_rpi_version_output,
3107        RegistryLookup, CACHE_FALLBACK_MAX_AGE_MS, UPDATE_CHECK_CONCURRENCY,
3108    };
3109
3110    struct RestoreConfigDir(Option<OsString>);
3111
3112    impl Drop for RestoreConfigDir {
3113        fn drop(&mut self) {
3114            match self.0.take() {
3115                Some(value) => std::env::set_var(crate::config::CONFIG_DIR_ENV, value),
3116                None => std::env::remove_var(crate::config::CONFIG_DIR_ENV),
3117            }
3118        }
3119    }
3120
3121    struct RestoreEnv {
3122        name: &'static str,
3123        value: Option<OsString>,
3124    }
3125
3126    impl RestoreEnv {
3127        fn capture(name: &'static str) -> Self {
3128            Self {
3129                name,
3130                value: std::env::var_os(name),
3131            }
3132        }
3133    }
3134
3135    impl Drop for RestoreEnv {
3136        fn drop(&mut self) {
3137            match self.value.take() {
3138                Some(value) => std::env::set_var(self.name, value),
3139                None => std::env::remove_var(self.name),
3140            }
3141        }
3142    }
3143
3144    #[cfg(windows)]
3145    fn fake_windows_executable(path: &Path, marker: &[u8]) {
3146        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
3147        let mut bytes = b"MZ".to_vec();
3148        bytes.extend_from_slice(marker);
3149        std::fs::write(path, bytes).unwrap();
3150    }
3151
3152    #[cfg(unix)]
3153    fn fake_unix_rpi(path: &Path, version: &str, fail_after_rename_to: Option<&str>) {
3154        use std::os::unix::fs::PermissionsExt;
3155
3156        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
3157        let failure = fail_after_rename_to.map_or_else(String::new, |name| {
3158            format!(
3159                "case \"$0\" in\n  */{name}) echo 'post-replace failure' >&2; exit 1 ;;\nesac\n"
3160            )
3161        });
3162        std::fs::write(
3163            path,
3164            format!("#!/bin/sh\n{failure}printf 'rpi {version}\\n'\n"),
3165        )
3166        .unwrap();
3167        std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755)).unwrap();
3168    }
3169
3170    fn write_test_update_status_at(path: &Path, state: &str, message: &str, updated_at_ms: i64) {
3171        let mut status = serde_json::json!({
3172            "state": state,
3173            "message": message,
3174        });
3175        if updated_at_ms > 0 {
3176            status["updatedAtMs"] = serde_json::json!(updated_at_ms);
3177        }
3178        std::fs::write(path, serde_json::to_vec(&status).unwrap()).unwrap();
3179    }
3180
3181    fn write_test_update_status(path: &Path, state: &str, message: &str) {
3182        std::fs::write(
3183            path,
3184            serde_json::to_vec(&serde_json::json!({
3185                "state": state,
3186                "message": message,
3187            }))
3188            .unwrap(),
3189        )
3190        .unwrap();
3191    }
3192
3193    #[test]
3194    fn path_validation_resolves_ancestor_links_but_refuses_a_link_leaf() {
3195        let temp = real_tempdir();
3196        // Real targets, plus a link directory that points at one of them.
3197        let real_dir = temp.path().join("real-dir");
3198        let real_file = temp.path().join("real-file.exe");
3199        std::fs::create_dir_all(&real_dir).unwrap();
3200        std::fs::write(&real_file, b"payload").unwrap();
3201
3202        let link_dir = temp.path().join("link-dir");
3203        let link_file = temp.path().join("link-file.exe");
3204        #[cfg(unix)]
3205        let linked = {
3206            std::os::unix::fs::symlink(&real_dir, &link_dir).unwrap();
3207            std::os::unix::fs::symlink(&real_file, &link_file).unwrap();
3208            true
3209        };
3210        #[cfg(windows)]
3211        let linked = {
3212            // Junctions need no elevation; file symlinks do, so skip the file
3213            // half when this process cannot create one.
3214            let dir_ok = std::process::Command::new("cmd")
3215                .args(["/c", "mklink", "/J"])
3216                .arg(&link_dir)
3217                .arg(&real_dir)
3218                .output()
3219                .map(|out| out.status.success())
3220                .unwrap_or(false);
3221            if dir_ok {
3222                let file_ok = std::os::windows::fs::symlink_file(&real_file, &link_file).is_ok();
3223                if !file_ok {
3224                    eprintln!("skipping the file-link half: no symlink privilege");
3225                }
3226            }
3227            dir_ok
3228        };
3229        if !linked {
3230            eprintln!("skipping: this platform could not create the link fixture");
3231            return;
3232        }
3233
3234        // A file *below* a linked directory resolves: the link is an ancestor,
3235        // not the thing being written.
3236        let through_link = link_dir.join("nested").join("leaf.exe");
3237        std::fs::create_dir_all(through_link.parent().unwrap()).unwrap();
3238        std::fs::write(&through_link, b"payload").unwrap();
3239        super::validated_regular_file(&through_link, "file below a linked directory").unwrap();
3240        assert_eq!(
3241            std::fs::canonicalize(&link_dir).unwrap(),
3242            std::fs::canonicalize(&real_dir).unwrap(),
3243        );
3244
3245        // A link *leaf* is still refused, and the error names both paths.
3246        let error = super::validated_real_directory(&link_dir, "linked directory").unwrap_err();
3247        assert!(error.contains("link or junction"), "{error}");
3248        assert!(error.contains(&link_dir.display().to_string()), "{error}");
3249
3250        if link_file.exists() {
3251            let error = super::validated_regular_file(&link_file, "linked file").unwrap_err();
3252            assert!(error.contains("link or junction"), "{error}");
3253            assert!(error.contains(&link_file.display().to_string()), "{error}");
3254            assert!(error.contains(&real_file.display().to_string()), "{error}");
3255        }
3256
3257        // The link leaf check must not be a blanket refusal: the real targets
3258        // still validate.
3259        super::validated_real_directory(&real_dir, "real directory").unwrap();
3260        super::validated_regular_file(&real_file, "real file").unwrap();
3261    }
3262
3263    #[test]
3264    fn cargo_self_update_staging_is_passed_as_a_structured_argument() {
3265        let temp = real_tempdir();
3266        let staging = temp.path().join("staging");
3267        let command_dir = temp.path().join("command");
3268        std::fs::create_dir_all(&staging).unwrap();
3269        std::fs::create_dir_all(&command_dir).unwrap();
3270        let command = cargo_install_command(Some(&staging), &command_dir).unwrap();
3271        let args = command.get_args().map(OsString::from).collect::<Vec<_>>();
3272
3273        assert_eq!(command.get_program(), "cargo");
3274        assert_eq!(args.len(), 7);
3275        assert_eq!(args[0], "install");
3276        assert_eq!(args[1], "--root");
3277        assert_eq!(args[2], staging.as_os_str());
3278        assert_eq!(args[3], "rpi-cli");
3279        assert_eq!(args[4], "--locked");
3280        assert_eq!(args[5], "--force");
3281        // Suppresses cargo's "add this to your PATH" advice, which names the
3282        // staging root that the atomic replace is about to consume.
3283        assert_eq!(args[6], "--quiet");
3284        // The command runs in the resolved directory, not the unresolved
3285        // fixture path: `cargo_install_command` validates it first.
3286        assert_eq!(
3287            command.get_current_dir(),
3288            Some(as_production_resolves(&command_dir).as_path())
3289        );
3290    }
3291
3292    #[cfg(unix)]
3293    #[test]
3294    fn direct_update_replaces_the_selected_target_and_rejects_downgrades() {
3295        let temp = real_tempdir();
3296        let staging = temp.path().join("staging");
3297        let staged = staging.join("bin/rpi");
3298        let target = temp.path().join("target/rpi-current");
3299        fake_unix_rpi(&staged, "9.9.9", None);
3300        fake_unix_rpi(&target, crate::VERSION, None);
3301        let expected = std::fs::read(&staged).unwrap();
3302
3303        let plan = build_direct_update_plan(&staging, &target).unwrap();
3304        assert_eq!(activate_direct_update(&plan).unwrap().to_string(), "9.9.9");
3305        assert_eq!(std::fs::read(&target).unwrap(), expected);
3306        assert!(!plan.replacement_temp.exists());
3307        assert!(!plan.backup_file.exists());
3308
3309        fake_unix_rpi(&staged, "0.0.1", None);
3310        let plan = build_direct_update_plan(&staging, &target).unwrap();
3311        let error = activate_direct_update(&plan).unwrap_err();
3312        assert!(error.contains("older version"), "{error}");
3313        assert_eq!(std::fs::read(&target).unwrap(), expected);
3314    }
3315
3316    #[cfg(unix)]
3317    #[test]
3318    fn direct_update_rolls_back_when_post_replace_validation_fails() {
3319        let temp = real_tempdir();
3320        let staging = temp.path().join("staging");
3321        let staged = staging.join("bin/rpi");
3322        let target = temp.path().join("target/rpi-current");
3323        fake_unix_rpi(&staged, "9.9.9", Some("rpi-current"));
3324        fake_unix_rpi(&target, crate::VERSION, None);
3325        let original = std::fs::read(&target).unwrap();
3326
3327        let plan = build_direct_update_plan(&staging, &target).unwrap();
3328        let error = activate_direct_update(&plan).unwrap_err();
3329
3330        assert!(error.contains("restored the previous"), "{error}");
3331        assert_eq!(std::fs::read(&target).unwrap(), original);
3332        assert!(!plan.replacement_temp.exists());
3333        assert!(!plan.backup_file.exists());
3334    }
3335
3336    #[test]
3337    fn self_update_arguments_are_parsed_explicitly() {
3338        let args = |list: &[&str]| list.iter().map(|arg| arg.to_string()).collect::<Vec<_>>();
3339        assert_eq!(
3340            super::parse_self_update_args(&args(&["--build", "--force"])),
3341            super::SelfUpdateArgs::Run {
3342                force: true,
3343                build: true,
3344                channel: super::UpdateChannel::Stable,
3345                cdn_base: None,
3346            }
3347        );
3348        assert_eq!(
3349            super::parse_self_update_args(&args(&[])),
3350            super::SelfUpdateArgs::Run {
3351                force: false,
3352                build: false,
3353                channel: super::UpdateChannel::Stable,
3354                cdn_base: None,
3355            }
3356        );
3357        for flag in ["--force", "-f"] {
3358            assert_eq!(
3359                super::parse_self_update_args(&args(&[flag])),
3360                super::SelfUpdateArgs::Run {
3361                    force: true,
3362                    build: false,
3363                    channel: super::UpdateChannel::Stable,
3364                    cdn_base: None,
3365                }
3366            );
3367        }
3368        assert_eq!(
3369            super::parse_self_update_args(&args(&["preview"])),
3370            super::SelfUpdateArgs::Run {
3371                force: false,
3372                build: false,
3373                channel: super::UpdateChannel::Preview,
3374                cdn_base: None,
3375            }
3376        );
3377        for flag in ["--help", "-h"] {
3378            assert_eq!(
3379                super::parse_self_update_args(&args(&[flag])),
3380                super::SelfUpdateArgs::Help
3381            );
3382        }
3383        // `--help` wins wherever it appears, and unknown flags are a usage
3384        // error rather than being silently ignored.
3385        assert_eq!(
3386            super::parse_self_update_args(&args(&["--force", "--help"])),
3387            super::SelfUpdateArgs::Help
3388        );
3389        assert_eq!(
3390            super::parse_self_update_args(&args(&["--nope"])),
3391            super::SelfUpdateArgs::Usage
3392        );
3393    }
3394
3395    #[test]
3396    fn default_self_update_requires_a_release_and_never_falls_back_to_cargo() {
3397        let staging = tempfile::tempdir().unwrap();
3398        let error = super::prepare_self_update(staging.path(), false, None, None).unwrap_err();
3399        assert!(error.contains("no verified release version"));
3400        assert_eq!(std::fs::read_dir(staging.path()).unwrap().count(), 0);
3401    }
3402
3403    #[test]
3404    fn self_update_honors_env_and_early_dispatched_offline_flag() {
3405        let _guard = crate::config::test_support::env_lock().lock().unwrap();
3406        let _restore = RestoreEnv::capture(crate::args::RPI_OFFLINE_ENV);
3407
3408        std::env::set_var(crate::args::RPI_OFFLINE_ENV, "tRuE");
3409        assert_eq!(super::run_self_update(&[]), 0);
3410
3411        std::env::set_var(crate::args::RPI_OFFLINE_ENV, "0");
3412        assert_eq!(super::run_self_update(&["--offline".into()]), 0);
3413        assert_eq!(
3414            std::env::var(crate::args::RPI_OFFLINE_ENV).as_deref(),
3415            Ok("1")
3416        );
3417    }
3418
3419    #[tokio::test]
3420    async fn offline_skips_rpi_startup_checks_before_cache_io() {
3421        let _guard = crate::config::test_support::env_lock().lock().unwrap();
3422        let _restore_config = RestoreConfigDir(std::env::var_os(crate::config::CONFIG_DIR_ENV));
3423        let _restore_offline = RestoreEnv::capture(crate::args::RPI_OFFLINE_ENV);
3424        let _restore_disabled = RestoreEnv::capture("RPI_DISABLE_UPDATE_CHECK");
3425        let temp = real_tempdir();
3426        let agent = temp.path().join("offline-agent");
3427        std::env::set_var(crate::config::CONFIG_DIR_ENV, &agent);
3428        std::env::set_var(crate::args::RPI_OFFLINE_ENV, "YES");
3429        std::env::remove_var("RPI_DISABLE_UPDATE_CHECK");
3430
3431        let report = super::check_rpi_startup().await;
3432
3433        assert_eq!(report, super::UpdateReport::default());
3434        assert!(
3435            !agent.exists(),
3436            "offline checks must not create the update cache directory"
3437        );
3438    }
3439
3440    #[tokio::test]
3441    async fn inventory_refresh_preserves_self_update_failure_for_startup() {
3442        let _guard = crate::config::test_support::env_lock().lock().unwrap();
3443        let _restore_config = RestoreConfigDir(std::env::var_os(crate::config::CONFIG_DIR_ENV));
3444        let _restore_offline = RestoreEnv::capture(crate::args::RPI_OFFLINE_ENV);
3445        let temp = real_tempdir();
3446        let agent = temp.path().join("agent");
3447        let update_root = agent.join("self-update");
3448        std::fs::create_dir_all(&update_root).unwrap();
3449        let failed = update_root.join("status-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json");
3450        write_test_update_status(&failed, "failed", "permission denied");
3451        std::env::set_var(crate::config::CONFIG_DIR_ENV, &agent);
3452        std::env::set_var(crate::args::RPI_OFFLINE_ENV, "1");
3453
3454        assert_eq!(
3455            super::run_updates(&["refresh".into(), "--json".into()]).await,
3456            0
3457        );
3458        super::refresh_update_cache(&agent, None).await;
3459        assert!(failed.exists());
3460
3461        let report = super::check_rpi_startup().await;
3462        assert_eq!(report.warnings.len(), 1);
3463        assert!(report.warnings[0].message.contains("permission denied"));
3464        assert!(!failed.exists());
3465    }
3466
3467    #[test]
3468    fn completed_self_update_statuses_are_consumed_once() {
3469        let temp = real_tempdir();
3470        let agent = temp.path().join("agent");
3471        let update_root = agent.join("self-update");
3472        std::fs::create_dir_all(&update_root).unwrap();
3473        let failed = update_root.join("status-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json");
3474        let succeeded = update_root.join("status-bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb.json");
3475        let waiting = update_root.join("status-cccccccccccccccccccccccccccccccc.json");
3476        let temporary = update_root.join("status-dddddddddddddddddddddddddddddddd.json.tmp");
3477        let malformed = update_root.join("status-eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee.json");
3478        let invalid_name = update_root.join("status-not-a-uuid.json");
3479        write_test_update_status(&failed, "failed", "permission\u{1b}[31m\r\n denied\u{7}");
3480        write_test_update_status(&succeeded, "succeeded", "done");
3481        write_test_update_status(&waiting, "waiting", "still running");
3482        write_test_update_status(&temporary, "failed", "not published");
3483        std::fs::write(&malformed, b"{not-json").unwrap();
3484        write_test_update_status(&invalid_name, "failed", "invalid name");
3485
3486        let warnings = super::consume_self_update_statuses(&agent);
3487
3488        assert_eq!(warnings.len(), 1);
3489        assert!(warnings[0]
3490            .message
3491            .contains("rpi update failed: permission [31m denied"));
3492        assert!(!warnings[0].message.chars().any(char::is_control));
3493        assert_eq!(warnings[0].command, "rpi update");
3494        assert!(!failed.exists());
3495        // A `succeeded` record is the receipt for the version now installed —
3496        // `rpi update` prints its path — so it survives consumption instead of
3497        // being deleted the moment the next start looks at it.
3498        assert!(succeeded.exists());
3499        assert!(waiting.exists());
3500        assert!(temporary.exists());
3501        assert!(malformed.exists());
3502        assert!(invalid_name.exists());
3503        // The failure is reported once: the record is gone, the kept one is not
3504        // a failure, and the young `waiting` record says nothing.
3505        assert!(super::consume_self_update_statuses(&agent).is_empty());
3506        assert!(succeeded.exists());
3507    }
3508
3509    #[test]
3510    fn stale_and_orphaned_self_update_records_are_pruned() {
3511        let temp = real_tempdir();
3512        let agent = temp.path().join("agent");
3513        std::fs::create_dir_all(&agent).unwrap();
3514        // `consume_self_update_statuses` resolves the agent directory before it
3515        // derives any staging path from it, so the fixture starts from the same
3516        // resolved path. Otherwise a staging directory this test records in a
3517        // status file would never compare equal to the one pruning computes,
3518        // and the pruning under test would silently not run.
3519        let agent = as_production_resolves(&agent);
3520        let update_root = agent.join("self-update");
3521        std::fs::create_dir_all(&update_root).unwrap();
3522        let name =
3523            |token: char| update_root.join(format!("status-{}.json", token.to_string().repeat(32)));
3524        let now = super::now_ms();
3525        let stale_ms = now - super::STALE_SELF_UPDATE_STATUS_TTL_MS - 60_000;
3526
3527        // Live run: recent `waiting` record that owns its staging directory.
3528        let live_status = name('1');
3529        let live_staging = update_root.join("pending-Live001");
3530        std::fs::create_dir_all(live_staging.join("bin")).unwrap();
3531        std::fs::write(live_staging.join("bin").join("rpi.exe"), b"payload").unwrap();
3532        std::fs::write(
3533            &live_status,
3534            serde_json::to_vec(&serde_json::json!({
3535                "state": "waiting",
3536                "staging": live_staging,
3537                "updatedAtMs": now - 1000,
3538            }))
3539            .unwrap(),
3540        )
3541        .unwrap();
3542
3543        // Abandoned run: the helper died, so the record aged out and the
3544        // payload it claims is debris.
3545        let dead_status = name('2');
3546        let dead_staging = update_root.join("pending-Dead002");
3547        std::fs::create_dir_all(dead_staging.join("bin")).unwrap();
3548        std::fs::write(dead_staging.join("bin").join("rpi.exe"), b"payload").unwrap();
3549        write_test_update_status_at(&dead_status, "preparing", "installing", stale_ms);
3550        // Name the staging directory in the stale record, the way the Windows
3551        // helper does: that is the evidence its payload is debris even though
3552        // the directory's own timestamp looks recent.
3553        let mut dead =
3554            serde_json::from_slice::<serde_json::Value>(&std::fs::read(&dead_status).unwrap())
3555                .unwrap();
3556        dead["staging"] = serde_json::json!(dead_staging);
3557        std::fs::write(&dead_status, serde_json::to_vec(&dead).unwrap()).unwrap();
3558
3559        // Orphan: no status file ever named it, and it was created long ago.
3560        let orphan = update_root.join("pending-Orphan3");
3561        std::fs::create_dir_all(orphan.join("bin")).unwrap();
3562        std::fs::write(orphan.join("bin").join("rpi.exe"), b"payload").unwrap();
3563
3564        // Debris that can never be serving an update: an empty staging
3565        // directory, even while it is brand new.
3566        let empty = update_root.join("pending-Empty04");
3567        std::fs::create_dir(&empty).unwrap();
3568
3569        // Not ours to touch: the name is not a tempfile label.
3570        let foreign = update_root.join("pending-not-ours");
3571        std::fs::create_dir_all(&foreign).unwrap();
3572        std::fs::write(foreign.join("keep"), b"keep").unwrap();
3573
3574        let warnings = super::consume_self_update_statuses(&agent);
3575
3576        assert!(warnings.is_empty());
3577        assert!(live_status.exists(), "a live run's record must survive");
3578        assert!(live_staging.exists(), "a live run's staging must survive");
3579        assert!(!dead_status.exists());
3580        assert!(!dead_staging.exists());
3581        // Pruning only deletes a populated directory it can prove is old; an
3582        // untimestamped orphan is left for a later pass rather than guessed at.
3583        assert!(orphan.exists());
3584        // An empty directory cannot be serving an update, whatever its age.
3585        assert!(!empty.exists());
3586        assert!(foreign.exists());
3587    }
3588
3589    #[test]
3590    fn completed_records_survive_and_supersede_leftovers() {
3591        let temp = real_tempdir();
3592        let agent = temp.path().join("agent");
3593        let update_root = agent.join("self-update");
3594        std::fs::create_dir_all(&update_root).unwrap();
3595        let now = super::now_ms();
3596        let staging = update_root.join("pending-Done001");
3597        std::fs::create_dir_all(staging.join("bin")).unwrap();
3598        std::fs::write(staging.join("bin").join("rpi.exe"), b"payload").unwrap();
3599
3600        // A `waiting` leftover naming the same directory as a completed run.
3601        let leftover = update_root.join(format!("status-{}.json", "3".repeat(32)));
3602        std::fs::write(
3603            &leftover,
3604            serde_json::to_vec(&serde_json::json!({
3605                "state": "waiting",
3606                "staging": staging,
3607                "updatedAtMs": now,
3608            }))
3609            .unwrap(),
3610        )
3611        .unwrap();
3612
3613        let recent = update_root.join(format!("status-{}.json", "4".repeat(32)));
3614        std::fs::write(
3615            &recent,
3616            serde_json::to_vec(&serde_json::json!({
3617                "state": "succeeded",
3618                "message": "rpi executable replaced successfully",
3619                "staging": staging,
3620                "updatedAtMs": now,
3621            }))
3622            .unwrap(),
3623        )
3624        .unwrap();
3625
3626        let aged = update_root.join(format!("status-{}.json", "5".repeat(32)));
3627        std::fs::write(
3628            &aged,
3629            serde_json::to_vec(&serde_json::json!({
3630                "state": "succeeded",
3631                "message": "rpi executable replaced successfully",
3632                "updatedAtMs": now - super::COMPLETED_SELF_UPDATE_STATUS_TTL_MS - 60_000,
3633            }))
3634            .unwrap(),
3635        )
3636        .unwrap();
3637
3638        assert!(super::consume_self_update_statuses(&agent).is_empty());
3639
3640        // The receipt for the installed version is kept until it ages out.
3641        assert!(recent.exists());
3642        assert!(!aged.exists());
3643        // The completed record owns the staging directory, so the leftover
3644        // `waiting` record that names it is debris; the directory itself is
3645        // still referenced, so it stays.
3646        assert!(!leftover.exists());
3647        assert!(staging.exists());
3648    }
3649
3650    #[test]
3651    fn self_update_status_validation_rejects_escape_and_links() {
3652        let temp = real_tempdir();
3653        let agent = temp.path().join("agent");
3654        let update_root = agent.join("self-update");
3655        let outside_root = temp.path().join("outside");
3656        std::fs::create_dir_all(&update_root).unwrap();
3657        std::fs::create_dir_all(&outside_root).unwrap();
3658        let name = "status-ffffffffffffffffffffffffffffffff.json";
3659        let outside = outside_root.join(name);
3660        write_test_update_status(&outside, "failed", "outside");
3661
3662        assert!(super::validated_self_update_status_file(&update_root, &outside).is_err());
3663
3664        let linked = update_root.join(name);
3665        #[cfg(unix)]
3666        std::os::unix::fs::symlink(&outside, &linked).unwrap();
3667        #[cfg(windows)]
3668        let link_created = std::os::windows::fs::symlink_file(&outside, &linked).is_ok();
3669        #[cfg(unix)]
3670        let link_created = true;
3671        if link_created {
3672            assert!(super::validated_self_update_status_file(&update_root, &linked).is_err());
3673            assert!(super::consume_self_update_statuses(&agent).is_empty());
3674            assert!(outside.exists());
3675        }
3676    }
3677
3678    #[test]
3679    fn cargo_self_update_without_staging_never_inherits_the_callers_cwd() {
3680        let temp = real_tempdir();
3681        let command_dir = temp.path().join("isolated");
3682        std::fs::create_dir_all(&command_dir).unwrap();
3683
3684        let command = cargo_install_command(None, &command_dir).unwrap();
3685        let args = command.get_args().map(OsString::from).collect::<Vec<_>>();
3686
3687        assert_eq!(
3688            args,
3689            ["install", "rpi-cli", "--locked", "--force", "--quiet"]
3690                .into_iter()
3691                .map(OsString::from)
3692                .collect::<Vec<_>>()
3693        );
3694        assert_eq!(
3695            command.get_current_dir(),
3696            Some(as_production_resolves(&command_dir).as_path())
3697        );
3698        assert_ne!(
3699            command.get_current_dir(),
3700            std::env::current_dir().ok().as_deref()
3701        );
3702        for variable in [
3703            "RUSTC_WRAPPER",
3704            "RUSTC_WORKSPACE_WRAPPER",
3705            "CARGO_BUILD_RUSTC_WRAPPER",
3706            "CARGO_BUILD_RUSTC_WORKSPACE_WRAPPER",
3707        ] {
3708            assert!(command
3709                .get_envs()
3710                .any(|(name, value)| name == variable && value.is_none()));
3711        }
3712        assert!(cargo_install_command(None, Path::new("relative-command-dir")).is_err());
3713
3714        let generated = create_self_update_command_dir().unwrap();
3715        let caller = std::fs::canonicalize(std::env::current_dir().unwrap()).unwrap();
3716        assert!(generated.path().is_absolute());
3717        assert!(!path_is_within(generated.path(), &caller));
3718    }
3719
3720    #[test]
3721    fn project_local_cargo_home_is_rejected_even_when_its_leaf_is_missing() {
3722        let temp = real_tempdir();
3723        let project = temp.path().join("project");
3724        let global = temp.path().join("global-cargo");
3725        std::fs::create_dir_all(&project).unwrap();
3726        std::fs::create_dir_all(&global).unwrap();
3727        let project = std::fs::canonicalize(project).unwrap();
3728
3729        assert!(cargo_home_is_project_local(&project.join(".cargo-home"), &project).unwrap());
3730        assert!(cargo_home_is_project_local(&project, &project).unwrap());
3731        assert!(!cargo_home_is_project_local(&global, &project).unwrap());
3732        assert!(cargo_home_is_project_local(Path::new("relative"), &project).is_err());
3733    }
3734
3735    #[cfg(windows)]
3736    #[test]
3737    fn windows_update_helper_atomically_replaces_a_valid_target() {
3738        let temp = real_tempdir();
3739        let staging = temp.path().join("staging 'semi;& with spaces");
3740        let staged = staging.join("bin/rpi.exe");
3741        let target = temp.path().join("target 'semi;& with spaces/rpi-copy.exe");
3742        fake_windows_executable(&staged, b"new-version");
3743        fake_windows_executable(&target, b"old-version");
3744        let expected = std::fs::read(&staged).unwrap();
3745        let plan = build_windows_update_plan(
3746            &staging,
3747            &target,
3748            &temp
3749                .path()
3750                .join("status-00000000000000000000000000000000.json"),
3751        )
3752        .unwrap();
3753        preflight_windows_replacement(&plan).unwrap();
3754        std::fs::write(&plan.helper_script, WINDOWS_UPDATE_HELPER).unwrap();
3755        write_windows_update_status(&plan.status_file, "scheduled", "test").unwrap();
3756
3757        let powershell = system_powershell_path().unwrap();
3758        let mut command =
3759            windows_update_helper_command(&powershell, &plan, i32::MAX as u32, "9.9.9");
3760        let args = command.get_args().map(OsString::from).collect::<Vec<_>>();
3761        for (flag, expected) in [
3762            ("-StagingPath", &plan.staging_dir),
3763            ("-StagedPath", &plan.staged_exe),
3764            ("-TargetPath", &plan.target_exe),
3765            ("-TempPath", &plan.replacement_temp),
3766            ("-BackupPath", &plan.backup_file),
3767            ("-RollbackDisplacedPath", &plan.rollback_displaced_file),
3768            ("-StatusPath", &plan.status_file),
3769        ] {
3770            let index = args.iter().position(|arg| arg == flag).unwrap();
3771            assert_eq!(args[index + 1], expected.as_os_str());
3772        }
3773        let version_index = args.iter().position(|arg| arg == "-StagedVersion").unwrap();
3774        assert_eq!(args[version_index + 1], "9.9.9");
3775        assert_eq!(command.get_current_dir(), plan.status_file.parent());
3776        assert!(command.get_envs().any(|(name, value)| {
3777            name == "PSModulePath"
3778                && value == Some(powershell.parent().unwrap().join("Modules").as_os_str())
3779        }));
3780        let status = command.status().unwrap();
3781
3782        let status_text = std::fs::read_to_string(&plan.status_file).unwrap();
3783        assert!(
3784            status.success(),
3785            "helper exited with {status}: {status_text}"
3786        );
3787        assert_eq!(std::fs::read(&target).unwrap(), expected);
3788        assert!(!staging.exists());
3789        assert!(!plan.replacement_temp.exists());
3790        assert!(!plan.backup_file.exists());
3791        assert!(!plan.rollback_displaced_file.exists());
3792        let status: serde_json::Value = serde_json::from_str(&status_text).unwrap();
3793        assert_eq!(status["state"], "succeeded");
3794        assert_eq!(status["stagedVersion"], "9.9.9");
3795    }
3796
3797    #[cfg(windows)]
3798    #[test]
3799    fn windows_update_helper_failure_preserves_the_old_executable() {
3800        let temp = real_tempdir();
3801        let staging = temp.path().join("staging with spaces");
3802        let staged = staging.join("bin/rpi.exe");
3803        let target = temp.path().join("target with spaces/rpi-copy.exe");
3804        fake_windows_executable(&staged, b"new-version");
3805        fake_windows_executable(&target, b"old-version");
3806        let expected = std::fs::read(&target).unwrap();
3807        let plan = build_windows_update_plan(
3808            &staging,
3809            &target,
3810            &temp
3811                .path()
3812                .join("status-00000000000000000000000000000000.json"),
3813        )
3814        .unwrap();
3815        preflight_windows_replacement(&plan).unwrap();
3816        std::fs::write(&plan.helper_script, WINDOWS_UPDATE_HELPER).unwrap();
3817        write_windows_update_status(&plan.status_file, "scheduled", "test").unwrap();
3818        std::fs::remove_file(&plan.staged_exe).unwrap();
3819
3820        let status = windows_update_helper_command(
3821            &system_powershell_path().unwrap(),
3822            &plan,
3823            i32::MAX as u32,
3824            "9.9.9",
3825        )
3826        .status()
3827        .unwrap();
3828
3829        let status_text = std::fs::read_to_string(&plan.status_file).unwrap();
3830        assert!(!status.success());
3831        assert_eq!(
3832            std::fs::read(&target).unwrap(),
3833            expected,
3834            "status={status_text}; backup_exists={}",
3835            plan.backup_file.exists()
3836        );
3837        assert!(!staging.exists());
3838        assert!(!plan.replacement_temp.exists());
3839        assert!(!plan.backup_file.exists());
3840        assert!(!plan.rollback_displaced_file.exists());
3841        let status: serde_json::Value = serde_json::from_str(&status_text).unwrap();
3842        assert_eq!(status["state"], "failed");
3843    }
3844
3845    #[cfg(windows)]
3846    #[test]
3847    fn windows_update_helper_rolls_back_after_post_replace_validation_failure() {
3848        let temp = real_tempdir();
3849        let staging = temp.path().join("staging");
3850        let staged = staging.join("bin/rpi.exe");
3851        let target = temp.path().join("target/rpi-copy.exe");
3852        fake_windows_executable(&staged, b"new-version");
3853        fake_windows_executable(&target, b"old-version");
3854        let expected = std::fs::read(&target).unwrap();
3855        let plan = build_windows_update_plan(
3856            &staging,
3857            &target,
3858            &temp
3859                .path()
3860                .join("status-00000000000000000000000000000000.json"),
3861        )
3862        .unwrap();
3863        preflight_windows_replacement(&plan).unwrap();
3864        let forced_failure = WINDOWS_UPDATE_HELPER.replace(
3865            "(Get-FileSha256 -Path $targetFull) -ne $expectedHash",
3866            "$true",
3867        );
3868        assert_ne!(forced_failure, WINDOWS_UPDATE_HELPER);
3869        std::fs::write(&plan.helper_script, forced_failure).unwrap();
3870        write_windows_update_status(&plan.status_file, "scheduled", "test").unwrap();
3871
3872        let status = windows_update_helper_command(
3873            &system_powershell_path().unwrap(),
3874            &plan,
3875            i32::MAX as u32,
3876            "9.9.9",
3877        )
3878        .status()
3879        .unwrap();
3880
3881        let status_text = std::fs::read_to_string(&plan.status_file).unwrap();
3882        assert!(!status.success());
3883        assert_eq!(
3884            std::fs::read(&target).unwrap(),
3885            expected,
3886            "status={status_text}; backup_exists={}",
3887            plan.backup_file.exists()
3888        );
3889        assert!(!staging.exists());
3890        assert!(!plan.replacement_temp.exists());
3891        assert!(!plan.backup_file.exists());
3892        assert!(!plan.rollback_displaced_file.exists());
3893        let status: serde_json::Value = serde_json::from_str(&status_text).unwrap();
3894        assert_eq!(status["state"], "failed");
3895        assert!(status["message"]
3896            .as_str()
3897            .unwrap()
3898            .contains("updated executable hash mismatch"));
3899    }
3900
3901    #[cfg(windows)]
3902    #[test]
3903    fn windows_update_plan_rejects_a_non_executable_staged_file() {
3904        let temp = real_tempdir();
3905        let staging = temp.path().join("staging");
3906        let staged = staging.join("bin/rpi.exe");
3907        let target = temp.path().join("target/rpi.exe");
3908        std::fs::create_dir_all(staged.parent().unwrap()).unwrap();
3909        std::fs::write(&staged, b"not-a-pe").unwrap();
3910        fake_windows_executable(&target, b"old-version");
3911        let expected = std::fs::read(&target).unwrap();
3912
3913        let error = build_windows_update_plan(
3914            &staging,
3915            &target,
3916            &temp
3917                .path()
3918                .join("status-00000000000000000000000000000000.json"),
3919        )
3920        .unwrap_err();
3921
3922        assert!(error.contains("not a Windows executable"));
3923        assert_eq!(std::fs::read(&target).unwrap(), expected);
3924    }
3925
3926    #[test]
3927    fn staged_rpi_version_output_is_exact_and_cannot_downgrade() {
3928        assert_eq!(
3929            parse_rpi_version_output(b"rpi 1.2.3\r\n").unwrap(),
3930            semver::Version::new(1, 2, 3)
3931        );
3932        assert_eq!(
3933            validate_staged_rpi_version_output(b"rpi 1.2.3\n", b"", "1.2.3").unwrap(),
3934            semver::Version::new(1, 2, 3)
3935        );
3936        assert!(
3937            validate_staged_rpi_version_output(b"rpi 1.2.2\n", b"", "1.2.3")
3938                .unwrap_err()
3939                .contains("older version")
3940        );
3941
3942        for output in [
3943            &b"pi 1.2.3\n"[..],
3944            &b"rpi v1.2.3\n"[..],
3945            &b"rpi 1.2.3 extra\n"[..],
3946            &b"rpi 1.2.3\nsecond line\n"[..],
3947            &b" rpi 1.2.3\n"[..],
3948        ] {
3949            assert!(
3950                parse_rpi_version_output(output).is_none(),
3951                "output={output:?}"
3952            );
3953        }
3954        assert!(
3955            validate_staged_rpi_version_output(b"rpi 1.2.3\n", b"warning", "1.2.3")
3956                .unwrap_err()
3957                .contains("stderr")
3958        );
3959    }
3960
3961    #[test]
3962    fn preview_release_selection_ignores_stable_and_draft_releases() {
3963        let releases = vec![
3964            super::GithubRelease {
3965                tag_name: "v0.9.4-preview.1".into(),
3966                draft: false,
3967                prerelease: true,
3968            },
3969            super::GithubRelease {
3970                tag_name: "v0.9.4-preview.3".into(),
3971                draft: false,
3972                prerelease: true,
3973            },
3974            super::GithubRelease {
3975                tag_name: "v0.9.4-preview.99".into(),
3976                draft: true,
3977                prerelease: true,
3978            },
3979            super::GithubRelease {
3980                tag_name: "v0.9.4".into(),
3981                draft: false,
3982                prerelease: false,
3983            },
3984        ];
3985        assert_eq!(
3986            super::latest_preview_version(releases),
3987            super::RegistryLookup::Found("0.9.4-preview.3".into())
3988        );
3989    }
3990
3991    #[test]
3992    fn compares_release_versions_conservatively() {
3993        assert!(is_newer("0.1.9", "0.1.10"));
3994        assert!(is_newer("v1.2.3", "1.3.0"));
3995        assert!(is_newer("1.2.3-beta.1", "1.2.3-beta.2"));
3996        assert!(is_newer("1.2.3-beta.2", "1.2.3"));
3997        assert!(!is_newer("1.2.3", "1.2.3"));
3998        assert!(!is_newer("1.2.3", "1.2.3+build.1"));
3999        assert!(!is_newer("1.2.3+build.1", "1.2.3+build.2"));
4000        assert!(!is_newer("nightly", "1.0.0"));
4001    }
4002
4003    #[test]
4004    fn failed_item_checks_keep_only_corresponding_cached_values() {
4005        let cached = BTreeMap::from([
4006            ("fresh".to_string(), "1.0.0".to_string()),
4007            ("failed".to_string(), "2.0.0".to_string()),
4008            ("removed".to_string(), "3.0.0".to_string()),
4009        ]);
4010        let results = vec![
4011            (
4012                "fresh".to_string(),
4013                RegistryLookup::Found("1.1.0".to_string()),
4014            ),
4015            ("failed".to_string(), RegistryLookup::TransientFailure),
4016            ("uncached".to_string(), RegistryLookup::TransientFailure),
4017            ("missing".to_string(), RegistryLookup::Missing),
4018        ];
4019
4020        let (merged, checked_at_values) =
4021            results_with_individual_cache_fallback(results, Some(&cached), None, 100, 100);
4022        assert_eq!(merged.get("fresh").map(String::as_str), Some("1.1.0"));
4023        assert_eq!(merged.get("failed").map(String::as_str), Some("2.0.0"));
4024        assert!(!merged.contains_key("removed"));
4025        assert!(!merged.contains_key("uncached"));
4026        assert!(!merged.contains_key("missing"));
4027        // A live lookup is stamped with the current check; a fallback keeps the
4028        // timestamp it was cached at, so the fallback window cannot be extended
4029        // indefinitely by repeated offline starts.
4030        assert_eq!(checked_at_values.get("fresh").copied(), Some(100));
4031        assert_eq!(checked_at_values.get("failed").copied(), Some(100));
4032        assert!(!checked_at_values.contains_key("uncached"));
4033        assert!(!checked_at_values.contains_key("missing"));
4034    }
4035
4036    #[tokio::test]
4037    async fn package_update_checks_have_a_shared_concurrency_limit() {
4038        let in_flight = Arc::new(AtomicUsize::new(0));
4039        let maximum = Arc::new(AtomicUsize::new(0));
4040        let checks = (0..(UPDATE_CHECK_CONCURRENCY * 3)).map(|index| {
4041            let in_flight = Arc::clone(&in_flight);
4042            let maximum = Arc::clone(&maximum);
4043            async move {
4044                let active = in_flight.fetch_add(1, Ordering::SeqCst) + 1;
4045                maximum.fetch_max(active, Ordering::SeqCst);
4046                tokio::time::sleep(std::time::Duration::from_millis(10)).await;
4047                in_flight.fetch_sub(1, Ordering::SeqCst);
4048                index
4049            }
4050        });
4051
4052        let mut results = collect_bounded(checks).await;
4053        results.sort_unstable();
4054
4055        assert_eq!(
4056            results,
4057            (0..(UPDATE_CHECK_CONCURRENCY * 3)).collect::<Vec<_>>()
4058        );
4059        assert_eq!(maximum.load(Ordering::SeqCst), UPDATE_CHECK_CONCURRENCY);
4060        assert_eq!(in_flight.load(Ordering::SeqCst), 0);
4061    }
4062
4063    #[tokio::test]
4064    async fn bounded_checks_do_not_head_of_line_block_new_work() {
4065        let release_first = Arc::new(tokio::sync::Notify::new());
4066        let checks = (0..(UPDATE_CHECK_CONCURRENCY + 1)).map(|index| {
4067            let release_first = Arc::clone(&release_first);
4068            async move {
4069                if index == 0 {
4070                    release_first.notified().await;
4071                } else if index == UPDATE_CHECK_CONCURRENCY {
4072                    release_first.notify_one();
4073                }
4074                index
4075            }
4076        });
4077
4078        let mut results =
4079            tokio::time::timeout(std::time::Duration::from_secs(1), collect_bounded(checks))
4080                .await
4081                .expect("a completed later check must free a concurrency slot");
4082        results.sort_unstable();
4083        assert_eq!(results, (0..=UPDATE_CHECK_CONCURRENCY).collect::<Vec<_>>());
4084    }
4085
4086    #[test]
4087    fn fresh_results_keep_individual_timestamps_when_a_peer_uses_fallback() {
4088        let now = 10 * CACHE_FALLBACK_MAX_AGE_MS;
4089        let nearly_stale = now - CACHE_FALLBACK_MAX_AGE_MS + 60_000;
4090        let cached = BTreeMap::from([
4091            ("fresh".to_string(), "1.0.0".to_string()),
4092            ("failed".to_string(), "2.0.0".to_string()),
4093        ]);
4094        let freshness = BTreeMap::from([
4095            ("fresh".to_string(), nearly_stale),
4096            ("failed".to_string(), nearly_stale),
4097        ]);
4098        let (values, timestamps) = results_with_individual_cache_fallback(
4099            vec![
4100                (
4101                    "fresh".to_string(),
4102                    RegistryLookup::Found("1.1.0".to_string()),
4103                ),
4104                ("failed".to_string(), RegistryLookup::TransientFailure),
4105            ],
4106            Some(&cached),
4107            Some(&freshness),
4108            nearly_stale,
4109            now,
4110        );
4111
4112        assert_eq!(timestamps.get("fresh"), Some(&now));
4113        assert_eq!(timestamps.get("failed"), Some(&nearly_stale));
4114        let after_old_entry_expires = now + 120_000;
4115        let (fallback, _) = results_with_individual_cache_fallback(
4116            vec![
4117                ("fresh".to_string(), RegistryLookup::TransientFailure),
4118                ("failed".to_string(), RegistryLookup::TransientFailure),
4119            ],
4120            Some(&values),
4121            Some(&timestamps),
4122            nearly_stale,
4123            after_old_entry_expires,
4124        );
4125        assert_eq!(fallback.get("fresh").map(String::as_str), Some("1.1.0"));
4126        assert!(!fallback.contains_key("failed"));
4127    }
4128
4129    #[tokio::test]
4130    async fn crates_rate_limits_and_request_timeouts_are_transient() {
4131        async fn lookup(status: &str, body: &str) -> RegistryLookup {
4132            use std::io::{BufRead, BufReader, Write};
4133
4134            let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
4135            let address = listener.local_addr().unwrap();
4136            let status = status.to_string();
4137            let body = body.to_string();
4138            let server = std::thread::spawn(move || {
4139                let (mut stream, _) = listener.accept().unwrap();
4140                {
4141                    let mut reader = BufReader::new(&mut stream);
4142                    let mut line = String::new();
4143                    loop {
4144                        line.clear();
4145                        if reader.read_line(&mut line).unwrap() == 0 || line == "\r\n" {
4146                            break;
4147                        }
4148                    }
4149                }
4150                write!(
4151                    stream,
4152                    "HTTP/1.1 {status}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
4153                    body.len()
4154                )
4155                .unwrap();
4156            });
4157            let client = reqwest::Client::builder().build().unwrap();
4158            let result = fetch_crates_url(&client, &format!("http://{address}/crate")).await;
4159            server.join().unwrap();
4160            result
4161        }
4162
4163        assert_eq!(
4164            lookup("408 Request Timeout", "").await,
4165            RegistryLookup::TransientFailure
4166        );
4167        assert_eq!(
4168            lookup("429 Too Many Requests", "").await,
4169            RegistryLookup::TransientFailure
4170        );
4171        let malformed = lookup("200 OK", "{malformed-json").await;
4172        assert_eq!(malformed, RegistryLookup::TransientFailure);
4173        assert_eq!(
4174            super::lookup_with_cache_fallback(malformed, Some("9.9.9"), true),
4175            (Some("9.9.9".to_string()), true)
4176        );
4177        assert_eq!(lookup("404 Not Found", "").await, RegistryLookup::Missing);
4178    }
4179
4180    /// One-shot HTTP server: answers the first request with `status`/`body`.
4181    ///
4182    /// Returns the URL, a stop flag, and the thread handle. The no-crates.io
4183    /// regression leaves one server unused, so accept must be nonblocking.
4184    fn serve_once(
4185        status: String,
4186        body: String,
4187    ) -> (
4188        String,
4189        std::sync::Arc<std::sync::atomic::AtomicBool>,
4190        std::thread::JoinHandle<usize>,
4191    ) {
4192        use std::io::{BufRead, BufReader, Write};
4193        use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
4194        use std::sync::Arc;
4195
4196        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
4197        let address = listener.local_addr().unwrap();
4198        // The no-crates.io regression leaves one of two servers unused, so the
4199        // accept must be able to time out on its own: a blocking accept that no
4200        // client ever reaches would hang the test, and a self-connect cannot
4201        // unblock `accept` on this platform.
4202        listener.set_nonblocking(true).unwrap();
4203        let hits = Arc::new(AtomicUsize::new(0));
4204        let thread_hits = hits.clone();
4205        let stop = Arc::new(AtomicBool::new(false));
4206        let thread_stop = stop.clone();
4207        let handle = std::thread::spawn(move || {
4208            let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20);
4209            let stream = loop {
4210                match listener.accept() {
4211                    Ok((stream, _)) => break Some(stream),
4212                    Err(ref error) if error.kind() == std::io::ErrorKind::WouldBlock => {
4213                        if thread_stop.load(Ordering::SeqCst)
4214                            || std::time::Instant::now() > deadline
4215                        {
4216                            break None;
4217                        }
4218                        std::thread::sleep(std::time::Duration::from_millis(2));
4219                    }
4220                    Err(_) => break None,
4221                }
4222            };
4223            let Some(mut stream) = stream else {
4224                return thread_hits.load(Ordering::SeqCst);
4225            };
4226            // `accept` inherited non-blocking from the listener; the request read
4227            // below must block, so put the stream back into blocking mode.
4228            stream.set_nonblocking(false).unwrap();
4229            thread_hits.fetch_add(1, Ordering::SeqCst);
4230            {
4231                let mut reader = BufReader::new(&mut stream);
4232                let mut line = String::new();
4233                loop {
4234                    line.clear();
4235                    if reader.read_line(&mut line).unwrap() == 0 || line == "\r\n" {
4236                        break;
4237                    }
4238                }
4239            }
4240            write!(
4241                stream,
4242                "HTTP/1.1 {status}
4243Content-Length: {}
4244Connection: close
4245
4246{body}",
4247                body.len()
4248            )
4249            .unwrap();
4250            thread_hits.load(Ordering::SeqCst)
4251        });
4252        (format!("http://{address}/release"), stop, handle)
4253    }
4254
4255    fn stop_and_join(
4256        stop: std::sync::Arc<std::sync::atomic::AtomicBool>,
4257        handle: std::thread::JoinHandle<usize>,
4258        url: &str,
4259    ) -> usize {
4260        use std::sync::atomic::Ordering;
4261        stop.store(true, Ordering::SeqCst);
4262        let _ = url;
4263        handle.join().unwrap()
4264    }
4265
4266    fn stable_release(tag: &str) -> String {
4267        serde_json::json!({"tag_name": tag, "draft": false, "prerelease": false}).to_string()
4268    }
4269
4270    #[tokio::test]
4271    async fn cli_stable_queries_github_without_contacting_crates_io() {
4272        let (crates_url, crates_stop, crates_server) = serve_once(
4273            "200 OK".into(),
4274            r#"{"crate":{"max_version":"99.0.0"}}"#.into(),
4275        );
4276        let (github_url, github_stop, github_server) =
4277            serve_once("200 OK".into(), stable_release("v0.11.0"));
4278        let client = reqwest::Client::new();
4279        let result = super::fetch_stable_from_github(&client, &github_url).await;
4280        assert_eq!(stop_and_join(crates_stop, crates_server, &crates_url), 0);
4281        assert_eq!(stop_and_join(github_stop, github_server, &github_url), 1);
4282        assert_eq!(result, RegistryLookup::Found("0.11.0".into()));
4283    }
4284
4285    #[tokio::test]
4286    async fn github_stable_rejects_prereleases_drafts_and_invalid_versions() {
4287        for body in [
4288            serde_json::json!({"tag_name":"v1.0.0-preview.1","draft":false,"prerelease":true}),
4289            serde_json::json!({"tag_name":"v1.0.0","draft":true,"prerelease":false}),
4290            serde_json::json!({"tag_name":"v1.0.0-rc.1","draft":false,"prerelease":false}),
4291            serde_json::json!({"tag_name":"1.0.0","draft":false,"prerelease":false}),
4292            serde_json::json!({"tag_name":"vnot-semver","draft":false,"prerelease":false}),
4293        ] {
4294            let (url, stop, server) = serve_once("200 OK".into(), body.to_string());
4295            let result = super::fetch_stable_from_github(&reqwest::Client::new(), &url).await;
4296            stop_and_join(stop, server, &url);
4297            assert_eq!(result, RegistryLookup::TransientFailure, "{body}");
4298        }
4299    }
4300
4301    #[tokio::test]
4302    async fn github_errors_preserve_fresh_cache_and_reject_expired_cache() {
4303        let _guard = crate::config::test_support::env_lock()
4304            .lock()
4305            .unwrap_or_else(|p| p.into_inner());
4306        let agent = tempfile::tempdir().unwrap();
4307        let _restore = RestoreConfigDir(std::env::var_os(crate::config::CONFIG_DIR_ENV));
4308        std::env::set_var(crate::config::CONFIG_DIR_ENV, agent.path());
4309        for (status, body) in [
4310            ("404 Not Found", ""),
4311            ("403 Forbidden", "rate limited"),
4312            ("500 Internal Server Error", ""),
4313            ("200 OK", "{not-json"),
4314        ] {
4315            for fresh in [true, false] {
4316                let stamp = super::now_ms() - if fresh { 1000 } else { 48 * 60 * 60 * 1000 };
4317                let cached = super::UpdateCache {
4318                    checked_at: stamp,
4319                    rpi_latest: Some("0.10.0".into()),
4320                    freshness: super::UpdateCacheFreshness {
4321                        rpi: stamp,
4322                        native_packages: Default::default(),
4323                    },
4324                    ..Default::default()
4325                };
4326                std::fs::write(
4327                    agent.path().join(super::CACHE_FILE),
4328                    serde_json::to_vec(&cached).unwrap(),
4329                )
4330                .unwrap();
4331                let (url, stop, server) = serve_once(status.into(), body.into());
4332                let result = super::lookup_latest_rpi_from(&url).await;
4333                stop_and_join(stop, server, &url);
4334                assert_eq!(
4335                    result,
4336                    fresh.then(|| ("0.10.0".into(), false)),
4337                    "{status}, fresh={fresh}"
4338                );
4339            }
4340        }
4341    }
4342
4343    #[tokio::test]
4344    async fn github_live_answer_is_verified_even_with_an_expired_cache() {
4345        let _guard = crate::config::test_support::env_lock()
4346            .lock()
4347            .unwrap_or_else(|p| p.into_inner());
4348        let agent = tempfile::tempdir().unwrap();
4349        let _restore = RestoreConfigDir(std::env::var_os(crate::config::CONFIG_DIR_ENV));
4350        std::env::set_var(crate::config::CONFIG_DIR_ENV, agent.path());
4351        let stamp = super::now_ms() - 48 * 60 * 60 * 1000;
4352        let cached = super::UpdateCache {
4353            checked_at: stamp,
4354            rpi_latest: Some("0.10.0".into()),
4355            freshness: super::UpdateCacheFreshness {
4356                rpi: stamp,
4357                native_packages: Default::default(),
4358            },
4359            ..Default::default()
4360        };
4361        std::fs::write(
4362            agent.path().join(super::CACHE_FILE),
4363            serde_json::to_vec(&cached).unwrap(),
4364        )
4365        .unwrap();
4366        let (url, stop, server) = serve_once("200 OK".into(), stable_release("v0.11.0"));
4367        let result = super::lookup_latest_rpi_from(&url).await;
4368        assert_eq!(stop_and_join(stop, server, &url), 1);
4369        assert_eq!(result, Some(("0.11.0".into(), true)));
4370    }
4371
4372    #[test]
4373    fn legacy_prebuilt_records_still_receive_update_notices() {
4374        let _guard = crate::config::test_support::env_lock()
4375            .lock()
4376            .unwrap_or_else(|p| p.into_inner());
4377        let agent = tempfile::tempdir().unwrap();
4378        let _restore = RestoreConfigDir(std::env::var_os(crate::config::CONFIG_DIR_ENV));
4379        std::env::set_var(crate::config::CONFIG_DIR_ENV, agent.path());
4380        // Records written before exact prebuilt provenance carry only the
4381        // publisher marker; a repository move must not stop their notices.
4382        let record: crate::install::InstalledNativePackage =
4383            serde_json::from_value(serde_json::json!({
4384                "name":"demo", "version":"1.0.0",
4385                "source":"prebuilt:https://github.com/pi-rust/rpi-package",
4386                "artifacts":["custom.so"]
4387            }))
4388            .unwrap();
4389        std::fs::write(
4390            agent.path().join("native-packages.json"),
4391            serde_json::to_vec(&[record.clone()]).unwrap(),
4392        )
4393        .unwrap();
4394        assert_eq!(super::native_cache_key(&record), "demo");
4395        let mut cache = super::UpdateCache::default();
4396        cache
4397            .native_packages
4398            .insert(super::native_cache_key(&record), "2.0.0".into());
4399        let report = super::report_from_cache(&cache);
4400        assert_eq!(report.notices.len(), 1);
4401        assert_eq!(report.notices[0].command, "rpi extension update demo");
4402
4403        // A local development build must never be advertised as updatable.
4404        let local: crate::install::InstalledNativePackage = serde_json::from_value(
4405            serde_json::json!({"name":"local","version":"1.0.0","source":"../local-ext"}),
4406        )
4407        .unwrap();
4408        std::fs::write(
4409            agent.path().join("native-packages.json"),
4410            serde_json::to_vec(&[local]).unwrap(),
4411        )
4412        .unwrap();
4413        let mut cache = super::UpdateCache::default();
4414        cache.native_packages.insert("local".into(), "9.9.9".into());
4415        assert!(super::report_from_cache(&cache).notices.is_empty());
4416    }
4417}