Skip to main content

agent_works/plugin/
registry.rs

1//! Install integrity registry (`<plugins_root>/registry.json`) — the pins live
2//! outside the directory they protect.
3//!
4//! An install.json placed inside the plugin directory can be rewritten by the same
5//! hand — anchor and anchored object in the same cave = self-deception. So the
6//! authoritative pins live only in this registry, **outside the plugin directory**,
7//! written exclusively by `plugin add` / `plugin remove`; no authoritative copy is
8//! stored inside the plugin directory.
9//!
10//! What gets pinned (design section "Plugin install"): **manifest hash + capabilities
11//! (paths/hosts resolved to absolute/normalized values) + the hash of every .wasm**.
12//! Re-verified on every load:
13//!
14//! - edit the manifest / swap the wasm / add a tool → **post-install tampering**:
15//!   all of that plugin's tools are fail-closed disabled + it reports "the plugin has
16//!   been modified; run `plugin add` again to re-review";
17//! - plugin.json lists a tool but the .wasm is missing → **corruption handling**:
18//!   that tool is disabled + an error is reported; the whole package is not silently
19//!   skipped (the other tools work as usual);
20//! - capability tightening reads **only the pinned values in this registry**, never
21//!   the plugin's own manifest.
22//!
23//! Secret rule: env/headers store only `${ENV:VAR}` references, **never** resolved
24//! token literals.
25
26use std::collections::BTreeMap;
27use std::path::{Path, PathBuf};
28
29use serde::{Deserialize, Serialize};
30
31use super::manifest::ResolvedCapability;
32
33/// Registry file name (`<plugins_root>/registry.json`).
34pub const REGISTRY_FILE: &str = "registry.json";
35
36/// Registry format version.
37pub const REGISTRY_SCHEMA_VERSION: u32 = 1;
38
39/// Registry read/write errors.
40#[derive(Debug)]
41pub enum RegistryError {
42    /// IO failure.
43    Io(std::io::Error),
44    /// Corrupt JSON (**not** silently treated as empty — this is the user's install ledger).
45    Json(String),
46    /// Unrecognized `schemaVersion`.
47    BadSchemaVersion(u32),
48}
49
50impl std::fmt::Display for RegistryError {
51    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
52        match self {
53            Self::Io(e) => write!(f, "registry io: {e}"),
54            Self::Json(e) => write!(f, "registry.json is corrupt: {e}"),
55            Self::BadSchemaVersion(v) => write!(f, "registry schemaVersion {v} is not supported"),
56        }
57    }
58}
59
60impl std::error::Error for RegistryError {}
61
62/// Pinned values for one tool (enforcement accepts only these, not the plugin manifest).
63#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
64#[serde(tag = "form", rename_all = "lowercase")]
65pub enum ToolPin {
66    /// wasm form: absolute component path + content hash + resolved capabilities.
67    Wasm {
68        /// Identity key `plugin.{plugin}.{tool}`.
69        identity: String,
70        /// Absolute component path (pinned at install time).
71        module: String,
72        /// Component content sha256 (hex).
73        wasm_sha256: String,
74        /// Pinned capability allowlist values (paths absolute / hosts normalized).
75        #[serde(default, skip_serializing_if = "Vec::is_empty")]
76        capabilities: Vec<ResolvedCapability>,
77    },
78    /// script form: pinned argv (absolute paths to prevent substitution).
79    Script {
80        /// Identity key `plugin.{plugin}.{tool}`.
81        identity: String,
82        /// argv (`run[0]`, or the interpreter's script argument, has been absolutized).
83        run: Vec<String>,
84    },
85    /// mcp form: pinned config for an in-package server (owned by the plugin; not written to connections.json).
86    Mcp {
87        /// Server label (the `name` in the manifest).
88        label: String,
89        /// stdio form argv (in-package paths absolutized).
90        #[serde(default, skip_serializing_if = "Option::is_none")]
91        command: Option<Vec<String>>,
92        /// stdio environment variable overrides (**store only `${ENV:VAR}` references**).
93        #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
94        env: BTreeMap<String, String>,
95        /// Remote URL form.
96        #[serde(default, skip_serializing_if = "Option::is_none")]
97        url: Option<String>,
98        /// Remote request headers (**store only `${ENV:VAR}` references**).
99        #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
100        headers: BTreeMap<String, String>,
101    },
102}
103
104impl ToolPin {
105    /// Identity key (for the mcp form, the normalized placeholder key of the label, `plugin.{plugin}.{label}`).
106    pub fn identity(&self, plugin: &str) -> String {
107        match self {
108            Self::Wasm { identity, .. } | Self::Script { identity, .. } => identity.clone(),
109            Self::Mcp { label, .. } => format!("plugin.{plugin}.{label}"),
110        }
111    }
112
113    /// Form name (wasm / script / mcp) — the error surface when a load-time pin doesn't match the manifest's form.
114    pub fn form(&self) -> &'static str {
115        match self {
116            Self::Wasm { .. } => "wasm",
117            Self::Script { .. } => "script",
118            Self::Mcp { .. } => "mcp",
119        }
120    }
121}
122
123/// The pins for one installed plugin.
124#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
125pub struct PluginPin {
126    /// Plugin name.
127    pub name: String,
128    /// Author's version (for audit display; integrity is judged by the hash).
129    pub version: String,
130    /// Source (path / git URL / archive URL) — for provenance, not a root of trust.
131    pub source: String,
132    /// sha256 (hex) of the raw plugin.json bytes.
133    pub manifest_sha256: String,
134    /// Per-tool pinned values.
135    pub tools: Vec<ToolPin>,
136}
137
138/// Package-level integrity verdict.
139#[derive(Debug, Clone, PartialEq, Eq)]
140pub enum PackageStatus {
141    /// manifest / wasm hashes match the pins.
142    Trusted,
143    /// **Post-install tampering**: manifest edited / wasm swapped / tool added → all tools disabled,
144    /// "the plugin has been modified; run `plugin add` again to re-review".
145    Tampered { reason: String },
146}
147
148/// Per-tool load status.
149#[derive(Debug, Clone, PartialEq, Eq)]
150pub enum ToolStatus {
151    /// Loadable (hash matches, file present).
152    Ready,
153    /// Missing/corrupt → **that tool** is disabled + an error is reported; the whole package is not skipped.
154    Broken { detail: String },
155}
156
157/// One re-verification finding.
158#[derive(Debug, Clone, PartialEq, Eq)]
159pub enum VerifyIssue {
160    /// plugin.json content does not match the pin.
161    ManifestHashMismatch,
162    /// The tool set in the manifest does not match the pin (tool added / removed / renamed).
163    ToolSetChanged { detail: String },
164    /// Some .wasm content does not match the pin (wasm swapped).
165    WasmHashMismatch { identity: String },
166    /// Some .wasm is missing.
167    MissingModule { identity: String, path: String },
168}
169
170/// The report of one load-time re-verification.
171#[derive(Debug, Clone, PartialEq, Eq)]
172pub struct VerifyReport {
173    /// Plugin name.
174    pub plugin: String,
175    /// Package-level verdict (Tampered ⇒ all of this plugin's tools are disabled).
176    pub package: PackageStatus,
177    /// Per-tool status (identity → status).
178    pub tools: Vec<(String, ToolStatus)>,
179    /// Finding list (for panel error display).
180    pub issues: Vec<VerifyIssue>,
181}
182
183impl VerifyReport {
184    /// Whether it was tampered with after install (all tools disabled + "re-run add to re-review").
185    pub fn tampered(&self) -> bool {
186        self.package != PackageStatus::Trusted
187    }
188
189    /// One-line panel message (design copy: "the plugin has been modified; run `plugin add` again to re-review").
190    pub fn user_message(&self) -> Option<String> {
191        match &self.package {
192            PackageStatus::Tampered { reason } => Some(format!(
193                "plugin `{}` has been modified ({reason}); run `plugin add` again to re-review",
194                self.plugin
195            )),
196            PackageStatus::Trusted => None,
197        }
198    }
199}
200
201/// Central registry (`<plugins_root>/registry.json`).
202#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
203pub struct PluginRegistry {
204    /// Format version.
205    pub schema_version: u32,
206    /// Plugin name → pin.
207    pub plugins: BTreeMap<String, PluginPin>,
208}
209
210impl Default for PluginRegistry {
211    fn default() -> Self {
212        Self::new()
213    }
214}
215
216impl PluginRegistry {
217    /// Empty registry (schemaVersion 1).
218    pub fn new() -> Self {
219        Self {
220            schema_version: REGISTRY_SCHEMA_VERSION,
221            plugins: BTreeMap::new(),
222        }
223    }
224
225    /// Read the registry. **Missing = empty table; corrupt = error** (never silently
226    /// treated as empty — this is the user's install ledger, and silently clearing it
227    /// would throw away the anchors of every reviewed plugin).
228    pub fn load(path: &Path) -> Result<Self, RegistryError> {
229        match std::fs::read_to_string(path) {
230            Ok(raw) => {
231                let registry: Self =
232                    serde_json::from_str(&raw).map_err(|e| RegistryError::Json(e.to_string()))?;
233                if registry.schema_version != REGISTRY_SCHEMA_VERSION {
234                    return Err(RegistryError::BadSchemaVersion(registry.schema_version));
235                }
236                Ok(registry)
237            }
238            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Self::new()),
239            Err(e) => Err(RegistryError::Io(e)),
240        }
241    }
242
243    /// Write back (pure JSON, machine-written; called only by `plugin add` / `plugin remove`).
244    pub fn save(&self, path: &Path) -> Result<(), RegistryError> {
245        if let Some(dir) = path.parent()
246            && !dir.as_os_str().is_empty()
247        {
248            std::fs::create_dir_all(dir).map_err(RegistryError::Io)?;
249        }
250        let raw =
251            serde_json::to_string_pretty(self).map_err(|e| RegistryError::Json(e.to_string()))?;
252        std::fs::write(path, raw).map_err(RegistryError::Io)
253    }
254
255    /// Registry path (convenience: `registry.json` under plugins_root).
256    pub fn path_in(plugins_root: &Path) -> PathBuf {
257        plugins_root.join(REGISTRY_FILE)
258    }
259
260    /// Get one plugin's pin.
261    pub fn get(&self, name: &str) -> Option<&PluginPin> {
262        self.plugins.get(name)
263    }
264
265    /// Pin in / overwrite (for `plugin add` only).
266    pub fn insert(&mut self, pin: PluginPin) {
267        self.plugins.insert(pin.name.clone(), pin);
268    }
269
270    /// Pull one plugin's pin (for `plugin remove` only).
271    pub fn remove(&mut self, name: &str) -> Option<PluginPin> {
272        self.plugins.remove(name)
273    }
274
275    /// Number of pinned plugins.
276    pub fn len(&self) -> usize {
277        self.plugins.len()
278    }
279
280    /// Whether it is empty.
281    pub fn is_empty(&self) -> bool {
282        self.plugins.is_empty()
283    }
284
285    /// Load-time re-verification: pins vs the plugin directory on disk.
286    ///
287    /// - manifest hash mismatch / tool set mismatch / any .wasm swapped → package-level
288    ///   [`PackageStatus::Tampered`] (all tools disabled + "re-run add to re-review");
289    /// - .wasm missing → per-tool [`ToolStatus::Broken`] (the package is not skipped);
290    /// - "manifest unreadable but hash matches" cannot happen (hash = content), so an
291    ///   unreadable manifest means tampering.
292    pub fn verify(&self, plugin_dir: &Path) -> VerifyReport {
293        // No file_name (root path) or no pin found by name → the tampering path.
294        let Some(pin) = plugin_dir
295            .file_name()
296            .and_then(|n| n.to_str())
297            .and_then(|n| self.plugins.get(n))
298        else {
299            let name = plugin_dir
300                .file_name()
301                .map(|n| n.to_string_lossy().into_owned())
302                .unwrap_or_default();
303            return VerifyReport {
304                plugin: name,
305                package: PackageStatus::Tampered {
306                    reason: "not installed (no registry pin)".into(),
307                },
308                tools: Vec::new(),
309                issues: vec![VerifyIssue::ManifestHashMismatch],
310            };
311        };
312        self.verify_pin(pin, plugin_dir)
313    }
314
315    /// Re-verify an installed plugin by name (used by the loader).
316    pub fn verify_plugin(&self, name: &str, plugin_dir: &Path) -> VerifyReport {
317        let Some(pin) = self.plugins.get(name) else {
318            return VerifyReport {
319                plugin: name.to_string(),
320                package: PackageStatus::Tampered {
321                    reason: "not installed (no registry pin)".into(),
322                },
323                tools: Vec::new(),
324                issues: vec![VerifyIssue::ManifestHashMismatch],
325            };
326        };
327        self.verify_pin(pin, plugin_dir)
328    }
329
330    fn verify_pin(&self, pin: &PluginPin, plugin_dir: &Path) -> VerifyReport {
331        let mut issues = Vec::new();
332        let mut tool_status: BTreeMap<String, ToolStatus> = BTreeMap::new();
333
334        // 1. manifest hash: manifest edited → tampered.
335        let manifest_path = plugin_dir.join("plugin.json");
336        let manifest_raw = std::fs::read(&manifest_path).ok();
337        let manifest_ok = match &manifest_raw {
338            Some(raw) if hex_sha256(raw) == pin.manifest_sha256 => true,
339            Some(_) => {
340                issues.push(VerifyIssue::ManifestHashMismatch);
341                false
342            }
343            None => {
344                issues.push(VerifyIssue::ManifestHashMismatch);
345                false
346            }
347        };
348
349        // 2. tool set consistency (tool added / removed / renamed → tampered).
350        if manifest_ok
351            && let Some(raw) = &manifest_raw
352            && let Ok(text) = std::str::from_utf8(raw)
353            && let Ok(manifest) = super::manifest::PluginManifest::from_json(text)
354        {
355            let manifest_keys: Vec<String> = manifest
356                .tools
357                .iter()
358                .map(|t| t.name().to_string())
359                .collect();
360            let pin_keys: Vec<String> = pin
361                .tools
362                .iter()
363                .map(|t| match t {
364                    ToolPin::Wasm { identity, .. } | ToolPin::Script { identity, .. } => {
365                        // identity = plugin.{name}.{tool} → take the tool segment
366                        identity.rsplit('.').next().unwrap_or_default().to_string()
367                    }
368                    ToolPin::Mcp { label, .. } => label.clone(),
369                })
370                .collect();
371            if manifest_keys != pin_keys {
372                issues.push(VerifyIssue::ToolSetChanged {
373                    detail: format!("manifest tools {manifest_keys:?} vs pinned {pin_keys:?}"),
374                });
375            }
376        }
377
378        // 3. per tool: wasm hash (wasm swapped → tampered); file missing → that tool Broken.
379        for tool in &pin.tools {
380            let (identity, status) = match tool {
381                ToolPin::Wasm {
382                    identity,
383                    module,
384                    wasm_sha256,
385                    ..
386                } => {
387                    let path = Path::new(module);
388                    if !path.is_file() {
389                        issues.push(VerifyIssue::MissingModule {
390                            identity: identity.clone(),
391                            path: module.clone(),
392                        });
393                        (
394                            identity.clone(),
395                            ToolStatus::Broken {
396                                detail: format!("module missing: {module}"),
397                            },
398                        )
399                    } else {
400                        match std::fs::read(path) {
401                            Ok(bytes) if hex_sha256(&bytes) == *wasm_sha256 => {
402                                (identity.clone(), ToolStatus::Ready)
403                            }
404                            Ok(_) => {
405                                issues.push(VerifyIssue::WasmHashMismatch {
406                                    identity: identity.clone(),
407                                });
408                                (
409                                    identity.clone(),
410                                    ToolStatus::Broken {
411                                        detail: "wasm hash mismatch".into(),
412                                    },
413                                )
414                            }
415                            Err(e) => (
416                                identity.clone(),
417                                ToolStatus::Broken {
418                                    detail: format!("module unreadable: {e}"),
419                                },
420                            ),
421                        }
422                    }
423                }
424                ToolPin::Script { identity, run } => {
425                    // Missing script file = corruption handling (that tool is disabled;
426                    // the package is not skipped).
427                    let missing = std::fs::metadata(&run[0])
428                        .map(|m| !m.is_file())
429                        .unwrap_or(true);
430                    if missing {
431                        (
432                            identity.clone(),
433                            ToolStatus::Broken {
434                                detail: format!("script missing: {}", run[0]),
435                            },
436                        )
437                    } else {
438                        (identity.clone(), ToolStatus::Ready)
439                    }
440                }
441                ToolPin::Mcp { label, .. } => {
442                    (format!("plugin.{}.{}", pin.name, label), ToolStatus::Ready)
443                }
444            };
445            tool_status.insert(identity, status);
446        }
447
448        // Package-level verdict: any mismatch of manifest / tool set / wasm hash = tampered (disable all).
449        let tampered = issues.iter().any(|i| {
450            matches!(
451                i,
452                VerifyIssue::ManifestHashMismatch
453                    | VerifyIssue::ToolSetChanged { .. }
454                    | VerifyIssue::WasmHashMismatch { .. }
455            )
456        });
457        let package = if tampered {
458            PackageStatus::Tampered {
459                reason: match issues.first() {
460                    Some(VerifyIssue::ManifestHashMismatch) => "manifest changed".into(),
461                    Some(VerifyIssue::ToolSetChanged { detail }) => {
462                        format!("tool set changed ({detail})")
463                    }
464                    Some(VerifyIssue::WasmHashMismatch { identity }) => {
465                        format!("wasm replaced ({identity})")
466                    }
467                    _ => "integrity check failed".into(),
468                },
469            }
470        } else {
471            PackageStatus::Trusted
472        };
473
474        // On tampering, all tools are disabled (even if individual files are still present).
475        let tools = pin
476            .tools
477            .iter()
478            .map(|t| {
479                let identity = t.identity(&pin.name);
480                let status = if tampered {
481                    ToolStatus::Broken {
482                        detail: "plugin tampered; re-run plugin add".into(),
483                    }
484                } else {
485                    tool_status.remove(&identity).unwrap_or(ToolStatus::Ready)
486                };
487                (identity, status)
488            })
489            .collect();
490
491        VerifyReport {
492            plugin: pin.name.clone(),
493            package,
494            tools,
495            issues,
496        }
497    }
498}
499
500/// sha256 → hex (lowercase). The one canonical encoding for integrity hashes.
501pub fn hex_sha256(bytes: &[u8]) -> String {
502    use sha2::{Digest, Sha256};
503    let digest = Sha256::digest(bytes);
504    digest.iter().map(|b| format!("{b:02x}")).collect()
505}
506
507#[cfg(test)]
508mod tests {
509    use super::*;
510
511    fn pin_with_wasm(
512        name: &str,
513        manifest_raw: &str,
514        wasm_path: &str,
515        wasm_bytes: &[u8],
516    ) -> PluginPin {
517        PluginPin {
518            name: name.into(),
519            version: "0.1.0".into(),
520            source: "path".into(),
521            manifest_sha256: hex_sha256(manifest_raw.as_bytes()),
522            tools: vec![ToolPin::Wasm {
523                identity: format!("plugin.{name}.search"),
524                module: wasm_path.into(),
525                wasm_sha256: hex_sha256(wasm_bytes),
526                capabilities: vec![ResolvedCapability::FsRead {
527                    paths: vec!["/tmp/data".into()],
528                }],
529            }],
530        }
531    }
532
533    fn manifest_raw() -> String {
534        serde_json::json!({
535            "schemaVersion": 1, "name": "my-tools", "version": "0.1.0",
536            "tools": [{"name": "search", "form": "wasm", "module": "wasm/search.wasm", "description": "d"}]
537        })
538        .to_string()
539    }
540
541    #[test]
542    fn registry_round_trips_json() {
543        let mut reg = PluginRegistry::new();
544        reg.insert(pin_with_wasm(
545            "my-tools",
546            &manifest_raw(),
547            "/abs/search.wasm",
548            b"wasm!",
549        ));
550
551        let dir = tempfile::tempdir().unwrap();
552        let path = dir.path().join(REGISTRY_FILE);
553        reg.save(&path).unwrap();
554
555        let raw = std::fs::read_to_string(&path).unwrap();
556        let parsed: serde_json::Value = serde_json::from_str(&raw).unwrap();
557        assert_eq!(parsed["schema_version"], 1);
558        assert_eq!(parsed["plugins"]["my-tools"]["version"], "0.1.0");
559        assert_eq!(parsed["plugins"]["my-tools"]["tools"][0]["form"], "wasm");
560        assert_eq!(
561            parsed["plugins"]["my-tools"]["tools"][0]["capabilities"][0]["paths"][0],
562            "/tmp/data"
563        );
564
565        let back = PluginRegistry::load(&path).unwrap();
566        assert_eq!(back, reg);
567    }
568
569    #[test]
570    fn load_missing_is_fresh_but_corrupt_is_error() {
571        let dir = tempfile::tempdir().unwrap();
572        let path = dir.path().join(REGISTRY_FILE);
573        assert!(PluginRegistry::load(&path).unwrap().is_empty());
574
575        std::fs::write(&path, "{broken").unwrap();
576        assert!(matches!(
577            PluginRegistry::load(&path),
578            Err(RegistryError::Json(_))
579        ));
580    }
581
582    #[test]
583    fn verify_trusted_when_untouched() {
584        let dir = tempfile::tempdir().unwrap();
585        let plugin_dir = dir.path().join("my-tools");
586        std::fs::create_dir_all(plugin_dir.join("wasm")).unwrap();
587        std::fs::write(plugin_dir.join("plugin.json"), manifest_raw()).unwrap();
588        std::fs::write(plugin_dir.join("wasm/search.wasm"), b"wasm!").unwrap();
589
590        let mut reg = PluginRegistry::new();
591        reg.insert(pin_with_wasm(
592            "my-tools",
593            &manifest_raw(),
594            plugin_dir.join("wasm/search.wasm").to_str().unwrap(),
595            b"wasm!",
596        ));
597
598        let report = reg.verify(&plugin_dir);
599        assert!(!report.tampered());
600        assert_eq!(report.package, PackageStatus::Trusted);
601        assert_eq!(
602            report.tools,
603            vec![("plugin.my-tools.search".into(), ToolStatus::Ready)]
604        );
605    }
606
607    #[test]
608    fn verify_tampered_on_manifest_edit() {
609        // Edit the manifest (add capability/add tool) → tampered → disable all + "re-run add to re-review".
610        let dir = tempfile::tempdir().unwrap();
611        let plugin_dir = dir.path().join("my-tools");
612        std::fs::create_dir_all(plugin_dir.join("wasm")).unwrap();
613        std::fs::write(plugin_dir.join("wasm/search.wasm"), b"wasm!").unwrap();
614
615        let tampered = serde_json::json!({
616            "schemaVersion": 1, "name": "my-tools", "version": "0.1.0",
617            "tools": [
618                {"name": "search", "form": "wasm", "module": "wasm/search.wasm", "description": "d",
619                 "capabilities": [{"type": "fs:read", "paths": ["/"]}]},
620                {"name": "evil", "form": "script", "description": "d", "run": ["scripts/x.sh"]}
621            ]
622        })
623        .to_string();
624        std::fs::write(plugin_dir.join("plugin.json"), &tampered).unwrap();
625
626        let mut reg = PluginRegistry::new();
627        reg.insert(pin_with_wasm(
628            "my-tools",
629            &manifest_raw(),
630            plugin_dir.join("wasm/search.wasm").to_str().unwrap(),
631            b"wasm!",
632        ));
633
634        let report = reg.verify(&plugin_dir);
635        assert!(report.tampered());
636        let msg = report.user_message().unwrap();
637        assert!(msg.contains("plugin add"), "{msg}");
638        // All tools are disabled (even the one that was not swapped).
639        assert!(
640            report
641                .tools
642                .iter()
643                .all(|(_, s)| matches!(s, ToolStatus::Broken { .. }))
644        );
645    }
646
647    #[test]
648    fn verify_tampered_on_wasm_swap() {
649        let dir = tempfile::tempdir().unwrap();
650        let plugin_dir = dir.path().join("my-tools");
651        std::fs::create_dir_all(plugin_dir.join("wasm")).unwrap();
652        std::fs::write(plugin_dir.join("plugin.json"), manifest_raw()).unwrap();
653        let wasm_path = plugin_dir.join("wasm/search.wasm");
654        std::fs::write(&wasm_path, b"EVIL!!").unwrap(); // swap the wasm
655
656        let mut reg = PluginRegistry::new();
657        reg.insert(pin_with_wasm(
658            "my-tools",
659            &manifest_raw(),
660            wasm_path.to_str().unwrap(),
661            b"wasm!",
662        ));
663
664        let report = reg.verify(&plugin_dir);
665        assert!(report.tampered());
666        assert!(report.user_message().unwrap().contains("plugin add"));
667    }
668
669    #[test]
670    fn verify_missing_wasm_disables_one_tool_not_package() {
671        // Corruption handling: .wasm missing → that tool is disabled + an error is
672        // reported; the package is not skipped.
673        let dir = tempfile::tempdir().unwrap();
674        let plugin_dir = dir.path().join("my-tools");
675        std::fs::create_dir_all(plugin_dir.join("wasm")).unwrap();
676        std::fs::write(plugin_dir.join("plugin.json"), manifest_raw()).unwrap();
677        // search.wasm does not exist.
678
679        let mut reg = PluginRegistry::new();
680        reg.insert(pin_with_wasm(
681            "my-tools",
682            &manifest_raw(),
683            plugin_dir.join("wasm/search.wasm").to_str().unwrap(),
684            b"wasm!",
685        ));
686
687        let report = reg.verify(&plugin_dir);
688        assert!(!report.tampered(), "missing is corruption, not tampering");
689        assert_eq!(report.package, PackageStatus::Trusted);
690        assert!(matches!(
691            &report.tools[0],
692            (id, ToolStatus::Broken { detail }) if id == "plugin.my-tools.search" && detail.contains("missing")
693        ));
694        assert!(matches!(
695            report.issues[0],
696            VerifyIssue::MissingModule { .. }
697        ));
698    }
699
700    #[test]
701    fn verify_unpinned_plugin_is_tampered() {
702        let dir = tempfile::tempdir().unwrap();
703        let plugin_dir = dir.path().join("stranger");
704        std::fs::create_dir_all(&plugin_dir).unwrap();
705        std::fs::write(plugin_dir.join("plugin.json"), manifest_raw()).unwrap();
706
707        let reg = PluginRegistry::new();
708        let report = reg.verify(&plugin_dir);
709        assert!(report.tampered());
710    }
711
712    #[test]
713    fn remove_clears_registry_entry() {
714        let mut reg = PluginRegistry::new();
715        reg.insert(pin_with_wasm(
716            "my-tools",
717            &manifest_raw(),
718            "/abs/s.wasm",
719            b"w",
720        ));
721        assert_eq!(reg.len(), 1);
722        let removed = reg.remove("my-tools").unwrap();
723        assert_eq!(removed.name, "my-tools");
724        assert!(reg.is_empty());
725        assert!(reg.remove("my-tools").is_none());
726    }
727}