Skip to main content

agent_works/plugin/
install.rs

1//! Plugin install lifecycle: `plugin add` / `plugin remove` (human review before
2//! install → write to disk → pin → uninstall).
3//!
4//! The channels are capped at **path + git + archive**; this does not grow into a
5//! package manager (marketplace / central catalog deferred).
6//!
7//! - **Human review before install**: [`plan_install`] only stages + produces a
8//!   [`ReviewDigest`] (full manifest + capability breakdown); only **after human
9//!   confirmation** does [`commit_install`] write to disk (product-level gate;
10//!   plugins requested by an agent are never allowed through by default);
11//! - **Pinned values**: manifest hash, each .wasm hash, `run`/module/server paths
12//!   absolutized, resolved values for capabilities' paths/hosts — all pinned into
13//!   [`PluginRegistry`] (the authority **outside** the plugin directory);
14//! - **zip-slip**: reject if an archive member path escapes the extraction
15//!   directory;
16//! - **git dependency made explicit** (Windows): the git URL channel depends on a
17//!   `git` executable on `PATH` (may embed gix later);
18//! - **Uninstall cleans all three places**: tool table (identity_keys returned to
19//!   the caller for deregistration) / ledger ([`RemovalReport::sweep_ledger`]) /
20//!   registry entries.
21//!
22//! secret rule: env/headers only flow as `${ENV:VAR}` references; this module
23//! never resolves them and never writes literals.
24
25use std::path::{Path, PathBuf};
26
27use super::manifest::{
28    ManifestError, PluginManifest, PluginToolSpec, ReviewDigest, resolve_capabilities,
29};
30use super::registry::{PluginPin, PluginRegistry, RegistryError, ToolPin, hex_sha256};
31use crate::script_tool::{
32    ScriptLawError, check_script_file_on_disk, pin_from_plugin_root, resolve_under_root,
33    script_file_index, script_file_is_program,
34};
35
36/// Archive format (archive channel).
37#[derive(Debug, Clone, Copy, PartialEq, Eq)]
38pub enum ArchiveFormat {
39    /// `.zip`。
40    Zip,
41    /// `.tar.gz` / `.tgz`。
42    TarGz,
43}
44
45/// Install source (channels capped at path + git + archive).
46#[derive(Debug, Clone, PartialEq, Eq)]
47pub enum PluginSource {
48    /// Local directory (copy install).
49    Path(PathBuf),
50    /// git URL (**depends on a git executable**; on Windows it must be on
51    /// PATH — made explicit).
52    Git {
53        /// Repository URL.
54        url: String,
55        /// Optional rev/tag/branch.
56        rev: Option<String>,
57    },
58    /// Local archive.
59    ArchivePath {
60        /// Archive path.
61        path: PathBuf,
62        /// Format.
63        format: ArchiveFormat,
64    },
65    /// Remote archive URL.
66    ArchiveUrl {
67        /// Download URL.
68        url: String,
69        /// Format.
70        format: ArchiveFormat,
71    },
72}
73
74impl PluginSource {
75    /// Parse the source from `plugin add` arguments (used by the product CLI).
76    ///
77    /// `*.git` / `git@` → git; `http(s)://` + `.zip|.tar.gz|.tgz` → archive URL;
78    /// anything else is treated as a local path (directory or archive file).
79    pub fn parse(spec: &str) -> Result<Self, InstallError> {
80        let lower = spec.to_ascii_lowercase();
81        if lower.ends_with(".git") || spec.starts_with("git@") {
82            return Ok(Self::Git {
83                url: spec.to_string(),
84                rev: None,
85            });
86        }
87        if spec.starts_with("https://") || spec.starts_with("http://") {
88            if let Some(format) = archive_format_of(&lower) {
89                return Ok(Self::ArchiveUrl {
90                    url: spec.to_string(),
91                    format,
92                });
93            }
94            return Err(InstallError::BadRequest {
95                reason: format!("unsupported URL `{spec}` (git URL or .zip/.tar.gz/.tgz archive)"),
96            });
97        }
98        let path = PathBuf::from(spec);
99        if let Some(format) = archive_format_of(&lower) {
100            return Ok(Self::ArchivePath { path, format });
101        }
102        if path.is_dir() {
103            return Ok(Self::Path(path));
104        }
105        Err(InstallError::BadRequest {
106            reason: format!("`{spec}` is not a plugin directory or archive"),
107        })
108    }
109}
110
111fn archive_format_of(lower_spec: &str) -> Option<ArchiveFormat> {
112    if lower_spec.ends_with(".zip") {
113        Some(ArchiveFormat::Zip)
114    } else if lower_spec.ends_with(".tar.gz") || lower_spec.ends_with(".tgz") {
115        Some(ArchiveFormat::TarGz)
116    } else {
117        None
118    }
119}
120
121/// Install errors. fail-closed: nothing is written to disk if any step is invalid.
122#[derive(Debug)]
123pub enum InstallError {
124    /// IO failure.
125    Io(std::io::Error),
126    /// Manifest parse/validation failure.
127    Manifest(ManifestError),
128    /// Path-law violation (escape from the plugin root, etc.).
129    PathLaw { source: ScriptLawError },
130    /// git channel failure (including **git not on PATH** — the real-world
131    /// friction made explicit for Windows).
132    Git(String),
133    /// Download failure.
134    Download(String),
135    /// Archive extraction failure.
136    Archive(String),
137    /// **zip-slip**: member path escapes the extraction directory.
138    ZipSlip { entry: String },
139    /// Registry write failure.
140    Registry(RegistryError),
141    /// Invalid arguments.
142    BadRequest { reason: String },
143    /// Plugin not installed (on remove).
144    NotInstalled { name: String },
145}
146
147impl std::fmt::Display for InstallError {
148    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
149        match self {
150            Self::Io(e) => write!(f, "install io: {e}"),
151            Self::Manifest(e) => write!(f, "install manifest: {e}"),
152            Self::PathLaw { source } => write!(f, "install path law: {source}"),
153            Self::Git(e) => write!(
154                f,
155                "git channel failed: {e} (git URLs need the git executable on PATH; on Windows install Git for Windows)"
156            ),
157            Self::Download(e) => write!(f, "download failed: {e}"),
158            Self::Archive(e) => write!(f, "archive extract failed: {e}"),
159            Self::ZipSlip { entry } => {
160                write!(
161                    f,
162                    "archive entry `{entry}` escapes the extract root (zip-slip)"
163                )
164            }
165            Self::Registry(e) => write!(f, "registry: {e}"),
166            Self::BadRequest { reason } => write!(f, "{reason}"),
167            Self::NotInstalled { name } => write!(f, "plugin `{name}` is not installed"),
168        }
169    }
170}
171
172impl std::error::Error for InstallError {}
173
174/// Staging layout (the output of `plan_install`, the input of `commit_install`).
175#[derive(Debug)]
176pub struct StagingLayout {
177    /// Staging directory (contents already in the plugin's full layout).
178    pub dir: PathBuf,
179}
180
181/// An install plan awaiting human review: staged content + review digest + pinned values.
182///
183/// **[`commit_install`] only after human confirmation** (product-level gate);
184/// [`InstallPlan::discard`] clears the staging area if not installing.
185#[derive(Debug)]
186pub struct InstallPlan {
187    /// Review digest (full manifest + capability breakdown + absolute paths).
188    pub digest: ReviewDigest,
189    /// Pinned values (paths already absolutized against the **final install dir**).
190    pub pin: PluginPin,
191    /// Final install directory (`<plugins_root>/<name>`).
192    pub plugin_root: PathBuf,
193    /// Staging layout.
194    pub staging: StagingLayout,
195    plugins_root: PathBuf,
196}
197
198impl InstallPlan {
199    /// Abandon the install: clear staging, write nothing to disk.
200    pub fn discard(self) {
201        let _ = std::fs::remove_dir_all(&self.staging.dir);
202    }
203}
204
205/// Install result.
206#[derive(Debug, Clone)]
207pub struct InstalledPlugin {
208    /// The pins (already written into the registry).
209    pub pin: PluginPin,
210    /// Install directory.
211    pub plugin_dir: PathBuf,
212    /// Tool identity keys (for tool-table registration / ledger cleanup).
213    pub identity_keys: Vec<String>,
214}
215
216/// Uninstall report: receipts for the three-place cleanup (tool table / ledger /
217/// registry).
218#[derive(Debug, Clone)]
219pub struct RemovalReport {
220    /// Plugin name.
221    pub name: String,
222    /// Tool identity keys (the caller deregisters these from the tool table).
223    pub identity_keys: Vec<String>,
224    /// Ledger prefix (`plugin.{name}.`).
225    pub ledger_prefix: String,
226    /// Whether the install directory has been deleted.
227    pub dir_removed: bool,
228    /// Whether the registry entry has been removed.
229    pub registry_removed: bool,
230}
231
232impl RemovalReport {
233    /// Sweep the ledger: wipe all tiers of `plugin.{name}.*` (no orphaned memory).
234    pub fn sweep_ledger(&self, ledger: &mut crate::approval_ledger::ApprovalLedger) -> usize {
235        ledger.remove_prefix(&self.ledger_prefix)
236    }
237}
238
239/// `plugin add` step one: materialize the source into staging, validate the
240/// manifest, compute pinned values, produce the review digest.
241///
242/// **Writes nothing to disk** (nothing into `<plugins_root>/<name>/`, nothing to
243/// the registry) — only after a human has reviewed [`InstallPlan::digest`] and
244/// confirmed does [`commit_install`] run.
245pub async fn plan_install(
246    source: &PluginSource,
247    plugins_root: &Path,
248) -> Result<InstallPlan, InstallError> {
249    let staging_dir = staging_dir_for(plugins_root);
250    std::fs::create_dir_all(&staging_dir).map_err(InstallError::Io)?;
251
252    match materialize(source, &staging_dir).await {
253        Ok(()) => {}
254        Err(e) => {
255            let _ = std::fs::remove_dir_all(&staging_dir);
256            return Err(e);
257        }
258    }
259    match build_plan(staging_dir, plugins_root) {
260        Ok(plan) => Ok(plan),
261        Err(e) => Err(e),
262    }
263}
264
265/// `plugin add` step two (**after human confirmation**): staging → final
266/// directory, pinned into the registry.
267pub fn commit_install(
268    plan: &InstallPlan,
269    registry: &mut PluginRegistry,
270) -> Result<InstalledPlugin, InstallError> {
271    // Replacement semantics for re-adding: delete the old directory first
272    // (same-name plugin slot).
273    if plan.plugin_root.exists() {
274        std::fs::remove_dir_all(&plan.plugin_root).map_err(InstallError::Io)?;
275    }
276    if let Some(parent) = plan.plugin_root.parent() {
277        std::fs::create_dir_all(parent).map_err(InstallError::Io)?;
278    }
279    std::fs::rename(&plan.staging.dir, &plan.plugin_root).map_err(InstallError::Io)?;
280
281    registry.insert(plan.pin.clone());
282    let registry_path = PluginRegistry::path_in(&plan.plugins_root);
283    registry
284        .save(&registry_path)
285        .map_err(InstallError::Registry)?;
286
287    let identity_keys = plan
288        .pin
289        .tools
290        .iter()
291        .flat_map(|t| match t {
292            // The real tool keys of the mcp form expand at load time by server
293            // tool name; here we give label keys, and the loader fills them in.
294            ToolPin::Wasm { identity, .. } | ToolPin::Script { identity, .. } => {
295                vec![identity.clone()]
296            }
297            ToolPin::Mcp { label, .. } => vec![format!("plugin.{}.{label}", plan.pin.name)],
298        })
299        .collect();
300
301    Ok(InstalledPlugin {
302        pin: plan.pin.clone(),
303        plugin_dir: plan.plugin_root.clone(),
304        identity_keys,
305    })
306}
307
308/// `plugin remove`: clean all three places (tool-table keys returned, ledger
309/// prefix sweepable, registry pins pulled), delete the install directory.
310pub fn remove_plugin(
311    plugins_root: &Path,
312    registry: &mut PluginRegistry,
313    name: &str,
314) -> Result<RemovalReport, InstallError> {
315    let pin = registry
316        .remove(name)
317        .ok_or_else(|| InstallError::NotInstalled {
318            name: name.to_string(),
319        })?;
320
321    let registry_path = PluginRegistry::path_in(plugins_root);
322    registry
323        .save(&registry_path)
324        .map_err(InstallError::Registry)?;
325
326    let plugin_dir = plugins_root.join(name);
327    let dir_removed = if plugin_dir.exists() {
328        std::fs::remove_dir_all(&plugin_dir).map_err(InstallError::Io)?;
329        true
330    } else {
331        false
332    };
333
334    let mut identity_keys = Vec::new();
335    for tool in &pin.tools {
336        match tool {
337            ToolPin::Wasm { identity, .. } | ToolPin::Script { identity, .. } => {
338                identity_keys.push(identity.clone());
339            }
340            ToolPin::Mcp { label, .. } => {
341                identity_keys.push(format!("plugin.{name}.{label}"));
342            }
343        }
344    }
345
346    Ok(RemovalReport {
347        name: name.to_string(),
348        identity_keys,
349        ledger_prefix: format!("plugin.{name}."),
350        dir_removed,
351        registry_removed: true,
352    })
353}
354
355// ── internal: materialize / plan ──────────────────────────────────────────
356
357fn staging_dir_for(plugins_root: &Path) -> PathBuf {
358    let stamp = std::time::SystemTime::now()
359        .duration_since(std::time::UNIX_EPOCH)
360        .map(|d| d.as_nanos())
361        .unwrap_or(0);
362    plugins_root.join(format!(".staging-{stamp}"))
363}
364
365async fn materialize(source: &PluginSource, staging: &Path) -> Result<(), InstallError> {
366    match source {
367        PluginSource::Path(path) => {
368            copy_dir(path, staging)?;
369            Ok(())
370        }
371        PluginSource::Git { url, rev } => git_clone(url, rev.as_deref(), staging).await,
372        PluginSource::ArchivePath { path, format } => {
373            let raw = std::fs::read(path).map_err(InstallError::Io)?;
374            extract_archive(&raw, *format, staging)
375        }
376        PluginSource::ArchiveUrl { url, format } => {
377            let raw = download(url).await?;
378            extract_archive(&raw, *format, staging)
379        }
380    }
381}
382
383async fn download(url: &str) -> Result<Vec<u8>, InstallError> {
384    let client = reqwest::Client::new();
385    let response = client
386        .get(url)
387        .send()
388        .await
389        .map_err(|e| InstallError::Download(format!("{url}: {e}")))?;
390    if !response.status().is_success() {
391        return Err(InstallError::Download(format!(
392            "{url}: HTTP {}",
393            response.status()
394        )));
395    }
396    response
397        .bytes()
398        .await
399        .map(|b| b.to_vec())
400        .map_err(|e| InstallError::Download(format!("{url}: {e}")))
401}
402
403/// git channel: `git clone` (+ optional rev). Depends on a git executable
404/// (explicit for Windows).
405async fn git_clone(url: &str, rev: Option<&str>, staging: &Path) -> Result<(), InstallError> {
406    let mut cmd = tokio::process::Command::new("git");
407    cmd.arg("clone")
408        .arg("--depth")
409        .arg("1")
410        .arg(url)
411        .arg(staging)
412        .stdin(std::process::Stdio::null())
413        .stdout(std::process::Stdio::null())
414        .stderr(std::process::Stdio::piped());
415    if let Some(rev) = rev {
416        cmd.arg("--branch").arg(rev);
417    }
418    let output = cmd
419        .output()
420        .await
421        .map_err(|e| InstallError::Git(format!("spawn git: {e}")))?;
422    if !output.status.success() {
423        return Err(InstallError::Git(
424            String::from_utf8_lossy(&output.stderr).into_owned(),
425        ));
426    }
427    Ok(())
428}
429
430fn copy_dir(from: &Path, to: &Path) -> Result<(), InstallError> {
431    std::fs::create_dir_all(to).map_err(InstallError::Io)?;
432    for entry in std::fs::read_dir(from).map_err(InstallError::Io)? {
433        let entry = entry.map_err(InstallError::Io)?;
434        let target = to.join(entry.file_name());
435        let kind = entry.file_type().map_err(InstallError::Io)?;
436        if kind.is_dir() {
437            copy_dir(&entry.path(), &target)?;
438        } else {
439            std::fs::copy(entry.path(), &target).map_err(InstallError::Io)?;
440        }
441    }
442    Ok(())
443}
444
445/// Extract into staging (zip-slip check: reject if a member path escapes the
446/// extraction directory).
447fn extract_archive(raw: &[u8], format: ArchiveFormat, staging: &Path) -> Result<(), InstallError> {
448    match format {
449        ArchiveFormat::Zip => extract_zip(raw, staging),
450        ArchiveFormat::TarGz => extract_tar_gz(raw, staging),
451    }
452}
453
454fn extract_zip(raw: &[u8], staging: &Path) -> Result<(), InstallError> {
455    let mut archive = zip::ZipArchive::new(std::io::Cursor::new(raw))
456        .map_err(|e| InstallError::Archive(e.to_string()))?;
457    for i in 0..archive.len() {
458        let mut file = archive
459            .by_index(i)
460            .map_err(|e| InstallError::Archive(e.to_string()))?;
461        let Some(rel) = file.enclosed_name() else {
462            return Err(InstallError::ZipSlip {
463                entry: file.name().to_string(),
464            });
465        };
466        let target = staging.join(&rel);
467        if file.is_dir() {
468            std::fs::create_dir_all(&target).map_err(InstallError::Io)?;
469        } else {
470            if let Some(parent) = target.parent() {
471                std::fs::create_dir_all(parent).map_err(InstallError::Io)?;
472            }
473            let mut out = std::fs::File::create(&target).map_err(InstallError::Io)?;
474            std::io::copy(&mut file, &mut out).map_err(InstallError::Io)?;
475        }
476    }
477    Ok(())
478}
479
480fn extract_tar_gz(raw: &[u8], staging: &Path) -> Result<(), InstallError> {
481    let decoder = flate2::read::GzDecoder::new(raw);
482    let mut archive = tar::Archive::new(decoder);
483    for entry in archive
484        .entries()
485        .map_err(|e| InstallError::Archive(e.to_string()))?
486    {
487        let mut entry = entry.map_err(|e| InstallError::Archive(e.to_string()))?;
488        let path = entry
489            .path()
490            .map_err(|e| InstallError::Archive(e.to_string()))?;
491        // zip-slip: after lexical normalization it must still be under the
492        // extraction directory.
493        let Some(rel) = normalize_relative(&path) else {
494            return Err(InstallError::ZipSlip {
495                entry: path.display().to_string(),
496            });
497        };
498        let target = staging.join(&rel);
499        if entry.header().entry_type().is_dir() {
500            std::fs::create_dir_all(&target).map_err(InstallError::Io)?;
501        } else {
502            if let Some(parent) = target.parent() {
503                std::fs::create_dir_all(parent).map_err(InstallError::Io)?;
504            }
505            let mut out = std::fs::File::create(&target).map_err(InstallError::Io)?;
506            std::io::copy(&mut entry, &mut out).map_err(InstallError::Io)?;
507        }
508    }
509    Ok(())
510}
511
512/// Lexical normalization of an archive member path: absolute path / `..`
513/// escape → `None` (zip-slip).
514fn normalize_relative(path: &Path) -> Option<PathBuf> {
515    use std::path::Component;
516
517    if path.is_absolute() {
518        return None;
519    }
520    let mut out = PathBuf::new();
521    for component in path.components() {
522        match component {
523            Component::Normal(part) => out.push(part),
524            Component::CurDir => {}
525            _ => return None, // reject ParentDir / RootDir / Prefix outright
526        }
527    }
528    if out.as_os_str().is_empty() {
529        None
530    } else {
531        Some(out)
532    }
533}
534
535/// Staging → plan: parse the manifest, compute pinned values against the
536/// **final directory**, produce the review digest.
537fn build_plan(staging_dir: PathBuf, plugins_root: &Path) -> Result<InstallPlan, InstallError> {
538    let manifest_path = staging_dir.join("plugin.json");
539    let manifest_raw = std::fs::read(&manifest_path).map_err(InstallError::Io)?;
540    let manifest_text = String::from_utf8_lossy(&manifest_raw).into_owned();
541    let manifest = PluginManifest::from_json(&manifest_text).map_err(InstallError::Manifest)?;
542
543    let plugin_root = plugins_root.join(&manifest.name);
544    let digest = manifest
545        .review(&plugin_root)
546        .map_err(InstallError::Manifest)?;
547
548    let pin = build_pin(&manifest, &manifest_raw, &plugin_root, &staging_dir)?;
549
550    Ok(InstallPlan {
551        digest,
552        pin,
553        plugin_root,
554        staging: StagingLayout { dir: staging_dir },
555        plugins_root: plugins_root.to_path_buf(),
556    })
557}
558
559fn build_pin(
560    manifest: &PluginManifest,
561    manifest_raw: &[u8],
562    plugin_root: &Path,
563    staging_dir: &Path,
564) -> Result<PluginPin, InstallError> {
565    let mut tools = Vec::with_capacity(manifest.tools.len());
566    for tool in &manifest.tools {
567        let identity = tool.identity(&manifest.name).map_err(|source| {
568            InstallError::Manifest(ManifestError::BadName {
569                name: tool.name().to_string(),
570                source,
571            })
572        })?;
573        match tool {
574            PluginToolSpec::Wasm(t) => {
575                let module = resolve_under_root(plugin_root, &t.module)
576                    .map_err(|source| InstallError::PathLaw { source })?;
577                // Hashes are computed over the staged content (bytes unchanged
578                // after the rename).
579                let staged_module = staging_dir.join(&t.module);
580                let bytes = std::fs::read(&staged_module).map_err(InstallError::Io)?;
581                let capabilities = resolve_capabilities(&t.capabilities, plugin_root)
582                    .map_err(|source| InstallError::PathLaw { source })?;
583                tools.push(ToolPin::Wasm {
584                    identity,
585                    module,
586                    wasm_sha256: hex_sha256(&bytes),
587                    capabilities,
588                });
589            }
590            PluginToolSpec::Script(t) => {
591                let run = pin_from_plugin_root(&t.run, plugin_root)
592                    .map_err(|source| InstallError::PathLaw { source })?;
593                // At install time the script files must be present in the
594                // package — the same fail-closed law as missing wasm files
595                // (acceptance fixture: a missing script file must block a
596                // half-package install). We check the staged content (bytes
597                // unchanged after the rename); if something is missing, report
598                // which file is missing.
599                let index =
600                    script_file_index(&t.run).map_err(|source| InstallError::PathLaw { source })?;
601                let require_executable = script_file_is_program(&t.run)
602                    .map_err(|source| InstallError::PathLaw { source })?;
603                check_script_file_on_disk(&staging_dir.join(&t.run[index]), require_executable)
604                    .map_err(|source| InstallError::PathLaw { source })?;
605                tools.push(ToolPin::Script { identity, run });
606            }
607            PluginToolSpec::Mcp(t) => {
608                let command = match &t.server.command {
609                    Some(cmd) => Some(
610                        pin_server_argv(cmd, plugin_root)
611                            .map_err(|source| InstallError::PathLaw { source })?,
612                    ),
613                    None => None,
614                };
615                tools.push(ToolPin::Mcp {
616                    label: t.name.clone(),
617                    command,
618                    env: t.server.env.clone(),
619                    url: t.server.url.clone(),
620                    headers: t.server.headers.clone(),
621                });
622            }
623        }
624    }
625
626    Ok(PluginPin {
627        name: manifest.name.clone(),
628        version: manifest.version.clone(),
629        source: "installed".into(),
630        manifest_sha256: hex_sha256(manifest_raw),
631        tools,
632    })
633}
634
635/// Argv pinning law for an in-package MCP server (same anti-substitution intent
636/// as `run[0]`, trimmed to the server context):
637///
638/// - **Path-shaped element** (contains a separator / starts with `.`) =
639///   in-package relative path → resolve to an absolute path under the plugin
640///   root and pin it (lexical normalization + reject escape from the plugin
641///   root);
642/// - **Bare name** (`python` / `npx` …) = interpreter/launcher resolved via
643///   PATH lookup, kept as-is — the server's author experience comes first
644///   (design example `["python", "server/main.py"]`);
645/// - **Absolute path** (`/usr/bin/python3`) = explicit interpreter, kept as-is.
646fn pin_server_argv(argv: &[String], plugin_root: &Path) -> Result<Vec<String>, ScriptLawError> {
647    argv.iter()
648        .map(|arg| {
649            let pathish = arg.contains('/') || arg.contains('\\') || arg.starts_with('.');
650            if !pathish || Path::new(arg).is_absolute() {
651                return Ok(arg.clone());
652            }
653            resolve_under_root(plugin_root, arg)
654        })
655        .collect()
656}
657
658#[cfg(test)]
659mod tests {
660    use super::super::manifest::ResolvedCapability;
661    use super::super::registry::PackageStatus;
662    use super::*;
663
664    /// Platform-independent absolute path (test criterion under the same law
665    /// as `Path::is_absolute`).
666    fn abs(rel: &str) -> PathBuf {
667        std::env::current_dir().unwrap().join(rel)
668    }
669
670    /// Write a script and set the executable bit (unix) — the install law
671    /// requires directly-executed `run[0]` to be executable.
672    fn write_script(path: &Path, contents: &str) {
673        std::fs::write(path, contents).unwrap();
674        #[cfg(unix)]
675        {
676            use std::os::unix::fs::PermissionsExt;
677            let mut perm = std::fs::metadata(path).unwrap().permissions();
678            perm.set_mode(0o755);
679            std::fs::set_permissions(path, perm).unwrap();
680        }
681    }
682
683    fn write_basic_plugin(dir: &Path) {
684        std::fs::create_dir_all(dir.join("scripts")).unwrap();
685        std::fs::create_dir_all(dir.join("wasm")).unwrap();
686        std::fs::create_dir_all(dir.join("server")).unwrap();
687        std::fs::write(
688            dir.join("plugin.json"),
689            serde_json::json!({
690                "schemaVersion": 1,
691                "name": "my-tools",
692                "version": "0.1.0",
693                "tools": [
694                    {
695                        "name": "deploy", "form": "script",
696                        "description": "deploy it",
697                        "run": ["scripts/deploy.sh", "--env", "${env}"],
698                        "parameters": {"env": {"type": "string"}},
699                        "timeout_secs": 120
700                    },
701                    {
702                        "name": "wiki", "form": "mcp",
703                        "server": {
704                            "command": ["python", "server/main.py"],
705                            "env": {"WIKI_TOKEN": "${ENV:WIKI_TOKEN}"}
706                        }
707                    }
708                ]
709            })
710            .to_string(),
711        )
712        .unwrap();
713        write_script(&dir.join("scripts/deploy.sh"), "#!/bin/sh\necho deployed\n");
714        std::fs::write(dir.join("server/main.py"), "print('wiki')\n").unwrap();
715    }
716
717    #[tokio::test]
718    async fn plan_then_commit_installs_and_pins() {
719        let tmp = tempfile::tempdir().unwrap();
720        let plugins_root = tmp.path().join("plugins");
721        let source_dir = tmp.path().join("src-plugin");
722        write_basic_plugin(&source_dir);
723
724        let plan = plan_install(&PluginSource::Path(source_dir), &plugins_root)
725            .await
726            .expect("plan");
727
728        // Review digest: full argv + absolute paths (mechanism side of UX
729        // criterion 3).
730        let deploy = plan
731            .digest
732            .tools
733            .iter()
734            .find(|t| t.identity == "plugin.my-tools.deploy")
735            .unwrap();
736        let run_abs = plugins_root
737            .join("my-tools")
738            .join("scripts/deploy.sh")
739            .to_string_lossy()
740            .into_owned();
741        assert_eq!(deploy.summary, format!("{run_abs} --env ${{env}}"));
742        assert_eq!(deploy.timeout_secs, Some(120));
743
744        // Before human confirmation: neither the final directory nor the
745        // registry exists.
746        assert!(!plugins_root.join("my-tools").exists());
747        assert!(!PluginRegistry::path_in(&plugins_root).exists());
748
749        // Standard install trio: env only flows as ${ENV:VAR} references
750        // (never resolved).
751        let mut registry = PluginRegistry::new();
752        let installed = commit_install(&plan, &mut registry).expect("commit");
753        assert!(plugins_root.join("my-tools/plugin.json").is_file());
754        assert!(registry.get("my-tools").is_some());
755
756        let pins = &registry.get("my-tools").unwrap().tools;
757        let script_pin = pins
758            .iter()
759            .find_map(|t| match t {
760                ToolPin::Script { identity, run } if identity == "plugin.my-tools.deploy" => {
761                    Some(run.clone())
762                }
763                _ => None,
764            })
765            .unwrap();
766        assert_eq!(script_pin[0], run_abs, "run[0] pinned to an absolute path");
767        assert!(matches!(
768            &pins[1],
769            ToolPin::Mcp { env, command: Some(cmd), .. }
770                if env.get("WIKI_TOKEN").map(String::as_str) == Some("${ENV:WIKI_TOKEN}")
771                    && cmd[0] == "python"
772                    && cmd[1].ends_with("server/main.py")
773                    && Path::new(&cmd[1]).is_absolute()
774        ));
775        assert_eq!(
776            installed.identity_keys,
777            vec!["plugin.my-tools.deploy", "plugin.my-tools.wiki"]
778        );
779
780        // The manifest hash in the registry matches the one on disk (load-time
781        // re-verification passes).
782        let report = registry.verify(&plugins_root.join("my-tools"));
783        assert_eq!(report.package, PackageStatus::Trusted);
784    }
785
786    #[tokio::test]
787    async fn discard_leaves_nothing() {
788        let tmp = tempfile::tempdir().unwrap();
789        let plugins_root = tmp.path().join("plugins");
790        let source_dir = tmp.path().join("src-plugin");
791        write_basic_plugin(&source_dir);
792
793        let plan = plan_install(&PluginSource::Path(source_dir), &plugins_root)
794            .await
795            .expect("plan");
796        plan.discard();
797        assert!(!plugins_root.join("my-tools").exists());
798        let leftovers = std::fs::read_dir(&plugins_root)
799            .map(|rd| rd.count())
800            .unwrap_or(0);
801        assert_eq!(leftovers, 0, "staging must be cleaned up too");
802    }
803
804    #[tokio::test]
805    async fn replace_reinstall_swaps_pin() {
806        // "Re-run plugin add to re-review": installing the same name again =
807        // replace + re-pin.
808        let tmp = tempfile::tempdir().unwrap();
809        let plugins_root = tmp.path().join("plugins");
810        let source_dir = tmp.path().join("src-plugin");
811        write_basic_plugin(&source_dir);
812
813        let mut registry = PluginRegistry::new();
814        let plan = plan_install(&PluginSource::Path(source_dir.clone()), &plugins_root)
815            .await
816            .unwrap();
817        commit_install(&plan, &mut registry).unwrap();
818
819        // The author changed the script content and installed again.
820        write_script(
821            &source_dir.join("scripts/deploy.sh"),
822            "#!/bin/sh\necho v2\n",
823        );
824        let plan = plan_install(&PluginSource::Path(source_dir), &plugins_root)
825            .await
826            .unwrap();
827        commit_install(&plan, &mut registry).unwrap();
828
829        let report = registry.verify(&plugins_root.join("my-tools"));
830        assert_eq!(report.package, PackageStatus::Trusted);
831    }
832
833    #[tokio::test]
834    async fn remove_clears_dir_registry_and_ledger() {
835        let tmp = tempfile::tempdir().unwrap();
836        let plugins_root = tmp.path().join("plugins");
837        let source_dir = tmp.path().join("src-plugin");
838        write_basic_plugin(&source_dir);
839
840        let mut registry = PluginRegistry::new();
841        let plan = plan_install(&PluginSource::Path(source_dir), &plugins_root)
842            .await
843            .unwrap();
844        let installed = commit_install(&plan, &mut registry).unwrap();
845
846        // Record a ledger tier first (simulate prior use).
847        let mut ledger = crate::approval_ledger::ApprovalLedger::new();
848        ledger.set_tier(
849            "plugin.my-tools.deploy",
850            crate::approval_ledger::ApprovalTier::AlwaysAllow,
851        );
852        ledger.set_tier(
853            "plugin.other.search",
854            crate::approval_ledger::ApprovalTier::AlwaysAllow,
855        );
856
857        let report = remove_plugin(&plugins_root, &mut registry, "my-tools").expect("remove");
858        assert!(report.dir_removed);
859        assert!(report.registry_removed);
860        assert!(registry.get("my-tools").is_none());
861        assert!(!installed.plugin_dir.exists());
862
863        // One of the three places: plugin.my-tools.* wiped, others untouched.
864        let swept = report.sweep_ledger(&mut ledger);
865        assert_eq!(swept, 1);
866        assert_eq!(
867            ledger.tier_of("plugin.my-tools.deploy"),
868            crate::approval_ledger::ApprovalTier::Ask
869        );
870        assert_eq!(
871            ledger.tier_of("plugin.other.search"),
872            crate::approval_ledger::ApprovalTier::AlwaysAllow
873        );
874        assert_eq!(
875            report.identity_keys,
876            vec!["plugin.my-tools.deploy", "plugin.my-tools.wiki"]
877        );
878    }
879
880    #[tokio::test]
881    async fn remove_unknown_plugin_errors() {
882        let tmp = tempfile::tempdir().unwrap();
883        let plugins_root = tmp.path().join("plugins");
884        let mut registry = PluginRegistry::new();
885        let err = remove_plugin(&plugins_root, &mut registry, "ghost").unwrap_err();
886        assert!(matches!(err, InstallError::NotInstalled { name } if name == "ghost"));
887    }
888
889    // ── zip-slip / archive channel ────────────────────────────────────
890
891    #[test]
892    fn normalize_relative_rejects_traversal() {
893        assert!(normalize_relative(Path::new("ok/inner.txt")).is_some());
894        assert!(normalize_relative(Path::new("./ok")).is_some());
895        assert!(normalize_relative(Path::new("../escape")).is_none());
896        assert!(normalize_relative(Path::new("a/../../b")).is_none());
897        assert!(normalize_relative(Path::new("/abs")).is_none());
898        assert!(normalize_relative(Path::new("")).is_none());
899    }
900
901    #[test]
902    fn tar_gz_zip_slip_is_rejected() {
903        // Build a tar.gz with a `../evil` entry (bypassing tar::Builder's path
904        // law by writing the GNU header directly — exactly how real malicious
905        // packages are made).
906        let mut raw = Vec::new();
907        {
908            let encoder = flate2::write::GzEncoder::new(&mut raw, flate2::Compression::default());
909            let mut builder = tar::Builder::new(encoder);
910            let mut header = tar::Header::new_gnu();
911            header.set_size(5);
912            header.set_mode(0o644);
913            header.set_entry_type(tar::EntryType::Regular);
914            header.as_gnu_mut().unwrap().name[..7].copy_from_slice(b"../evil");
915            header.set_cksum();
916            builder.append(&header, &b"pwned"[..]).expect("append");
917            builder.finish().expect("finish");
918        }
919
920        let tmp = tempfile::tempdir().unwrap();
921        let err = extract_archive(&raw, ArchiveFormat::TarGz, tmp.path()).unwrap_err();
922        assert!(
923            matches!(err, InstallError::ZipSlip { ref entry } if entry.contains("evil")),
924            "{err:?}"
925        );
926        assert!(!tmp.path().join("../evil").exists());
927    }
928
929    #[test]
930    fn tar_gz_extracts_clean_archive() {
931        let mut raw = Vec::new();
932        {
933            let encoder = flate2::write::GzEncoder::new(&mut raw, flate2::Compression::default());
934            let mut builder = tar::Builder::new(encoder);
935            let mut header = tar::Header::new_gnu();
936            header.set_size(5);
937            header.set_mode(0o644);
938            header.set_cksum();
939            builder
940                .append_data(&mut header, "plugin.json", &b"hello"[..])
941                .unwrap();
942            builder.finish().unwrap();
943        }
944        let tmp = tempfile::tempdir().unwrap();
945        extract_archive(&raw, ArchiveFormat::TarGz, tmp.path()).unwrap();
946        assert_eq!(
947            std::fs::read_to_string(tmp.path().join("plugin.json")).unwrap(),
948            "hello"
949        );
950    }
951
952    // ── source parsing ────────────────────────────────────────────────────
953
954    #[test]
955    fn source_parse_channels() {
956        assert_eq!(
957            PluginSource::parse("https://x.example/my-tools.git").unwrap(),
958            PluginSource::Git {
959                url: "https://x.example/my-tools.git".into(),
960                rev: None
961            }
962        );
963        assert_eq!(
964            PluginSource::parse("git@github.com:me/my-tools.git").unwrap(),
965            PluginSource::Git {
966                url: "git@github.com:me/my-tools.git".into(),
967                rev: None
968            }
969        );
970        assert_eq!(
971            PluginSource::parse("https://x.example/my-tools.tar.gz").unwrap(),
972            PluginSource::ArchiveUrl {
973                url: "https://x.example/my-tools.tar.gz".into(),
974                format: ArchiveFormat::TarGz
975            }
976        );
977        assert!(matches!(
978            PluginSource::parse("https://x.example/page.html"),
979            Err(InstallError::BadRequest { .. })
980        ));
981        assert!(matches!(
982            PluginSource::parse("/definitely/not/here"),
983            Err(InstallError::BadRequest { .. })
984        ));
985        assert_eq!(
986            PluginSource::parse("packs/my-tools.zip").unwrap(),
987            PluginSource::ArchivePath {
988                path: PathBuf::from("packs/my-tools.zip"),
989                format: ArchiveFormat::Zip
990            }
991        );
992    }
993
994    #[test]
995    fn pin_server_argv_pins_paths_keeps_interpreters() {
996        let root = abs("plugin-root-test");
997        let pinned = pin_server_argv(
998            &[
999                "python".into(),
1000                "server/main.py".into(),
1001                abs("/usr/bin/python3").to_string_lossy().into_owned(),
1002            ],
1003            &root,
1004        )
1005        .unwrap();
1006        assert_eq!(pinned[0], "python", "bare-name interpreter kept as-is");
1007        assert_eq!(
1008            pinned[1],
1009            root.join("server/main.py").to_string_lossy().into_owned(),
1010            "in-package relative path pinned absolute"
1011        );
1012        assert!(
1013            Path::new(&pinned[2]).is_absolute(),
1014            "explicit absolute interpreter kept as-is"
1015        );
1016
1017        // Path-shaped arguments that escape the plugin root are rejected.
1018        let err = pin_server_argv(&["python".into(), "../evil.py".into()], &root).unwrap_err();
1019        assert!(
1020            matches!(err, ScriptLawError::EscapedPluginRoot { .. }),
1021            "{err:?}"
1022        );
1023    }
1024
1025    #[tokio::test]
1026    async fn wasm_missing_at_install_is_reported() {
1027        // plugin.json lists a wasm tool but the .wasm is missing → cannot
1028        // install (fail-closed); a half package is never pinned into the
1029        // registry.
1030        let tmp = tempfile::tempdir().unwrap();
1031        let plugins_root = tmp.path().join("plugins");
1032        let source_dir = tmp.path().join("src-plugin");
1033        std::fs::create_dir_all(&source_dir).unwrap();
1034        std::fs::write(
1035            source_dir.join("plugin.json"),
1036            serde_json::json!({
1037                "schemaVersion": 1, "name": "my-tools", "version": "0.1.0",
1038                "tools": [{"name": "search", "form": "wasm", "module": "wasm/s.wasm", "description": "d"}]
1039            })
1040            .to_string(),
1041        )
1042        .unwrap();
1043
1044        let err = plan_install(&PluginSource::Path(source_dir), &plugins_root)
1045            .await
1046            .unwrap_err();
1047        assert!(matches!(err, InstallError::Io(_)), "{err:?}");
1048    }
1049
1050    #[tokio::test]
1051    async fn script_missing_at_install_is_reported() {
1052        // Same law as missing wasm files: the manifest lists a script tool but
1053        // the file is absent (acceptance fixture: a missing script file must
1054        // block a half-package install) → cannot install, and the error says
1055        // which file is missing.
1056        let tmp = tempfile::tempdir().unwrap();
1057        let plugins_root = tmp.path().join("plugins");
1058        let source_dir = tmp.path().join("src-plugin");
1059        std::fs::create_dir_all(source_dir.join("scripts")).unwrap();
1060        std::fs::write(
1061            source_dir.join("plugin.json"),
1062            serde_json::json!({
1063                "schemaVersion": 1, "name": "my-tools", "version": "0.1.0",
1064                "tools": [{
1065                    "name": "deploy", "form": "script",
1066                    "description": "deploy it",
1067                    "run": ["scripts/deploy.sh", "--env", "${env}"],
1068                    "parameters": {"env": {"type": "string"}}
1069                }]
1070            })
1071            .to_string(),
1072        )
1073        .unwrap();
1074
1075        let err = plan_install(&PluginSource::Path(source_dir), &plugins_root)
1076            .await
1077            .unwrap_err();
1078        assert!(
1079            err.to_string().contains("scripts/deploy.sh")
1080                && err.to_string().contains("does not exist"),
1081            "missing files must be named: {err}"
1082        );
1083    }
1084
1085    #[cfg(unix)]
1086    #[tokio::test]
1087    async fn script_not_executable_at_install_is_reported() {
1088        // `run[0]` is the script body itself, executed directly — no
1089        // executable bit = it would not run even if installed, so reject at
1090        // install time (chmod +x and come back).
1091        let tmp = tempfile::tempdir().unwrap();
1092        let plugins_root = tmp.path().join("plugins");
1093        let source_dir = tmp.path().join("src-plugin");
1094        std::fs::create_dir_all(source_dir.join("scripts")).unwrap();
1095        std::fs::write(
1096            source_dir.join("plugin.json"),
1097            serde_json::json!({
1098                "schemaVersion": 1, "name": "my-tools", "version": "0.1.0",
1099                "tools": [{
1100                    "name": "deploy", "form": "script",
1101                    "description": "deploy it",
1102                    "run": ["scripts/deploy.sh"]
1103                }]
1104            })
1105            .to_string(),
1106        )
1107        .unwrap();
1108        std::fs::write(source_dir.join("scripts/deploy.sh"), "#!/bin/sh\necho hi\n").unwrap();
1109        // 0644 — no executable bit.
1110
1111        let err = plan_install(&PluginSource::Path(source_dir), &plugins_root)
1112            .await
1113            .unwrap_err();
1114        assert!(
1115            err.to_string().contains("not executable"),
1116            "a missing executable bit must be stated clearly: {err}"
1117        );
1118    }
1119
1120    #[tokio::test]
1121    async fn script_interpreter_form_checks_the_script_arg_not_the_interpreter() {
1122        // Interpreter form: the executable bit is checked on the interpreter
1123        // (PATH resolution, not the installer's business), but the script
1124        // argument must be in the package.
1125        let tmp = tempfile::tempdir().unwrap();
1126        let plugins_root = tmp.path().join("plugins");
1127        let source_dir = tmp.path().join("src-plugin");
1128        std::fs::create_dir_all(source_dir.join("scripts")).unwrap();
1129        std::fs::write(
1130            source_dir.join("plugin.json"),
1131            serde_json::json!({
1132                "schemaVersion": 1, "name": "my-tools", "version": "0.1.0",
1133                "tools": [{
1134                    "name": "deploy", "form": "script",
1135                    "description": "deploy it",
1136                    "run": ["cmd", "/c", "scripts/deploy.bat"]
1137                }]
1138            })
1139            .to_string(),
1140        )
1141        .unwrap();
1142
1143        let err = plan_install(&PluginSource::Path(source_dir), &plugins_root)
1144            .await
1145            .unwrap_err();
1146        assert!(
1147            err.to_string().contains("deploy.bat") && err.to_string().contains("does not exist"),
1148            "the interpreter form checks the script argument: {err}"
1149        );
1150    }
1151
1152    #[tokio::test]
1153    async fn capability_pinned_with_resolved_values() {
1154        let tmp = tempfile::tempdir().unwrap();
1155        let plugins_root = tmp.path().join("plugins");
1156        let source_dir = tmp.path().join("src-plugin");
1157        std::fs::create_dir_all(source_dir.join("wasm")).unwrap();
1158        std::fs::write(source_dir.join("wasm/s.wasm"), b"wasm-bytes").unwrap();
1159        std::fs::write(
1160            source_dir.join("plugin.json"),
1161            serde_json::json!({
1162                "schemaVersion": 1, "name": "my-tools", "version": "0.1.0",
1163                "tools": [{
1164                    "name": "search", "form": "wasm", "module": "wasm/s.wasm", "description": "d",
1165                    "capabilities": [
1166                        {"type": "fs:read", "paths": ["./data"]},
1167                        {"type": "net:http", "hosts": ["API.Example.com"]}
1168                    ]
1169                }]
1170            })
1171            .to_string(),
1172        )
1173        .unwrap();
1174
1175        let plan = plan_install(&PluginSource::Path(source_dir), &plugins_root)
1176            .await
1177            .expect("plan");
1178        match &plan.pin.tools[0] {
1179            ToolPin::Wasm {
1180                capabilities,
1181                wasm_sha256,
1182                module,
1183                ..
1184            } => {
1185                let data_abs = plugins_root
1186                    .join("my-tools")
1187                    .join("data")
1188                    .to_string_lossy()
1189                    .into_owned();
1190                assert_eq!(
1191                    capabilities,
1192                    &vec![
1193                        ResolvedCapability::FsRead {
1194                            paths: vec![data_abs]
1195                        },
1196                        ResolvedCapability::NetHttp {
1197                            hosts: vec!["api.example.com".into()]
1198                        }
1199                    ]
1200                );
1201                assert_eq!(*wasm_sha256, hex_sha256(b"wasm-bytes"));
1202                assert!(Path::new(module).is_absolute());
1203            }
1204            other => panic!("expected wasm pin, got {other:?}"),
1205        }
1206    }
1207}