Skip to main content

cpa_plugin/
homeplugins.rs

1//! Home-managed plugin installs, deletes and their status reports (Go
2//! internal/homeplugins and internal/home/plugin_status.go).
3//!
4//! Home either resolves the plugins to install (`plugin-sync`, with short-lived store
5//! credentials) or, on Homes without plugin sync, leaves the node to install the
6//! `store` manifests in its plugin configs. Every outcome becomes a [`SyncReport`] that
7//! the node pushes to Home's `plugin-status` list.
8
9use cpa_core::gostr::GoStr;
10use std::collections::BTreeMap;
11use std::path::{Path, PathBuf};
12use std::sync::Arc;
13use std::time::{Duration, SystemTime};
14
15use futures_util::future::BoxFuture;
16use serde_yaml_ng::Value;
17use tokio_util::sync::CancellationToken;
18
19use crate::config::{self, yaml_bool, yaml_int, yaml_string};
20use crate::go_struct;
21use crate::gojson::{self, GoTime, NonNil};
22use crate::store::{
23    AuthConfig, Client, Doer, InstallOptions, InstallResult, Manifest, PluginSyncItem, update_available,
24};
25
26const TASK_SYNC: &str = "plugin-sync";
27const TASK_DELETE: &str = "plugin-delete";
28const STATUS_OK: &str = "success";
29const STATUS_ERROR: &str = "failed";
30const PHASE_INSTALL: &str = "install";
31const PHASE_LOAD: &str = "load";
32const PHASE_DELETE: &str = "delete";
33const INSTALLED: &str = "installed";
34const SKIPPED: &str = "skipped";
35const FAILED: &str = "failed";
36const DELETED: &str = "deleted";
37const MISSING: &str = "missing";
38const LOADED: &str = "loaded";
39
40/// Go `pluginStatusReportTimeout`.
41const STATUS_REPORT_TIMEOUT: Duration = Duration::from_secs(10);
42
43go_struct! {
44    /// Go `homeplugins.Platform`.
45    pub struct Platform("homeplugins.Platform") {
46        "goos" => goos: String,
47        "goarch" => goarch: String,
48    }
49}
50
51go_struct! {
52    /// Go `homeplugins.SyncReport`.
53    pub struct SyncReport("homeplugins.SyncReport") {
54        "schema_version" => schema_version: isize,
55        "task_id" omitempty => task_id: u64,
56        "task" => task: String,
57        "node_id" omitempty => node_id: String,
58        "status" => status: String,
59        "phase" => phase: String,
60        "ok" => ok: bool,
61        "started_at" => started_at: GoTime,
62        "finished_at" => finished_at: GoTime,
63        "updated_at" => updated_at: GoTime,
64        "platform" => platform: Platform,
65        "plugins" => plugins: NonNil<Vec<PluginInstallStatus>>,
66        "error" omitempty => error: String,
67    }
68}
69
70go_struct! {
71    /// Go `homeplugins.PluginInstallStatus`.
72    pub struct PluginInstallStatus("homeplugins.PluginInstallStatus") {
73        "id" => id: String,
74        "version" omitempty => version: String,
75        "release_tag" omitempty => release_tag: String,
76        "repository" omitempty => repository: String,
77        "install_type" omitempty => install_type: String,
78        "install_status" => install_status: String,
79        "load_status" omitempty => load_status: String,
80        "path" omitempty => path: String,
81        "skipped" omitempty => skipped: bool,
82        "overwritten" omitempty => overwritten: bool,
83        "error" omitempty => error: String,
84    }
85}
86
87/// What the plugin host tells a sync (Go `PluginRuntime` and `PluginLoadInspector`).
88pub trait PluginRuntime: Send + Sync {
89    /// Loaded or still loading.
90    fn plugin_busy(&self, id: &str) -> bool;
91    /// Detaches and closes the plugin; `false` when nothing was unloaded. Cancelling
92    /// `cancel` stops waiting for it (Go `UnloadPluginContext`).
93    fn unload_plugin<'a>(&'a self, id: &'a str, cancel: &'a CancellationToken) -> BoxFuture<'a, bool>;
94    /// Active in the current snapshot.
95    fn plugin_registered(&self, id: &str) -> bool;
96}
97
98impl PluginRuntime for crate::Host {
99    fn plugin_busy(&self, id: &str) -> bool {
100        crate::Host::plugin_busy(self, id)
101    }
102    fn unload_plugin<'a>(&'a self, id: &'a str, cancel: &'a CancellationToken) -> BoxFuture<'a, bool> {
103        Box::pin(crate::Host::unload_plugin_until(self, id, cancel))
104    }
105    fn plugin_registered(&self, id: &str) -> bool {
106        crate::Host::plugin_registered(self, id)
107    }
108}
109
110/// The parts of a config a sync reads (Go's `cfg.Plugins` and `cfg.ProxyURL`).
111#[derive(Debug, Clone, Default, PartialEq)]
112pub struct SyncConfig {
113    pub enabled: bool,
114    /// `plugins.dir` as configured.
115    pub dir: String,
116    /// Each `plugins.configs.<id>` subtree, by ID as written.
117    pub configs: BTreeMap<String, Value>,
118    /// `plugins.configs` with its plain scalars' text (`Config::plugin_configs`), so a
119    /// respelt value (`1.50` to `1.5`) is a change, as Go's raw node makes it one.
120    pub raw_configs: Value,
121    pub auth_revision: i64,
122    /// `plugins.store-auth`, normalized.
123    pub store_auth: Vec<AuthConfig>,
124    pub proxy_url: String,
125}
126
127impl SyncConfig {
128    pub fn from_document(document: &Value) -> Self {
129        let plugins = document.get("plugins");
130        let field = |key: &str| plugins.and_then(|p| p.get(key));
131        Self {
132            enabled: field("enabled").and_then(yaml_bool).unwrap_or(false),
133            dir: config::configured_dir(document),
134            configs: match field("configs") {
135                Some(Value::Mapping(map)) => map.iter().map(|(k, v)| (yaml_string(k), v.clone())).collect(),
136                _ => BTreeMap::new(),
137            },
138            auth_revision: field("auth-revision").and_then(yaml_int).unwrap_or(0),
139            raw_configs: Value::Null,
140            store_auth: config::store_auth(document),
141            proxy_url: document
142                .get("requests")
143                .and_then(|r| r.get("proxy-url"))
144                .map(yaml_string)
145                .unwrap_or_default()
146                .trim()
147                .to_owned(),
148        }
149    }
150
151    /// The enabled plugin configs in ID order (Go `pluginConfigEnabled`).
152    fn enabled_configs(&self) -> impl Iterator<Item = (&String, &Value)> {
153        self.configs
154            .iter()
155            .filter(|(id, node)| config::item_config(id, node, None).enabled)
156    }
157}
158
159/// Go `CurrentPlatform`.
160pub fn current_platform() -> Platform {
161    Platform {
162        goos: crate::platform::goos().into(),
163        goarch: crate::platform::goarch().into(),
164    }
165}
166
167/// Go `NormalizePlatform`.
168pub fn normalize_platform(platform: &Platform) -> Platform {
169    let goos = match platform.goos.trim().go_lower().as_str() {
170        "mac" | "macos" | "osx" => "darwin".to_owned(),
171        other => other.to_owned(),
172    };
173    let goarch = match platform.goarch.trim().go_lower().as_str() {
174        "x64" | "x86_64" => "amd64".to_owned(),
175        "aarch64" => "arm64".to_owned(),
176        other => other.to_owned(),
177    };
178    Platform { goos, goarch }
179}
180
181fn new_report(platform: &Platform) -> SyncReport {
182    let now = GoTime::now_utc();
183    SyncReport {
184        schema_version: 1,
185        task: TASK_SYNC.into(),
186        status: STATUS_OK.into(),
187        phase: PHASE_INSTALL.into(),
188        ok: true,
189        started_at: now,
190        updated_at: now,
191        platform: normalize_platform(platform),
192        ..Default::default()
193    }
194}
195
196/// Go `finishReport`.
197fn finish(report: &mut SyncReport, error: Option<&str>) {
198    let now = GoTime::now_utc();
199    report.finished_at = now;
200    report.updated_at = now;
201    report.ok = error.is_none();
202    match error {
203        Some(e) => {
204            report.status = STATUS_ERROR.into();
205            report.error = e.to_owned();
206        }
207        None => {
208            report.status = STATUS_OK.into();
209            report.error.clear();
210        }
211    }
212}
213
214/// Go `errors.Join` of the collected messages.
215fn joined(errors: &[String]) -> Option<String> {
216    (!errors.is_empty()).then(|| errors.join("\n"))
217}
218
219/// Go `CompletedSyncReport`: a finished report for an outcome before any install.
220pub fn completed_sync_report(platform: &Platform, error: Option<&str>) -> SyncReport {
221    let mut report = new_report(platform);
222    finish(&mut report, error);
223    report
224}
225
226fn resolve_root(cfg: &SyncConfig) -> Result<PathBuf, String> {
227    config::resolve_dir(&cfg.dir).map_err(|e| format!("home plugins: {e}"))
228}
229
230/// Go `newPluginStoreClient` and `newResolvedPluginStoreClient`: `http` already goes
231/// through the config's proxy, which also scopes the shared GitHub cooldown.
232fn store_client(cfg: &SyncConfig, http: &Arc<dyn Doer>) -> Client {
233    let mut client = Client::new(http.clone());
234    client.network_scope = cfg.proxy_url.clone();
235    client
236}
237
238/// Go `storeManifestFromPluginConfig`: `None` without a `store` node.
239fn store_manifest(id: &str, node: &Value) -> Result<Option<Manifest>, String> {
240    let Some(store) = node.as_mapping().and_then(|m| m.get("store")).filter(|s| !s.is_null()) else {
241        return Ok(None);
242    };
243    let mut manifest =
244        Manifest::from_yaml(store).ok_or_else(|| format!("home plugins: decode store manifest for {id}"))?;
245    if manifest.id.trim().is_empty() {
246        manifest.id = id.trim().to_owned();
247    }
248    manifest
249        .validate()
250        .map_err(|e| format!("home plugins: invalid store manifest for {id}: {e}"))?;
251    Ok(Some(manifest))
252}
253
254/// Go `pluginStatusFromManifest`.
255fn status_from_manifest(manifest: &Manifest) -> PluginInstallStatus {
256    PluginInstallStatus {
257        id: manifest.id.trim().to_owned(),
258        version: manifest.version.trim().to_owned(),
259        release_tag: manifest.release_tag.trim().to_owned(),
260        repository: manifest.repository.trim().to_owned(),
261        install_type: manifest.install_type(),
262        install_status: FAILED.into(),
263        ..Default::default()
264    }
265}
266
267fn record_install(status: &mut PluginInstallStatus, result: Result<InstallResult, String>) -> Option<String> {
268    match result {
269        Ok(result) => {
270            status.path = result.path.trim().to_owned();
271            status.skipped = result.skipped;
272            status.overwritten = result.overwritten;
273            status.install_status = if result.skipped { SKIPPED } else { INSTALLED }.into();
274            None
275        }
276        Err(e) => {
277            status.install_status = FAILED.into();
278            status.error = e.clone();
279            Some(e)
280        }
281    }
282}
283
284/// Go `installManifest`.
285async fn install_manifest(
286    client: &Client,
287    manifest: &Manifest,
288    root: &Path,
289    platform: &Platform,
290    runtime: Option<&Arc<dyn PluginRuntime>>,
291) -> Result<InstallResult, String> {
292    let id = manifest.id.trim().to_owned();
293    if id.is_empty() {
294        return Err("home plugins: manifest plugin id is empty".into());
295    }
296    let busy = runtime.cloned().map(|runtime| {
297        let id = id.clone();
298        Box::new(move || runtime.plugin_busy(&id)) as Box<dyn Fn() -> bool + Send + Sync>
299    });
300    let options = InstallOptions {
301        plugins_dir: root.to_string_lossy().into_owned(),
302        goos: platform.goos.clone(),
303        goarch: platform.goarch.clone(),
304        plugin_loaded: busy,
305        before_write: None,
306    };
307    client
308        .install_manifest(manifest, options)
309        .await
310        .map_err(|e| format!("home plugins: install {id}: {e}"))
311}
312
313/// Go `SyncWithReport`: installs each enabled plugin's `store` manifest for this
314/// platform (Homes without plugin sync).
315pub async fn sync_with_report(
316    cfg: &SyncConfig,
317    http: &Arc<dyn Doer>,
318    runtime: Option<&Arc<dyn PluginRuntime>>,
319) -> (SyncReport, Option<String>) {
320    sync_platform_with_report(cfg, http, runtime, &current_platform()).await
321}
322
323/// Go `SyncPlatformWithReport`.
324pub async fn sync_platform_with_report(
325    cfg: &SyncConfig,
326    http: &Arc<dyn Doer>,
327    runtime: Option<&Arc<dyn PluginRuntime>>,
328    platform: &Platform,
329) -> (SyncReport, Option<String>) {
330    if !cfg.enabled {
331        return (new_report(platform), None);
332    }
333    let platform = normalize_platform(platform);
334    let mut report = new_report(&platform);
335    let fail = |mut report: SyncReport, e: String| {
336        finish(&mut report, Some(&e));
337        (report, Some(e))
338    };
339    if platform.goos.is_empty() {
340        return fail(report, "home plugins: goos is required".into());
341    }
342    if platform.goarch.is_empty() {
343        return fail(report, "home plugins: goarch is required".into());
344    }
345    let root = match resolve_root(cfg) {
346        Ok(root) => root,
347        Err(e) => return fail(report, e),
348    };
349    let mut client = store_client(cfg, http);
350    client.auth = cfg.store_auth.clone();
351    let mut errors = Vec::new();
352    for (id, node) in cfg.enabled_configs() {
353        let manifest = match store_manifest(id, node) {
354            Ok(Some(manifest)) => manifest,
355            Ok(None) => continue,
356            Err(e) => {
357                report.plugins.0.push(PluginInstallStatus {
358                    id: id.trim().to_owned(),
359                    install_status: FAILED.into(),
360                    error: e.clone(),
361                    ..Default::default()
362                });
363                errors.push(e);
364                continue;
365            }
366        };
367        let mut status = status_from_manifest(&manifest);
368        let result = install_manifest(&client, &manifest, &root, &platform, runtime).await;
369        errors.extend(record_install(&mut status, result));
370        report.plugins.0.push(status);
371    }
372    let error = joined(&errors);
373    finish(&mut report, error.as_deref());
374    (report, error)
375}
376
377/// Go `SyncResolvedWithReport`: installs the plugins Home resolved, with the store
378/// credentials it sent for them until `expires_at`. Installed plugins Home left out are
379/// reported as skipped.
380pub async fn sync_resolved_with_report(
381    cfg: &SyncConfig,
382    items: Vec<PluginSyncItem>,
383    expires_at: GoTime,
384    installed_versions: &BTreeMap<String, String>,
385    http: &Arc<dyn Doer>,
386    runtime: Option<&Arc<dyn PluginRuntime>>,
387) -> (SyncReport, Option<String>) {
388    let platform = normalize_platform(&current_platform());
389    let mut report = new_report(&platform);
390    if !cfg.enabled {
391        finish(&mut report, None);
392        return (report, None);
393    }
394    let root = match resolve_root(cfg) {
395        Ok(root) => root,
396        Err(e) => {
397            finish(&mut report, Some(&e));
398            return (report, Some(e));
399        }
400    };
401    add_installed_version_statuses(&mut report, cfg, &root, installed_versions);
402    let expires = expires_at.0.map(SystemTime::from);
403    let mut errors = Vec::new();
404    for item in items {
405        if expires.is_none_or(|expires| SystemTime::now() >= expires) {
406            errors.push("home plugins: plugin sync response expired".into());
407            break;
408        }
409        let mut status = status_from_manifest(&item.manifest);
410        let mut client = store_client(cfg, http);
411        client.resolved_auth = item.auth;
412        client.resolved_auth_expires_at = expires;
413        let result = install_manifest(&client, &item.manifest, &root, &platform, runtime).await;
414        drop(client);
415        errors.extend(record_install(&mut status, result));
416        upsert(&mut report, status);
417    }
418    let error = joined(&errors);
419    finish(&mut report, error.as_deref());
420    (report, error)
421}
422
423/// Go `addInstalledVersionStatuses`.
424fn add_installed_version_statuses(
425    report: &mut SyncReport,
426    cfg: &SyncConfig,
427    root: &Path,
428    installed: &BTreeMap<String, String>,
429) {
430    if installed.is_empty() {
431        return;
432    }
433    for (id, node) in cfg.enabled_configs() {
434        let id = id.trim();
435        let Some(version) = installed.get(id) else {
436            continue;
437        };
438        let mut status = PluginInstallStatus {
439            id: id.to_owned(),
440            version: version.trim().to_owned(),
441            install_status: SKIPPED.into(),
442            skipped: true,
443            ..Default::default()
444        };
445        if let Ok(files) = plugin_files(root, id)
446            && let Some(file) = files.iter().find(|f| f.version.trim() == status.version)
447        {
448            status.path = file.path.to_string_lossy().trim().to_owned();
449        }
450        if let Ok(Some(manifest)) = store_manifest(id, node)
451            && versions_equal(&status.version, &manifest.version)
452        {
453            status.release_tag = manifest.release_tag.trim().to_owned();
454            status.repository = manifest.repository.trim().to_owned();
455            status.install_type = manifest.install_type();
456        }
457        report.plugins.0.push(status);
458    }
459}
460
461/// Go `pluginVersionsEqual`.
462fn versions_equal(left: &str, right: &str) -> bool {
463    let (left, right) = (left.trim(), right.trim());
464    !left.is_empty() && !right.is_empty() && !update_available(left, right) && !update_available(right, left)
465}
466
467/// Go `upsertPluginInstallStatus`.
468fn upsert(report: &mut SyncReport, status: PluginInstallStatus) {
469    let id = status.id.trim().to_owned();
470    match report.plugins.0.iter_mut().find(|p| p.id.trim() == id) {
471        Some(existing) => *existing = status,
472        None => report.plugins.0.push(status),
473    }
474}
475
476/// Go `InstalledVersions`: the selected file's version of every configured plugin.
477pub fn installed_versions(cfg: &SyncConfig) -> Result<BTreeMap<String, String>, String> {
478    let root = resolve_root(cfg)?;
479    let mut versions = BTreeMap::new();
480    for id in cfg.configs.keys() {
481        let files =
482            plugin_files(&root, id).map_err(|e| format!("home plugins: discover installed plugin {id}: {e}"))?;
483        if let Some(version) = files.first().map(|f| f.version.trim()).filter(|v| !v.is_empty()) {
484            versions.insert(id.trim().to_owned(), version.to_owned());
485        }
486    }
487    Ok(versions)
488}
489
490/// Go `MarkLoadResults`: moves the report to the load phase, failing it for every
491/// installed plugin the host did not register. An earlier sync error is kept.
492pub fn mark_load_results(report: &mut SyncReport, runtime: Option<&dyn PluginRuntime>) -> Option<String> {
493    report.phase = PHASE_LOAD.into();
494    let mut errors = Vec::new();
495    let preserve = !report.ok && !report.error.trim().is_empty();
496    if preserve {
497        errors.push(report.error.clone());
498    }
499    for status in &mut report.plugins.0 {
500        if status.install_status == FAILED {
501            if status.load_status.is_empty() {
502                status.load_status = SKIPPED.into();
503            }
504            if !preserve {
505                errors.push(match status.error.trim() {
506                    "" => format!("home plugins: plugin {} install failed", status.id),
507                    _ => status.error.clone(),
508                });
509            }
510            continue;
511        }
512        if runtime.is_some_and(|r| r.plugin_registered(&status.id)) {
513            status.load_status = LOADED.into();
514            continue;
515        }
516        status.load_status = FAILED.into();
517        let error = format!("home plugins: plugin {} installed but not loaded", status.id);
518        if status.error.trim().is_empty() {
519            status.error = error.clone();
520        }
521        errors.push(error);
522    }
523    let error = joined(&errors);
524    finish(report, error.as_deref());
525    error
526}
527
528/// Go `DeleteWithReport`: removes every file of the plugin for this platform,
529/// unloading it first when it is busy.
530pub async fn delete_with_report(
531    cancel: &CancellationToken,
532    cfg: Option<&SyncConfig>,
533    runtime: Option<&Arc<dyn PluginRuntime>>,
534    task_id: u64,
535    plugin_id: &str,
536) -> SyncReport {
537    let mut report = new_report(&current_platform());
538    report.task_id = task_id;
539    report.task = TASK_DELETE.into();
540    report.phase = PHASE_DELETE.into();
541    let mut status = PluginInstallStatus {
542        id: plugin_id.trim().to_owned(),
543        ..Default::default()
544    };
545    let outcome = match cfg {
546        _ if cancel.is_cancelled() => Err(CANCELED.to_owned()),
547        None => Err("home plugins: config is nil".to_owned()),
548        Some(cfg) => match resolve_root(cfg) {
549            Err(e) => Err(e),
550            Ok(_) if cancel.is_cancelled() => Err(CANCELED.to_owned()),
551            Ok(root) => {
552                let (path, deleted, result) = delete_artifact(cancel, &root, &status.id, runtime).await;
553                status.path = path.trim().to_owned();
554                result.map(|()| deleted)
555            }
556        },
557    };
558    let error = match outcome {
559        Ok(deleted) => {
560            status.install_status = if deleted { DELETED } else { MISSING }.into();
561            None
562        }
563        Err(e) => {
564            status.install_status = FAILED.into();
565            status.error = e.clone();
566            Some(e)
567        }
568    };
569    report.plugins.0.push(status);
570    finish(&mut report, error.as_deref());
571    report
572}
573
574/// Go's `context.Canceled` text.
575const CANCELED: &str = "context canceled";
576
577/// Go `deletePluginArtifact`: the representative path, whether a file went, and the
578/// error.
579async fn delete_artifact(
580    cancel: &CancellationToken,
581    root: &Path,
582    id: &str,
583    runtime: Option<&Arc<dyn PluginRuntime>>,
584) -> (String, bool, Result<(), String>) {
585    if !valid_file_id(id) {
586        return (
587            String::new(),
588            false,
589            Err(format!("invalid plugin id {}", cpa_common::gostr::quote(id))),
590        );
591    }
592    let paths: Vec<String> = match plugin_files(root, id) {
593        Ok(files) => files.iter().map(|f| f.path.to_string_lossy().into_owned()).collect(),
594        Err(e) => return (String::new(), false, Err(e.to_string())),
595    };
596    if cancel.is_cancelled() {
597        return (String::new(), false, Err(CANCELED.into()));
598    }
599    let Some(first) = paths.first().cloned() else {
600        return (String::new(), false, Ok(()));
601    };
602    if let Some(runtime) = runtime
603        && runtime.plugin_busy(id)
604    {
605        if cancel.is_cancelled() {
606            return (first, false, Err(CANCELED.into()));
607        }
608        if !runtime.unload_plugin(id, cancel).await && runtime.plugin_busy(id) {
609            return (first, false, Err(crate::store::LOADED_PLUGIN_LOCKED.into()));
610        }
611    }
612    let mut deleted = false;
613    for path in &paths {
614        if cancel.is_cancelled() {
615            return (first, deleted, Err(CANCELED.into()));
616        }
617        match std::fs::remove_file(path) {
618            Ok(()) => deleted = true,
619            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
620            Err(e) => return (first, deleted, Err(e.to_string())),
621        }
622    }
623    (first, deleted, Ok(()))
624}
625
626/// Go `pluginFileInfo`.
627struct PluginFile {
628    path: PathBuf,
629    version: String,
630}
631
632/// Go `pluginFileInfos`: the plugin's files for this platform, the preferred one first.
633fn plugin_files(root: &Path, id: &str) -> std::io::Result<Vec<PluginFile>> {
634    let root = if root.as_os_str().is_empty() {
635        Path::new("plugins")
636    } else {
637        root
638    };
639    let id = id.trim();
640    let platform = current_platform();
641    let extension = crate::platform::extension(&platform.goos);
642    let mut candidates = Vec::new();
643    for dir in crate::platform::candidate_dirs(root, &platform.goos, &platform.goarch) {
644        let entries = match std::fs::read_dir(&dir) {
645            Ok(entries) => entries,
646            Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue,
647            Err(e) => return Err(e),
648        };
649        let mut names = Vec::new();
650        for entry in entries {
651            let entry = entry?;
652            // Go's DirEntry type is lstat-based: symlinks are not regular files.
653            if entry.file_type()?.is_file() && entry.file_name().to_string_lossy().go_lower().ends_with(extension) {
654                names.push(dir.join(entry.file_name()));
655            }
656        }
657        names.sort_by(|a, b| a.as_os_str().as_encoded_bytes().cmp(b.as_os_str().as_encoded_bytes()));
658        for path in names {
659            if let Some((file_id, version)) = split_file_name(&path, extension)
660                && file_id == id
661            {
662                candidates.push(PluginFile { path, version });
663            }
664        }
665    }
666    let best = (1..candidates.len()).fold(0, |best, i| {
667        if preferred(&candidates[i], &candidates[best]) {
668            i
669        } else {
670            best
671        }
672    });
673    if best != 0 {
674        let file = candidates.remove(best);
675        candidates.insert(0, file);
676    }
677    Ok(candidates)
678}
679
680/// Go `pluginFileFromPath`: `(id, version)` of `<id>[-v<version>]<extension>`.
681fn split_file_name(path: &Path, extension: &str) -> Option<(String, String)> {
682    let base = path.file_name()?.to_string_lossy().into_owned();
683    if !base.go_lower().ends_with(extension) {
684        return None;
685    }
686    let name = &base[..base.len() - extension.len()];
687    let (mut id, mut version) = (name, "");
688    if let Some(i) = name.rfind("-v").filter(|i| *i > 0) {
689        let (candidate_id, candidate_version) = (&name[..i], &name[i + 2..]);
690        if valid_file_id(candidate_id) && valid_file_version(candidate_version) {
691            (id, version) = (candidate_id, candidate_version);
692        }
693    }
694    valid_file_id(id).then(|| (id.to_owned(), version.to_owned()))
695}
696
697/// Go `pluginFilePreferred`.
698fn preferred(candidate: &PluginFile, current: &PluginFile) -> bool {
699    if candidate.version.is_empty() {
700        return false;
701    }
702    current.version.is_empty() || update_available(&current.version, &candidate.version)
703}
704
705/// Go homeplugins `validPluginFileID`.
706fn valid_file_id(id: &str) -> bool {
707    let id = id.trim();
708    !id.is_empty()
709        && id != "."
710        && id != ".."
711        && id
712            .chars()
713            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'))
714}
715
716/// Go homeplugins `validPluginFileVersion`.
717fn valid_file_version(version: &str) -> bool {
718    version.trim().as_bytes().first().is_some_and(u8::is_ascii_digit)
719}
720
721/// Go `home.ReportPluginStatus`: stamps the node and time on `report` and pushes it with
722/// `push` (Go `RPushPluginStatus`) within ten seconds.
723pub async fn report_plugin_status<F, Fut>(push: F, node_id: &str, mut report: SyncReport) -> Result<(), String>
724where
725    F: FnOnce(Vec<u8>) -> Fut,
726    Fut: std::future::Future<Output = Result<(), String>>,
727{
728    let node_id = node_id.trim();
729    if node_id.is_empty() {
730        return Err("home plugin status node id is empty".into());
731    }
732    report.node_id = node_id.to_owned();
733    report.updated_at = GoTime::now_utc();
734    let payload = gojson::to_vec(&report);
735    tokio::time::timeout(STATUS_REPORT_TIMEOUT, push(payload))
736        .await
737        .unwrap_or_else(|_| Err("context deadline exceeded".into()))
738}
739
740#[cfg(test)]
741mod tests {
742    //! Go internal/homeplugins/sync_test.go, network_scope_test.go and
743    //! internal/home/plugin_status_test.go.
744
745    use std::sync::Mutex;
746    use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
747
748    use bytes::Bytes;
749    use futures_util::StreamExt as _;
750    use sha2::{Digest as _, Sha256};
751
752    use super::*;
753    use crate::store::{
754        Artifact, DoerResponse, Headers, INSTALL_TYPE_DIRECT, INSTALL_TYPE_GITHUB_RELEASE, InstallPlan, Plugin,
755        REQUEST_KIND_ARTIFACT, ResolvedAuthConfig, Secret, StoreError,
756    };
757
758    /// Go `mapHTTPDoer`: fixed bodies by exact URL, 404 otherwise. `bearer` makes every
759    /// route answer 401 unless the request carries that bearer token.
760    #[derive(Default)]
761    struct MapDoer {
762        routes: BTreeMap<String, Vec<u8>>,
763        bearer: Option<String>,
764        authenticated: AtomicBool,
765        calls: AtomicUsize,
766        status: Option<u16>,
767    }
768
769    impl Doer for MapDoer {
770        fn get(&self, url: &str, headers: &Headers) -> BoxFuture<'_, Result<DoerResponse, String>> {
771            self.calls.fetch_add(1, Ordering::SeqCst);
772            let authorized = match &self.bearer {
773                None => true,
774                Some(token) => headers
775                    .get("Authorization")
776                    .is_some_and(|v| v.iter().any(|v| *v == format!("Bearer {token}"))),
777            };
778            if self.bearer.is_some() && authorized {
779                self.authenticated.store(true, Ordering::SeqCst);
780            }
781            let (status, body) = match (self.status, self.routes.get(url)) {
782                (Some(status), _) => (status, b"proxy".to_vec()),
783                _ if !authorized => (401, b"unauthorized".to_vec()),
784                (None, Some(body)) => (200, body.clone()),
785                (None, None) => (404, b"not found".to_vec()),
786            };
787            Box::pin(async move {
788                Ok(DoerResponse {
789                    status,
790                    headers: Headers::new(),
791                    body: futures_util::stream::once(async move { Ok(Bytes::from(body)) }).boxed(),
792                })
793            })
794        }
795    }
796
797    #[derive(Default)]
798    struct FakeRuntime {
799        busy: AtomicBool,
800        unloaded: Mutex<Vec<String>>,
801        /// The cancellation each unload received.
802        unload_cancels: Mutex<Vec<CancellationToken>>,
803        registered: Vec<&'static str>,
804    }
805
806    impl PluginRuntime for FakeRuntime {
807        fn plugin_busy(&self, _id: &str) -> bool {
808            self.busy.load(Ordering::SeqCst)
809        }
810        fn unload_plugin<'a>(&'a self, id: &'a str, cancel: &'a CancellationToken) -> BoxFuture<'a, bool> {
811            self.unloaded.lock().unwrap().push(id.to_owned());
812            self.unload_cancels.lock().unwrap().push(cancel.clone());
813            self.busy.store(false, Ordering::SeqCst);
814            Box::pin(async { true })
815        }
816        fn plugin_registered(&self, id: &str) -> bool {
817            self.registered.contains(&id)
818        }
819    }
820
821    fn busy_runtime() -> Arc<FakeRuntime> {
822        let runtime = FakeRuntime::default();
823        runtime.busy.store(true, Ordering::SeqCst);
824        Arc::new(runtime)
825    }
826
827    fn dyn_runtime(runtime: &Arc<FakeRuntime>) -> Arc<dyn PluginRuntime> {
828        runtime.clone()
829    }
830
831    /// A stored (uncompressed) zip archive, as Go's `zip.Writer` with `Create` would
832    /// hold the same files.
833    fn make_zip(files: &[(&str, &str)]) -> Vec<u8> {
834        let (mut out, mut central) = (Vec::new(), Vec::new());
835        for (name, content) in files {
836            let mut crc = flate2::Crc::new();
837            crc.update(content.as_bytes());
838            let offset = out.len() as u32;
839            let header = |sig: u32, central: bool| {
840                let mut h = sig.to_le_bytes().to_vec();
841                if central {
842                    h.extend(20u16.to_le_bytes()); // made by: FAT, 2.0
843                }
844                h.extend(20u16.to_le_bytes()); // version needed
845                h.extend(0u16.to_le_bytes()); // flags
846                h.extend(0u16.to_le_bytes()); // stored
847                h.extend(0u32.to_le_bytes()); // time and date
848                h.extend(crc.sum().to_le_bytes());
849                h.extend((content.len() as u32).to_le_bytes());
850                h.extend((content.len() as u32).to_le_bytes());
851                h.extend((name.len() as u16).to_le_bytes());
852                h.extend(0u16.to_le_bytes()); // extra
853                if central {
854                    h.extend([0u8; 6]); // comment, disk, internal attributes
855                    h.extend(0u32.to_le_bytes()); // external attributes
856                    h.extend(offset.to_le_bytes());
857                }
858                h.extend(name.as_bytes());
859                h
860            };
861            out.extend(header(0x0403_4b50, false));
862            out.extend(content.as_bytes());
863            central.extend(header(0x0201_4b50, true));
864        }
865        let (start, size) = (out.len() as u32, central.len() as u32);
866        out.extend(central);
867        out.extend(0x0605_4b50u32.to_le_bytes());
868        out.extend([0u8; 4]);
869        out.extend((files.len() as u16).to_le_bytes());
870        out.extend((files.len() as u16).to_le_bytes());
871        out.extend(size.to_le_bytes());
872        out.extend(start.to_le_bytes());
873        out.extend(0u16.to_le_bytes());
874        out
875    }
876
877    fn hex_sha256(data: &[u8]) -> String {
878        Sha256::digest(data).iter().map(|b| format!("{b:02x}")).collect()
879    }
880
881    /// The GitHub release routes for sample v0.2.0 on windows/amd64.
882    fn release_doer() -> Arc<dyn Doer> {
883        let archive = make_zip(&[("sample.dll", "library-data")]);
884        let name = "sample_0.2.0_windows_amd64.zip";
885        let mut routes = BTreeMap::new();
886        routes.insert(
887            "https://api.github.com/repos/owner/sample-plugin/releases/tags/v0.2.0".to_owned(),
888            format!(
889                r#"{{"tag_name": "v0.2.0", "assets": [
890                    {{"name": "{name}", "browser_download_url": "https://downloads.example/{name}"}},
891                    {{"name": "checksums.txt", "browser_download_url": "https://downloads.example/checksums.txt"}}]}}"#
892            )
893            .into_bytes(),
894        );
895        routes.insert(
896            "https://downloads.example/checksums.txt".to_owned(),
897            format!("{}  {name}\n", hex_sha256(&archive)).into_bytes(),
898        );
899        routes.insert(format!("https://downloads.example/{name}"), archive);
900        Arc::new(MapDoer {
901            routes,
902            ..Default::default()
903        })
904    }
905
906    fn config_yaml(root: &Path, configs: &str) -> SyncConfig {
907        let text = format!(
908            "plugins:\n  enabled: true\n  dir: {}\n  configs:\n{configs}",
909            root.display()
910        );
911        SyncConfig::from_document(&serde_yaml_ng::from_str(&text).unwrap())
912    }
913
914    /// Go `syncTestConfig`.
915    fn sync_test_config(root: &Path) -> SyncConfig {
916        config_yaml(
917            root,
918            "    sample:
919      enabled: true
920      store:
921        id: sample
922        name: Sample
923        description: Adds sample support.
924        author: owner
925        version: 0.2.0
926        release-tag: v0.2.0
927        repository: https://github.com/owner/sample-plugin
928",
929        )
930    }
931
932    /// Go `pluginTestPath`.
933    fn plugin_test_path(root: &Path, goos: &str, goarch: &str, id: &str, version: &str) -> PathBuf {
934        let mut name = id.to_owned();
935        if !version.is_empty() {
936            name += &format!("-v{version}");
937        }
938        root.join(goos)
939            .join(goarch)
940            .join(name + crate::platform::extension(goos))
941    }
942
943    fn write_plugin(path: &Path) {
944        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
945        std::fs::write(path, "library-data").unwrap();
946    }
947
948    fn windows() -> Platform {
949        Platform {
950            goos: "windows".into(),
951            goarch: "amd64".into(),
952        }
953    }
954
955    fn linux() -> Platform {
956        Platform {
957            goos: "linux".into(),
958            goarch: "amd64".into(),
959        }
960    }
961
962    fn host_platform() -> (String, String) {
963        let p = current_platform();
964        (p.goos, p.goarch)
965    }
966
967    fn in_a_minute() -> GoTime {
968        GoTime(Some(
969            (chrono::Utc::now() + chrono::Duration::seconds(60)).fixed_offset(),
970        ))
971    }
972
973    #[tokio::test]
974    async fn sync_platform_installs_manifest_artifact() {
975        let root = tempdir();
976        let (_, error) = sync_platform_with_report(&sync_test_config(&root), &release_doer(), None, &windows()).await;
977        assert_eq!(error, None);
978        let target = plugin_test_path(&root, "windows", "amd64", "sample", "0.2.0");
979        assert_eq!(std::fs::read_to_string(target).unwrap(), "library-data");
980    }
981
982    #[tokio::test]
983    async fn sync_resolved_with_report_uses_temporary_auth_and_clears_it() {
984        let root = tempdir();
985        let (goos, goarch) = host_platform();
986        let library = format!("sample{}", crate::platform::extension(&goos));
987        let archive = make_zip(&[(&library, "library-data")]);
988        let url = "https://downloads.example/private/sample.zip";
989        let doer = Arc::new(MapDoer {
990            routes: BTreeMap::from([(url.to_owned(), archive.clone())]),
991            bearer: Some("temporary-token".into()),
992            ..Default::default()
993        });
994        let items = vec![PluginSyncItem {
995            manifest: Manifest {
996                schema_version: 2,
997                id: "sample".into(),
998                version: "1.0.0".into(),
999                install: InstallPlan {
1000                    install_type: INSTALL_TYPE_DIRECT.into(),
1001                    artifacts: vec![Artifact {
1002                        goos: goos.clone(),
1003                        goarch: goarch.clone(),
1004                        url: url.into(),
1005                        sha256: hex_sha256(&archive),
1006                        size: archive.len() as i64,
1007                    }],
1008                },
1009                ..Default::default()
1010            },
1011            auth: vec![ResolvedAuthConfig {
1012                matches: "https://downloads.example/private/".into(),
1013                apply_to: vec![REQUEST_KIND_ARTIFACT.into()],
1014                auth_type: "bearer".into(),
1015                token: Secret(b"temporary-token".to_vec()),
1016                ..Default::default()
1017            }],
1018        }];
1019        let cfg = config_yaml(&root, "    sample:\n      enabled: true\n");
1020        let installed = BTreeMap::from([("sample".to_owned(), "0.9.0".to_owned())]);
1021        let http: Arc<dyn Doer> = doer.clone();
1022        // The items move into the sync, which drops (and so zeroes) their credentials.
1023        let (report, error) = sync_resolved_with_report(&cfg, items, in_a_minute(), &installed, &http, None).await;
1024        assert_eq!(error, None);
1025        assert!(doer.authenticated.load(Ordering::SeqCst));
1026        assert!(report.ok);
1027        assert_eq!(report.plugins.0.len(), 1);
1028        assert_eq!(report.plugins.0[0].version, "1.0.0");
1029        let target = plugin_test_path(&root, &goos, &goarch, "sample", "1.0.0");
1030        assert_eq!(std::fs::read_to_string(target).unwrap(), "library-data");
1031    }
1032
1033    #[tokio::test]
1034    async fn sync_resolved_with_report_includes_unchanged_installed_plugins() {
1035        let root = tempdir();
1036        let (goos, goarch) = host_platform();
1037        let target = plugin_test_path(&root, &goos, &goarch, "sample", "1.0.0");
1038        write_plugin(&target);
1039        let cfg = config_yaml(
1040            &root,
1041            "    sample:
1042      enabled: true
1043      store:
1044        id: sample
1045        name: Sample
1046        description: Adds sample support.
1047        author: owner
1048        version: 1.0.0
1049        release-tag: v1.0.0
1050        repository: https://github.com/owner/sample-plugin
1051",
1052        );
1053        let installed = BTreeMap::from([("sample".to_owned(), "1.0.0".to_owned())]);
1054        let http: Arc<dyn Doer> = Arc::new(MapDoer::default());
1055        let (mut report, error) =
1056            sync_resolved_with_report(&cfg, Vec::new(), in_a_minute(), &installed, &http, None).await;
1057        assert_eq!(error, None);
1058        assert_eq!(report.plugins.0.len(), 1);
1059        let status = &report.plugins.0[0];
1060        assert_eq!(
1061            (status.id.as_str(), status.install_status.as_str()),
1062            ("sample", SKIPPED)
1063        );
1064        assert_eq!(status.path, target.to_string_lossy());
1065        assert_eq!(status.release_tag, "v1.0.0");
1066        assert_eq!(status.repository, "https://github.com/owner/sample-plugin");
1067        assert_eq!(status.install_type, INSTALL_TYPE_GITHUB_RELEASE);
1068        assert!(mark_load_results(&mut report, Some(&FakeRuntime::default())).is_some());
1069        assert_eq!(report.plugins.0[0].load_status, FAILED);
1070    }
1071
1072    #[tokio::test]
1073    async fn sync_resolved_with_report_does_not_mix_installed_and_configured_metadata() {
1074        let root = tempdir();
1075        let (goos, goarch) = host_platform();
1076        let target = plugin_test_path(&root, &goos, &goarch, "sample", "1.0.0");
1077        write_plugin(&target);
1078        let cfg = config_yaml(
1079            &root,
1080            "    sample:
1081      enabled: true
1082      store:
1083        id: sample
1084        name: Sample
1085        description: Adds sample support.
1086        author: owner
1087        version: 2.0.0
1088        release-tag: v2.0.0
1089        repository: https://github.com/owner/sample-plugin-v2
1090",
1091        );
1092        let installed = BTreeMap::from([("sample".to_owned(), "1.0.0".to_owned())]);
1093        let http: Arc<dyn Doer> = Arc::new(MapDoer::default());
1094        let (report, error) = sync_resolved_with_report(&cfg, Vec::new(), in_a_minute(), &installed, &http, None).await;
1095        assert_eq!(error, None);
1096        assert_eq!(report.plugins.0.len(), 1);
1097        let status = &report.plugins.0[0];
1098        assert_eq!(
1099            (status.version.as_str(), status.path.as_str()),
1100            ("1.0.0", &*target.to_string_lossy())
1101        );
1102        assert_eq!(
1103            (
1104                status.release_tag.as_str(),
1105                status.repository.as_str(),
1106                status.install_type.as_str()
1107            ),
1108            ("", "", "")
1109        );
1110    }
1111
1112    #[test]
1113    fn installed_versions_uses_plugin_files_on_disk() {
1114        let root = tempdir();
1115        let (goos, goarch) = host_platform();
1116        write_plugin(&plugin_test_path(&root, &goos, &goarch, "sample", "2.3.4"));
1117        let cfg = config_yaml(&root, "    sample: {}\n");
1118        let versions = installed_versions(&cfg).unwrap();
1119        assert_eq!(versions.get("sample").map(String::as_str), Some("2.3.4"));
1120    }
1121
1122    #[tokio::test]
1123    async fn sync_platform_with_report_records_successful_install() {
1124        let root = tempdir();
1125        let (report, error) =
1126            sync_platform_with_report(&sync_test_config(&root), &release_doer(), None, &windows()).await;
1127        assert_eq!(error, None);
1128        assert!(report.ok);
1129        assert_eq!(
1130            (report.status.as_str(), report.phase.as_str()),
1131            (STATUS_OK, PHASE_INSTALL)
1132        );
1133        assert_eq!(report.plugins.0.len(), 1);
1134        let plugin = &report.plugins.0[0];
1135        assert_eq!(
1136            (
1137                plugin.id.as_str(),
1138                plugin.install_status.as_str(),
1139                plugin.version.as_str()
1140            ),
1141            ("sample", INSTALLED, "0.2.0")
1142        );
1143        let want = plugin_test_path(&root, "windows", "amd64", "sample", "0.2.0");
1144        assert_eq!(plugin.path, want.to_string_lossy());
1145    }
1146
1147    #[tokio::test]
1148    async fn sync_platform_with_report_records_skipped_identical_artifact() {
1149        let root = tempdir();
1150        let target = plugin_test_path(&root, "windows", "amd64", "sample", "0.2.0");
1151        write_plugin(&target);
1152        let (report, error) =
1153            sync_platform_with_report(&sync_test_config(&root), &release_doer(), None, &windows()).await;
1154        assert_eq!(error, None);
1155        assert!(report.ok);
1156        assert_eq!(report.plugins.0.len(), 1);
1157        let plugin = &report.plugins.0[0];
1158        assert_eq!(
1159            (plugin.id.as_str(), plugin.install_status.as_str()),
1160            ("sample", SKIPPED)
1161        );
1162        assert!(plugin.skipped);
1163        assert_eq!(plugin.path, target.to_string_lossy());
1164    }
1165
1166    #[tokio::test]
1167    async fn sync_platform_skips_identical_busy_plugin() {
1168        let root = tempdir();
1169        let target = plugin_test_path(&root, "windows", "amd64", "sample", "0.2.0");
1170        write_plugin(&target);
1171        let runtime = busy_runtime();
1172        let (_, error) = sync_platform_with_report(
1173            &sync_test_config(&root),
1174            &release_doer(),
1175            Some(&dyn_runtime(&runtime)),
1176            &windows(),
1177        )
1178        .await;
1179        assert_eq!(error, None);
1180        assert!(runtime.unloaded.lock().unwrap().is_empty());
1181        assert_eq!(std::fs::read_to_string(target).unwrap(), "library-data");
1182    }
1183
1184    #[tokio::test]
1185    async fn sync_platform_skips_config_without_manifest() {
1186        let root = tempdir();
1187        let cfg = config_yaml(&root, "    sample:\n      enabled: true\n");
1188        let http: Arc<dyn Doer> = Arc::new(MapDoer::default());
1189        let (report, error) = sync_platform_with_report(&cfg, &http, None, &linux()).await;
1190        assert_eq!(error, None);
1191        assert!(report.plugins.0.is_empty());
1192    }
1193
1194    #[tokio::test]
1195    async fn sync_platform_rejects_invalid_manifest() {
1196        let root = tempdir();
1197        let cfg = config_yaml(
1198            &root,
1199            "    sample:\n      enabled: true\n      store:\n        id: sample\n",
1200        );
1201        let http: Arc<dyn Doer> = Arc::new(MapDoer::default());
1202        assert!(sync_platform_with_report(&cfg, &http, None, &linux()).await.1.is_some());
1203    }
1204
1205    #[tokio::test]
1206    async fn sync_platform_with_report_records_invalid_manifest() {
1207        let root = tempdir();
1208        let cfg = config_yaml(
1209            &root,
1210            "    sample:\n      enabled: true\n      store:\n        id: sample\n",
1211        );
1212        let http: Arc<dyn Doer> = Arc::new(MapDoer::default());
1213        let (report, error) = sync_platform_with_report(&cfg, &http, None, &linux()).await;
1214        assert!(error.is_some());
1215        assert!(!report.ok);
1216        assert_eq!(report.status, STATUS_ERROR);
1217        assert_eq!(report.plugins.0.len(), 1);
1218        let plugin = &report.plugins.0[0];
1219        assert_eq!((plugin.id.as_str(), plugin.install_status.as_str()), ("sample", FAILED));
1220        assert!(plugin.error.contains("invalid store manifest"), "{}", plugin.error);
1221    }
1222
1223    fn installed_report(id: &str, install_status: &str, error: &str) -> SyncReport {
1224        SyncReport {
1225            status: STATUS_OK.into(),
1226            ok: true,
1227            phase: PHASE_INSTALL.into(),
1228            plugins: NonNil(vec![PluginInstallStatus {
1229                id: id.into(),
1230                install_status: install_status.into(),
1231                error: error.into(),
1232                ..Default::default()
1233            }]),
1234            ..Default::default()
1235        }
1236    }
1237
1238    #[test]
1239    fn mark_load_results_fails_when_installed_plugin_did_not_load() {
1240        let mut report = installed_report("sample", INSTALLED, "");
1241        assert!(mark_load_results(&mut report, Some(&FakeRuntime::default())).is_some());
1242        assert!(!report.ok);
1243        assert_eq!(
1244            (report.status.as_str(), report.phase.as_str()),
1245            (STATUS_ERROR, PHASE_LOAD)
1246        );
1247        assert_eq!(report.plugins.0[0].load_status, FAILED);
1248        assert!(report.plugins.0[0].error.contains("installed but not loaded"));
1249    }
1250
1251    #[test]
1252    fn mark_load_results_preserves_install_failure() {
1253        let mut report = installed_report("sample", FAILED, "install boom");
1254        report.status = STATUS_ERROR.into();
1255        report.ok = false;
1256        let runtime = FakeRuntime {
1257            registered: vec!["sample"],
1258            ..Default::default()
1259        };
1260        assert!(mark_load_results(&mut report, Some(&runtime)).is_some());
1261        assert!(!report.ok);
1262        assert_eq!(report.status, STATUS_ERROR);
1263        assert_eq!(report.plugins.0[0].load_status, SKIPPED);
1264    }
1265
1266    #[test]
1267    fn mark_load_results_preserves_global_sync_failure() {
1268        let mut report = new_report(&linux());
1269        report.plugins.0.push(PluginInstallStatus {
1270            id: "installed".into(),
1271            install_status: INSTALLED.into(),
1272            ..Default::default()
1273        });
1274        finish(&mut report, Some("home plugins: plugin sync response expired"));
1275        let runtime = FakeRuntime {
1276            registered: vec!["installed"],
1277            ..Default::default()
1278        };
1279        let error = mark_load_results(&mut report, Some(&runtime)).unwrap();
1280        assert!(error.contains("plugin sync response expired"));
1281        assert!(!report.ok);
1282        assert_eq!(
1283            (report.status.as_str(), report.phase.as_str()),
1284            (STATUS_ERROR, PHASE_LOAD)
1285        );
1286        assert!(report.error.contains("plugin sync response expired"));
1287        assert_eq!(report.plugins.0[0].load_status, LOADED);
1288    }
1289
1290    #[test]
1291    fn completed_sync_report_both_outcomes() {
1292        // Go TestCompletedSyncReport.
1293        let ok = completed_sync_report(&linux(), None);
1294        assert!(ok.ok && ok.task == TASK_SYNC && ok.finished_at.0.is_some());
1295        let failure = "home plugins: inspect installed plugins: access denied";
1296        let failed = completed_sync_report(&linux(), Some(failure));
1297        assert!(!failed.ok && failed.task == TASK_SYNC && failed.finished_at.0.is_some());
1298        assert_eq!((failed.status.as_str(), failed.error.as_str()), (STATUS_ERROR, failure));
1299    }
1300
1301    #[tokio::test]
1302    async fn delete_with_report_rejects_unresolved_plugins_dir() {
1303        let cfg = SyncConfig {
1304            dir: "~/.cli-proxy-api/plugins".into(),
1305            ..Default::default()
1306        };
1307        let home = std::env::var_os("HOME");
1308        // SAFETY: nothing else in this crate's tests reads $HOME (nextest also runs
1309        // each test in its own process).
1310        unsafe { std::env::remove_var("HOME") };
1311        let report = delete_with_report(&CancellationToken::new(), Some(&cfg), None, 41, "sample").await;
1312        if let Some(home) = home {
1313            unsafe { std::env::set_var("HOME", home) };
1314        }
1315        assert!(!report.ok);
1316        assert_eq!(report.status, STATUS_ERROR);
1317        assert_eq!(report.plugins.0.len(), 1);
1318        assert_eq!(report.plugins.0[0].install_status, FAILED);
1319        assert!(report.plugins.0[0].error.contains("resolve plugins directory"));
1320    }
1321
1322    #[tokio::test]
1323    async fn delete_with_report_removes_current_platform_plugin() {
1324        let root = tempdir();
1325        let (goos, goarch) = host_platform();
1326        let target = plugin_test_path(&root, &goos, &goarch, "sample", "");
1327        write_plugin(&target);
1328        let runtime = busy_runtime();
1329        let report = delete_with_report(
1330            &CancellationToken::new(),
1331            Some(&sync_test_config(&root)),
1332            Some(&dyn_runtime(&runtime)),
1333            42,
1334            "sample",
1335        )
1336        .await;
1337        assert!(report.ok);
1338        assert_eq!(report.task_id, 42);
1339        assert_eq!(
1340            (report.task.as_str(), report.phase.as_str()),
1341            (TASK_DELETE, PHASE_DELETE)
1342        );
1343        assert_eq!(*runtime.unloaded.lock().unwrap(), ["sample"]);
1344        assert_eq!(report.plugins.0.len(), 1);
1345        assert_eq!(report.plugins.0[0].install_status, DELETED);
1346        assert_eq!(report.plugins.0[0].path, target.to_string_lossy());
1347        assert!(!target.exists());
1348    }
1349
1350    #[tokio::test]
1351    async fn delete_with_report_removes_all_current_platform_plugin_versions() {
1352        let root = tempdir();
1353        let (goos, goarch) = host_platform();
1354        let older = plugin_test_path(&root, &goos, &goarch, "sample", "0.2.0");
1355        let newer = plugin_test_path(&root, &goos, &goarch, "sample", "0.3.0");
1356        let other = plugin_test_path(&root, &goos, &goarch, "other", "0.3.0");
1357        for path in [&older, &newer, &other] {
1358            write_plugin(path);
1359        }
1360        let runtime = busy_runtime();
1361        let report = delete_with_report(
1362            &CancellationToken::new(),
1363            Some(&sync_test_config(&root)),
1364            Some(&dyn_runtime(&runtime)),
1365            43,
1366            "sample",
1367        )
1368        .await;
1369        assert!(report.ok);
1370        assert_eq!(*runtime.unloaded.lock().unwrap(), ["sample"]);
1371        assert_eq!(report.plugins.0[0].install_status, DELETED);
1372        // The newest version is the representative path.
1373        assert_eq!(report.plugins.0[0].path, newer.to_string_lossy());
1374        assert!(!older.exists() && !newer.exists());
1375        assert!(other.exists());
1376    }
1377
1378    #[tokio::test]
1379    async fn delete_with_report_stops_before_unload_when_context_canceled() {
1380        let root = tempdir();
1381        let (goos, goarch) = host_platform();
1382        let path = plugin_test_path(&root, &goos, &goarch, "sample", "1.0.0");
1383        write_plugin(&path);
1384        let runtime = busy_runtime();
1385        let cancel = CancellationToken::new();
1386        cancel.cancel();
1387        let report = delete_with_report(
1388            &cancel,
1389            Some(&sync_test_config(&root)),
1390            Some(&dyn_runtime(&runtime)),
1391            44,
1392            "sample",
1393        )
1394        .await;
1395        assert!(!report.ok);
1396        assert!(report.error.contains(CANCELED));
1397        assert!(runtime.unloaded.lock().unwrap().is_empty());
1398        assert!(path.exists());
1399    }
1400
1401    #[tokio::test]
1402    async fn delete_with_report_uses_contextual_unload() {
1403        // Go passes the task's context to the unload: cancelling the delete cancels the
1404        // unload it started. The host side is `a_cancelled_home_unload_releases_the_host`.
1405        let root = tempdir();
1406        let (goos, goarch) = host_platform();
1407        write_plugin(&plugin_test_path(&root, &goos, &goarch, "sample", "1.0.0"));
1408        let runtime = busy_runtime();
1409        let cancel = CancellationToken::new();
1410        let report = delete_with_report(
1411            &cancel,
1412            Some(&sync_test_config(&root)),
1413            Some(&dyn_runtime(&runtime)),
1414            45,
1415            "sample",
1416        )
1417        .await;
1418        assert!(report.ok, "{report:?}");
1419        assert_eq!(*runtime.unloaded.lock().unwrap(), ["sample"]);
1420        let received = runtime.unload_cancels.lock().unwrap()[0].clone();
1421        assert!(!received.is_cancelled());
1422        cancel.cancel();
1423        assert!(
1424            received.is_cancelled(),
1425            "the unload did not get the delete's cancellation"
1426        );
1427    }
1428
1429    #[tokio::test]
1430    async fn delete_with_report_missing_plugin_is_success() {
1431        let root = tempdir();
1432        let report = delete_with_report(
1433            &CancellationToken::new(),
1434            Some(&sync_test_config(&root)),
1435            None,
1436            7,
1437            "missing",
1438        )
1439        .await;
1440        assert!(report.ok);
1441        assert_eq!(report.status, STATUS_OK);
1442        assert_eq!(report.plugins.0.len(), 1);
1443        assert_eq!(report.plugins.0[0].install_status, MISSING);
1444    }
1445
1446    #[tokio::test]
1447    async fn plugin_store_clients_share_proxy_cooldown() {
1448        // Go network_scope_test.go: Home's store clients key the shared GitHub cooldown
1449        // by the trimmed proxy URL, so a cooldown seeded through that proxy holds them
1450        // without a request.
1451        let proxy_url = "http://127.0.0.1:9/plugin-store-clients-share-proxy-cooldown";
1452        let token_env = "HOME_PLUGIN_NETWORK_SCOPE_TEST_TOKEN";
1453        let token = "plugin_store_clients_share_proxy_cooldown";
1454        // SAFETY: the variable is unique to this test.
1455        unsafe { std::env::set_var(token_env, token) };
1456        let resolved = vec![ResolvedAuthConfig {
1457            matches: "https://api.github.com/".into(),
1458            auth_type: "github-token".into(),
1459            token: Secret(token.as_bytes().to_vec()),
1460            ..Default::default()
1461        }];
1462        let expires = SystemTime::now() + Duration::from_secs(3600);
1463        let plugin = Plugin {
1464            repository: "https://github.com/test/home-network-scope".into(),
1465            ..Default::default()
1466        };
1467        let seed_doer = Arc::new(RetryAfterDoer);
1468        let mut seed = Client::new(seed_doer);
1469        seed.network_scope = proxy_url.into();
1470        seed.resolved_auth = resolved.clone();
1471        seed.resolved_auth_expires_at = Some(expires);
1472        assert!(matches!(
1473            seed.fetch_latest_release(&plugin).await,
1474            Err(StoreError::RateLimited(_))
1475        ));
1476
1477        let document: Value = serde_yaml_ng::from_str(&format!(
1478            "requests:\n  proxy-url: \" {proxy_url} \"\nplugins:\n  store-auth:\n    - match: https://api.github.com/\n      type: github-token\n      token-env: {token_env}\n"
1479        ))
1480        .unwrap();
1481        let cfg = SyncConfig::from_document(&document);
1482        let proxy = Arc::new(MapDoer {
1483            status: Some(502),
1484            ..Default::default()
1485        });
1486        let http: Arc<dyn Doer> = proxy.clone();
1487        let mut configured = store_client(&cfg, &http);
1488        configured.auth = cfg.store_auth.clone();
1489        let mut resolved_client = store_client(&cfg, &http);
1490        resolved_client.resolved_auth = resolved;
1491        resolved_client.resolved_auth_expires_at = Some(expires);
1492        for client in [configured, resolved_client] {
1493            let result = client.fetch_latest_release(&plugin).await;
1494            assert!(matches!(result, Err(StoreError::RateLimited(_))), "{result:?}");
1495        }
1496        assert_eq!(proxy.calls.load(Ordering::SeqCst), 0);
1497    }
1498
1499    /// GitHub's 429 with an hour's `Retry-After`.
1500    struct RetryAfterDoer;
1501
1502    impl Doer for RetryAfterDoer {
1503        fn get(&self, _url: &str, _headers: &Headers) -> BoxFuture<'_, Result<DoerResponse, String>> {
1504            Box::pin(async {
1505                Ok(DoerResponse {
1506                    status: 429,
1507                    headers: Headers::from([("Retry-After".to_owned(), vec!["3600".to_owned()])]),
1508                    body: futures_util::stream::once(async { Ok(Bytes::from_static(b"limited")) }).boxed(),
1509                })
1510            })
1511        }
1512    }
1513
1514    fn status_report(plugins: Vec<PluginInstallStatus>) -> SyncReport {
1515        SyncReport {
1516            task: TASK_SYNC.into(),
1517            status: STATUS_OK.into(),
1518            ok: true,
1519            plugins: NonNil(plugins),
1520            ..Default::default()
1521        }
1522    }
1523
1524    fn sample(install_status: &str) -> PluginInstallStatus {
1525        PluginInstallStatus {
1526            id: "sample".into(),
1527            install_status: install_status.into(),
1528            ..Default::default()
1529        }
1530    }
1531
1532    async fn report_and_capture(node_id: &str, report: SyncReport, fail: bool) -> (Result<(), String>, Vec<u8>) {
1533        let captured = Mutex::new(Vec::new());
1534        let result = report_plugin_status(
1535            |payload| {
1536                *captured.lock().unwrap() = payload;
1537                async move { if fail { Err("push failed".to_owned()) } else { Ok(()) } }
1538            },
1539            node_id,
1540            report,
1541        )
1542        .await;
1543        (result, captured.into_inner().unwrap())
1544    }
1545
1546    #[tokio::test]
1547    async fn report_plugin_status_pushes_node_report() {
1548        let (result, payload) = report_and_capture(" node-1 ", status_report(vec![sample(INSTALLED)]), false).await;
1549        result.unwrap();
1550        let payload: SyncReport = gojson::from_slice(&payload).unwrap();
1551        assert_eq!(payload.node_id, "node-1");
1552        assert!(payload.ok);
1553        assert_eq!(payload.plugins.0.len(), 1);
1554        assert!(payload.updated_at.0.is_some());
1555    }
1556
1557    #[tokio::test]
1558    async fn report_plugin_status_pushes_empty_report() {
1559        let (result, payload) = report_and_capture("node-1", status_report(Vec::new()), false).await;
1560        result.unwrap();
1561        // Go marshals an empty, non-nil slice as [].
1562        assert!(String::from_utf8_lossy(&payload).contains(r#""plugins":[]"#));
1563        let payload: SyncReport = gojson::from_slice(&payload).unwrap();
1564        assert_eq!(payload.node_id, "node-1");
1565        assert!(payload.plugins.0.is_empty());
1566    }
1567
1568    #[tokio::test]
1569    async fn report_plugin_status_requires_node_id() {
1570        let report = SyncReport {
1571            plugins: NonNil(vec![sample(FAILED)]),
1572            ..Default::default()
1573        };
1574        let (result, payload) = report_and_capture(" ", report, false).await;
1575        assert!(result.unwrap_err().contains("node id"));
1576        assert!(payload.is_empty());
1577    }
1578
1579    #[tokio::test]
1580    async fn report_plugin_status_propagates_push_error() {
1581        let report = SyncReport {
1582            plugins: NonNil(vec![sample(INSTALLED)]),
1583            ..Default::default()
1584        };
1585        let (result, _) = report_and_capture("node-1", report, true).await;
1586        assert_eq!(result.unwrap_err(), "push failed");
1587    }
1588
1589    fn tempdir() -> PathBuf {
1590        static NEXT: AtomicUsize = AtomicUsize::new(0);
1591        let dir = std::env::temp_dir().join(format!(
1592            "cpa-homeplugins-{}-{}",
1593            std::process::id(),
1594            NEXT.fetch_add(1, Ordering::SeqCst)
1595        ));
1596        let _ = std::fs::remove_dir_all(&dir);
1597        std::fs::create_dir_all(&dir).unwrap();
1598        dir
1599    }
1600}