vtcode_skills/native_plugin/
mod.rs1#![allow(
2 unsafe_code,
3 reason = "Intentional compatibility, platform, or test-only suppression."
4)]
5
6use anyhow::{Context, Result, anyhow};
59use hashbrown::HashMap;
60use libloading::{Library, Symbol};
61use serde::{Deserialize, Serialize};
62use std::ffi::{CStr, CString};
63#[cfg(unix)]
64use std::os::unix::fs::PermissionsExt;
65use std::path::{Path, PathBuf};
66use std::ptr::NonNull;
67use std::sync::Mutex;
68use tracing::{debug, info, warn};
69use vtcode_commons::canonicalize;
70
71pub const PLUGIN_ABI_VERSION: u32 = 1;
74
75use std::os::raw::c_char;
76
77type PluginVersionFn = unsafe extern "C" fn() -> u32;
93type PluginMetadataFn = unsafe extern "C" fn() -> *const c_char;
94type PluginExecuteFn = unsafe extern "C" fn(*const c_char) -> *const c_char;
95type PluginFreeStringFn = unsafe extern "C" fn(*const c_char);
96
97#[derive(Debug, Clone, Serialize, Deserialize)]
99pub struct PluginContext {
100 input: HashMap<String, serde_json::Value>,
102 workspace_root: Option<String>,
104 config: HashMap<String, serde_json::Value>,
106}
107
108#[derive(Debug, Clone, Serialize, Deserialize)]
110pub struct PluginResult {
111 success: bool,
113 output: HashMap<String, serde_json::Value>,
115 error: Option<String>,
117 files: Vec<String>,
119}
120
121#[derive(Debug, Clone, Serialize, Deserialize)]
123pub struct PluginMetadata {
124 pub name: String,
126 pub description: String,
128 version: String,
130 author: Option<String>,
132 abi_version: u32,
134 when_to_use: Option<String>,
136 when_not_to_use: Option<String>,
138 allowed_tools: Option<Vec<String>>,
140 #[serde(default)]
143 thread_safe: bool,
144}
145
146pub trait NativePluginTrait: Send + Sync + std::fmt::Debug {
148 fn metadata(&self) -> &PluginMetadata;
150
151 fn path(&self) -> &Path;
153
154 fn execute(&self, ctx: &PluginContext) -> Result<PluginResult>;
156}
157
158pub struct NativePlugin {
160 _library: Library,
170 metadata: PluginMetadata,
172 path: PathBuf,
174 execute_fn: PluginExecuteFn,
176 free_string_fn: Option<PluginFreeStringFn>,
178 execution_lock: Mutex<()>,
180 thread_safe: bool,
182}
183
184fn ensure_non_null_c_string_ptr(ptr: *const c_char, context: &'static str) -> Result<NonNull<c_char>> {
185 NonNull::new(ptr.cast_mut()).ok_or_else(|| anyhow!("{context} returned null pointer"))
186}
187
188struct PluginOwnedCString {
200 ptr: NonNull<c_char>,
201 free: Option<PluginFreeStringFn>,
202}
203
204impl PluginOwnedCString {
205 fn new(ptr: NonNull<c_char>, free: Option<PluginFreeStringFn>) -> Self {
206 Self { ptr, free }
207 }
208
209 fn decode(&self, utf8_error_context: &'static str) -> Result<String> {
214 let raw_ptr = self.ptr.as_ptr().cast_const();
215 unsafe { CStr::from_ptr(raw_ptr) }
222 .to_str()
223 .context(utf8_error_context)
224 .map(str::to_owned)
225 }
226}
227
228impl Drop for PluginOwnedCString {
229 fn drop(&mut self) {
230 if let Some(free_fn) = self.free {
231 unsafe { free_fn(self.ptr.as_ptr().cast_const()) };
234 }
235 }
236}
237
238fn decode_plugin_c_string(
241 ptr: NonNull<c_char>,
242 free_string_fn: Option<PluginFreeStringFn>,
243 utf8_error_context: &'static str,
244) -> Result<String> {
245 PluginOwnedCString::new(ptr, free_string_fn).decode(utf8_error_context)
246}
247
248impl std::fmt::Debug for NativePlugin {
249 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
250 f.debug_struct("NativePlugin")
251 .field("metadata", &self.metadata)
252 .field("path", &self.path)
253 .finish()
254 }
255}
256
257fn canonicalize_existing_path(path: &Path, label: &str) -> Result<PathBuf> {
258 canonicalize(path).with_context(|| format!("Failed to resolve {label} '{}'", path.display()))
259}
260
261fn get_plugin_symbol<T: Copy>(library: &Library, name: &[u8]) -> Result<T> {
267 let symbol: Symbol<T> = unsafe { library.get(name) }.with_context(|| {
270 format!("Failed to load plugin symbol: {:?}", String::from_utf8_lossy(name.trim_suffix(b"\0")))
271 })?;
272 Ok(*symbol)
273}
274
275fn normalize_trusted_dir(path: PathBuf) -> PathBuf {
276 canonicalize_existing_path(&path, "trusted plugin directory").unwrap_or_else(|_| {
277 if path.is_absolute() {
278 path
279 } else {
280 std::env::current_dir().map(|cwd| cwd.join(&path)).unwrap_or(path)
281 }
282 })
283}
284
285#[cfg(unix)]
286fn warn_if_insecure_trusted_dir(dir: &Path) {
287 if let Ok(metadata) = std::fs::metadata(dir) {
288 let mode = metadata.permissions().mode();
289 if mode & 0o022 != 0 {
290 let perm_octal = format!("{:o}", mode & 0o777);
291 warn!(
292 dir = ?dir,
293 mode = %perm_octal,
294 "trusted plugin directory is writable by group or others; a non-owner user could plant a malicious plugin via symlink or replacement"
295 );
296 }
297 }
298}
299
300#[cfg(not(unix))]
301fn warn_if_insecure_trusted_dir(_dir: &Path) {}
302
303impl NativePlugin {
304 fn new(library: Library, path: PathBuf) -> Result<Self> {
306 let version_fn = get_plugin_symbol::<PluginVersionFn>(&library, b"vtcode_plugin_version\0")?;
308
309 let abi_version = unsafe { version_fn() };
311 if abi_version != PLUGIN_ABI_VERSION {
312 return Err(anyhow!("Plugin ABI version mismatch: expected {PLUGIN_ABI_VERSION}, got {abi_version}"));
313 }
314
315 let free_string_fn = get_plugin_symbol::<PluginFreeStringFn>(&library, b"vtcode_plugin_free_string\0").ok();
317
318 let metadata_fn = get_plugin_symbol::<PluginMetadataFn>(&library, b"vtcode_plugin_metadata\0")?;
320
321 let metadata_ptr = ensure_non_null_c_string_ptr(unsafe { metadata_fn() }, "Plugin metadata function")?;
323 let metadata_json = decode_plugin_c_string(metadata_ptr, free_string_fn, "Plugin metadata is not valid UTF-8")?;
324
325 let metadata: PluginMetadata =
326 serde_json::from_str(&metadata_json).context("Failed to parse plugin metadata JSON")?;
327
328 let execute_fn = get_plugin_symbol::<PluginExecuteFn>(&library, b"vtcode_plugin_execute\0")?;
330
331 Ok(Self {
332 _library: library,
333 metadata: metadata.clone(), path,
335 execute_fn,
336 free_string_fn,
337 execution_lock: Mutex::new(()),
338 thread_safe: metadata.thread_safe, })
340 }
341
342 fn execute(&self, ctx: &PluginContext) -> Result<PluginResult> {
344 let input_json = serde_json::to_string(ctx).context("Failed to serialize plugin context")?;
345 let input_cstr = CString::new(input_json).context("Plugin context contains internal null bytes")?;
346
347 if !self.thread_safe {
351 let _execution_guard = self
352 .execution_lock
353 .lock()
354 .map_err(|_e| anyhow!("native plugin execution lock poisoned"))?;
355
356 self.execute_ffi(input_cstr)
357 } else {
358 self.execute_ffi(input_cstr)
360 }
361 }
362
363 fn execute_ffi(&self, input_cstr: CString) -> Result<PluginResult> {
370 let result_ptr =
375 ensure_non_null_c_string_ptr(unsafe { (self.execute_fn)(input_cstr.as_ptr()) }, "Plugin execute function")?;
376 let result_json = decode_plugin_c_string(result_ptr, self.free_string_fn, "Plugin result is not valid UTF-8")?;
377
378 let result: PluginResult = serde_json::from_str(&result_json).context("Failed to parse plugin result JSON")?;
379
380 Ok(result)
381 }
382}
383
384impl NativePluginTrait for NativePlugin {
385 fn metadata(&self) -> &PluginMetadata {
386 &self.metadata
387 }
388
389 fn path(&self) -> &Path {
390 &self.path
391 }
392
393 fn execute(&self, ctx: &PluginContext) -> Result<PluginResult> {
394 self.execute(ctx)
395 }
396}
397
398pub struct PluginLoader {
405 trusted_dirs: Vec<PathBuf>,
407}
408
409impl PluginLoader {
410 pub fn new() -> Self {
412 Self { trusted_dirs: Vec::new() }
413 }
414
415 pub fn add_trusted_dir(&mut self, path: PathBuf) -> &mut Self {
421 let path = normalize_trusted_dir(path);
422 if !self.trusted_dirs.contains(&path) {
423 warn_if_insecure_trusted_dir(&path);
424 self.trusted_dirs.push(path);
425 }
426 self
427 }
428
429 pub fn trusted_dirs(&self) -> &[PathBuf] {
431 &self.trusted_dirs
432 }
433
434 pub fn load_plugin(&self, plugin_path: &Path) -> Result<Box<dyn NativePluginTrait>> {
443 debug!("Loading native plugin from {:?}", plugin_path);
444
445 let plugin_path = self.ensure_trusted_path(plugin_path, "Plugin path")?;
446
447 let lib_path = self.find_library_file(&plugin_path)?;
449 let lib_path = self.ensure_trusted_path(&lib_path, "Plugin library path")?;
450
451 let library = unsafe { Library::new(&lib_path) }
462 .with_context(|| format!("Failed to load dynamic library at {lib_path:?}"))?;
463
464 let plugin = NativePlugin::new(library, plugin_path.clone())?;
465
466 info!(
467 "Loaded native plugin '{}' v{} from {:?}",
468 plugin.metadata.name, plugin.metadata.version, plugin_path
469 );
470
471 Ok(Box::new(plugin))
472 }
473
474 pub fn discover_plugins(&self) -> Result<Vec<Box<dyn NativePluginTrait>>> {
479 let mut plugins = Vec::new();
480
481 for dir in &self.trusted_dirs {
482 warn_if_insecure_trusted_dir(dir);
483 if !dir.exists() {
484 continue;
485 }
486
487 match self.discover_plugins_in_dir(dir) {
488 Ok(mut dir_plugins) => plugins.append(&mut dir_plugins),
489 Err(e) => {
490 warn!("Failed to discover plugins in {:?}: {}", dir, e);
491 }
492 }
493 }
494
495 Ok(plugins)
496 }
497
498 fn is_in_trusted_dir(&self, path: &Path) -> bool {
500 self.trusted_dirs.iter().any(|dir| path.starts_with(dir))
501 }
502
503 fn ensure_trusted_path(&self, path: &Path, label: &str) -> Result<PathBuf> {
504 let path = canonicalize_existing_path(path, label)?;
505 if self.is_in_trusted_dir(&path) {
506 Ok(path)
507 } else {
508 Err(anyhow!("{label} {path:?} is not in a trusted directory"))
509 }
510 }
511
512 fn find_library_file(&self, plugin_dir: &Path) -> Result<PathBuf> {
514 if !plugin_dir.is_dir() {
515 return Err(anyhow!("Plugin path is not a directory"));
516 }
517
518 let metadata_path = plugin_dir.join("plugin.json");
520 if !metadata_path.exists() {
521 return Err(anyhow!("No plugin.json found in {plugin_dir:?}"));
522 }
523
524 let lib_name = self.get_library_name_from_metadata(&metadata_path)?;
526
527 let lib_path = plugin_dir.join(&lib_name);
528 if lib_path.exists() {
529 return Ok(lib_path);
530 }
531
532 let alternatives = self.get_alternative_library_names(&lib_name);
534 for alt in alternatives {
535 let alt_path = plugin_dir.join(alt);
536 if alt_path.exists() {
537 return Ok(alt_path);
538 }
539 }
540
541 Err(anyhow!("No dynamic library found in {plugin_dir:?}. Expected one of: {lib_name}, or alternatives"))
542 }
543
544 fn get_library_name_from_metadata(&self, metadata_path: &Path) -> Result<String> {
546 let metadata_content = std::fs::read_to_string(metadata_path).context("Failed to read plugin metadata")?;
547 let metadata: serde_json::Value =
548 serde_json::from_str(&metadata_content).context("Invalid plugin metadata JSON")?;
549
550 let name = metadata["name"]
551 .as_str()
552 .ok_or_else(|| anyhow!("Plugin metadata missing 'name' field"))?;
553
554 Ok(self.library_filename(name))
555 }
556
557 fn get_alternative_library_names(&self, base_name: &str) -> Vec<String> {
559 let mut alternatives = Vec::new();
560
561 if let Some(stripped) = base_name.strip_prefix("lib") {
563 alternatives.push(stripped.to_string());
564 } else {
565 alternatives.push(format!("lib{base_name}"));
566 }
567
568 let base = base_name.trim_prefix("lib");
570 #[cfg(target_os = "macos")]
571 {
572 alternatives.push(format!("{base}.dylib"));
573 alternatives.push(format!("lib{base}.dylib"));
574 }
575 #[cfg(target_os = "linux")]
576 {
577 alternatives.push(format!("{}.so", base));
578 alternatives.push(format!("lib{}.so", base));
579 }
580 #[cfg(target_os = "windows")]
581 {
582 alternatives.push(format!("{}.dll", base));
583 alternatives.push(format!("lib{}.dll", base));
584 }
585
586 alternatives
587 }
588
589 fn discover_plugins_in_dir(&self, dir: &Path) -> Result<Vec<Box<dyn NativePluginTrait>>> {
591 let mut plugins = Vec::new();
592
593 for entry in std::fs::read_dir(dir)? {
594 let entry = entry?;
595 let path = entry.path();
596
597 if vtcode_commons::walk::entry_is_dir(&entry) && path.join("plugin.json").exists() {
599 match self.load_plugin(&path) {
600 Ok(plugin) => plugins.push(plugin),
601 Err(e) => {
602 warn!("Failed to load plugin at {:?}: {}", path, e);
603 }
604 }
605 }
606 }
607
608 Ok(plugins)
609 }
610
611 pub fn library_filename(&self, name: &str) -> String {
613 #[cfg(target_os = "macos")]
614 {
615 format!("lib{name}.dylib")
616 }
617 #[cfg(target_os = "linux")]
618 {
619 format!("lib{}.so", name)
620 }
621 #[cfg(target_os = "windows")]
622 {
623 format!("{}.dll", name)
624 }
625 #[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))]
626 {
627 format!("lib{}", name)
628 }
629 }
630}
631
632impl Default for PluginLoader {
633 fn default() -> Self {
634 Self::new()
635 }
636}
637
638pub fn validate_plugin_structure(plugin_dir: &Path) -> Result<Vec<String>> {
640 let mut errors = Vec::new();
641
642 if !plugin_dir.join("plugin.json").exists() {
644 errors.push("Missing plugin.json".to_string());
645 }
646
647 let has_lib = std::fs::read_dir(plugin_dir)
649 .map(|entries| {
650 entries.filter_map(|e| e.ok()).any(|entry| {
651 let path = entry.path();
652 let ext = path.extension().and_then(|e| e.to_str());
653 matches!(ext, Some("dylib") | Some("so") | Some("dll"))
654 })
655 })
656 .unwrap_or(false);
657
658 if !has_lib {
659 errors.push("No dynamic library found (.dylib, .so, or .dll)".to_string());
660 }
661
662 if let Ok(content) = std::fs::read_to_string(plugin_dir.join("plugin.json")) {
664 if let Ok(metadata) = serde_json::from_str::<serde_json::Value>(&content) {
665 if metadata["name"].as_str().is_none() {
666 errors.push("plugin.json missing required 'name' field".to_string());
667 }
668 if metadata["description"].as_str().is_none() {
669 errors.push("plugin.json missing required 'description' field".to_string());
670 }
671 if metadata["version"].as_str().is_none() {
672 errors.push("plugin.json missing required 'version' field".to_string());
673 }
674 } else {
675 errors.push("Invalid JSON in plugin.json".to_string());
676 }
677 }
678
679 Ok(errors)
680}
681
682#[cfg(test)]
683mod tests;