1use std::collections::BTreeMap;
27use std::path::{Path, PathBuf};
28
29use serde::{Deserialize, Serialize};
30
31use super::manifest::ResolvedCapability;
32
33pub const REGISTRY_FILE: &str = "registry.json";
35
36pub const REGISTRY_SCHEMA_VERSION: u32 = 1;
38
39#[derive(Debug)]
41pub enum RegistryError {
42 Io(std::io::Error),
44 Json(String),
46 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
64#[serde(tag = "form", rename_all = "lowercase")]
65pub enum ToolPin {
66 Wasm {
68 identity: String,
70 module: String,
72 wasm_sha256: String,
74 #[serde(default, skip_serializing_if = "Vec::is_empty")]
76 capabilities: Vec<ResolvedCapability>,
77 },
78 Script {
80 identity: String,
82 run: Vec<String>,
84 },
85 Mcp {
87 label: String,
89 #[serde(default, skip_serializing_if = "Option::is_none")]
91 command: Option<Vec<String>>,
92 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
94 env: BTreeMap<String, String>,
95 #[serde(default, skip_serializing_if = "Option::is_none")]
97 url: Option<String>,
98 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
100 headers: BTreeMap<String, String>,
101 },
102}
103
104impl ToolPin {
105 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 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
125pub struct PluginPin {
126 pub name: String,
128 pub version: String,
130 pub source: String,
132 pub manifest_sha256: String,
134 pub tools: Vec<ToolPin>,
136}
137
138#[derive(Debug, Clone, PartialEq, Eq)]
140pub enum PackageStatus {
141 Trusted,
143 Tampered { reason: String },
146}
147
148#[derive(Debug, Clone, PartialEq, Eq)]
150pub enum ToolStatus {
151 Ready,
153 Broken { detail: String },
155}
156
157#[derive(Debug, Clone, PartialEq, Eq)]
159pub enum VerifyIssue {
160 ManifestHashMismatch,
162 ToolSetChanged { detail: String },
164 WasmHashMismatch { identity: String },
166 MissingModule { identity: String, path: String },
168}
169
170#[derive(Debug, Clone, PartialEq, Eq)]
172pub struct VerifyReport {
173 pub plugin: String,
175 pub package: PackageStatus,
177 pub tools: Vec<(String, ToolStatus)>,
179 pub issues: Vec<VerifyIssue>,
181}
182
183impl VerifyReport {
184 pub fn tampered(&self) -> bool {
186 self.package != PackageStatus::Trusted
187 }
188
189 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
203pub struct PluginRegistry {
204 pub schema_version: u32,
206 pub plugins: BTreeMap<String, PluginPin>,
208}
209
210impl Default for PluginRegistry {
211 fn default() -> Self {
212 Self::new()
213 }
214}
215
216impl PluginRegistry {
217 pub fn new() -> Self {
219 Self {
220 schema_version: REGISTRY_SCHEMA_VERSION,
221 plugins: BTreeMap::new(),
222 }
223 }
224
225 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 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 pub fn path_in(plugins_root: &Path) -> PathBuf {
257 plugins_root.join(REGISTRY_FILE)
258 }
259
260 pub fn get(&self, name: &str) -> Option<&PluginPin> {
262 self.plugins.get(name)
263 }
264
265 pub fn insert(&mut self, pin: PluginPin) {
267 self.plugins.insert(pin.name.clone(), pin);
268 }
269
270 pub fn remove(&mut self, name: &str) -> Option<PluginPin> {
272 self.plugins.remove(name)
273 }
274
275 pub fn len(&self) -> usize {
277 self.plugins.len()
278 }
279
280 pub fn is_empty(&self) -> bool {
282 self.plugins.is_empty()
283 }
284
285 pub fn verify(&self, plugin_dir: &Path) -> VerifyReport {
293 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 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 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 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.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 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 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 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 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
500pub 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 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 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(); 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 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 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}