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
188fn decode_plugin_c_string(
189 ptr: NonNull<c_char>,
190 free_string_fn: Option<PluginFreeStringFn>,
191 utf8_error_context: &'static str,
192) -> Result<String> {
193 let raw_ptr = ptr.as_ptr() as *const c_char;
194 let decoded = unsafe { CStr::from_ptr(raw_ptr) }
201 .to_str()
202 .context(utf8_error_context)
203 .map(str::to_owned);
204
205 if let Some(free_fn) = free_string_fn {
206 unsafe { free_fn(raw_ptr) };
209 }
210
211 decoded
212}
213
214impl std::fmt::Debug for NativePlugin {
215 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
216 f.debug_struct("NativePlugin")
217 .field("metadata", &self.metadata)
218 .field("path", &self.path)
219 .finish()
220 }
221}
222
223fn canonicalize_existing_path(path: &Path, label: &str) -> Result<PathBuf> {
224 canonicalize(path).with_context(|| format!("Failed to resolve {label} '{}'", path.display()))
225}
226
227fn get_plugin_symbol<T: Copy>(library: &Library, name: &[u8]) -> Result<T> {
233 let symbol: Symbol<T> = unsafe { library.get(name) }.with_context(|| {
236 format!("Failed to load plugin symbol: {:?}", String::from_utf8_lossy(name.trim_suffix(b"\0")))
237 })?;
238 Ok(*symbol)
239}
240
241fn normalize_trusted_dir(path: PathBuf) -> PathBuf {
242 canonicalize_existing_path(&path, "trusted plugin directory").unwrap_or_else(|_| {
243 if path.is_absolute() {
244 path
245 } else {
246 std::env::current_dir().map(|cwd| cwd.join(&path)).unwrap_or(path)
247 }
248 })
249}
250
251#[cfg(unix)]
252fn warn_if_insecure_trusted_dir(dir: &Path) {
253 if let Ok(metadata) = std::fs::metadata(dir) {
254 let mode = metadata.permissions().mode();
255 if mode & 0o022 != 0 {
256 let perm_octal = format!("{:o}", mode & 0o777);
257 warn!(
258 dir = ?dir,
259 mode = %perm_octal,
260 "trusted plugin directory is writable by group or others; a non-owner user could plant a malicious plugin via symlink or replacement"
261 );
262 }
263 }
264}
265
266#[cfg(not(unix))]
267fn warn_if_insecure_trusted_dir(_dir: &Path) {}
268
269impl NativePlugin {
270 fn new(library: Library, path: PathBuf) -> Result<Self> {
272 let version_fn = get_plugin_symbol::<PluginVersionFn>(&library, b"vtcode_plugin_version\0")?;
274
275 let abi_version = unsafe { version_fn() };
277 if abi_version != PLUGIN_ABI_VERSION {
278 return Err(anyhow!("Plugin ABI version mismatch: expected {PLUGIN_ABI_VERSION}, got {abi_version}"));
279 }
280
281 let free_string_fn = get_plugin_symbol::<PluginFreeStringFn>(&library, b"vtcode_plugin_free_string\0").ok();
283
284 let metadata_fn = get_plugin_symbol::<PluginMetadataFn>(&library, b"vtcode_plugin_metadata\0")?;
286
287 let metadata_ptr = ensure_non_null_c_string_ptr(unsafe { metadata_fn() }, "Plugin metadata function")?;
289 let metadata_json = decode_plugin_c_string(metadata_ptr, free_string_fn, "Plugin metadata is not valid UTF-8")?;
290
291 let metadata: PluginMetadata =
292 serde_json::from_str(&metadata_json).context("Failed to parse plugin metadata JSON")?;
293
294 let execute_fn = get_plugin_symbol::<PluginExecuteFn>(&library, b"vtcode_plugin_execute\0")?;
296
297 Ok(Self {
298 _library: library,
299 metadata: metadata.clone(), path,
301 execute_fn,
302 free_string_fn,
303 execution_lock: Mutex::new(()),
304 thread_safe: metadata.thread_safe, })
306 }
307
308 fn execute(&self, ctx: &PluginContext) -> Result<PluginResult> {
310 let input_json = serde_json::to_string(ctx).context("Failed to serialize plugin context")?;
311 let input_cstr = CString::new(input_json).context("Plugin context contains internal null bytes")?;
312
313 if !self.thread_safe {
317 let _execution_guard = self
318 .execution_lock
319 .lock()
320 .map_err(|_e| anyhow!("native plugin execution lock poisoned"))?;
321
322 self.execute_ffi(input_cstr)
323 } else {
324 self.execute_ffi(input_cstr)
326 }
327 }
328
329 fn execute_ffi(&self, input_cstr: CString) -> Result<PluginResult> {
336 let result_ptr =
341 ensure_non_null_c_string_ptr(unsafe { (self.execute_fn)(input_cstr.as_ptr()) }, "Plugin execute function")?;
342 let result_json = decode_plugin_c_string(result_ptr, self.free_string_fn, "Plugin result is not valid UTF-8")?;
343
344 let result: PluginResult = serde_json::from_str(&result_json).context("Failed to parse plugin result JSON")?;
345
346 Ok(result)
347 }
348}
349
350impl NativePluginTrait for NativePlugin {
351 fn metadata(&self) -> &PluginMetadata {
352 &self.metadata
353 }
354
355 fn path(&self) -> &Path {
356 &self.path
357 }
358
359 fn execute(&self, ctx: &PluginContext) -> Result<PluginResult> {
360 self.execute(ctx)
361 }
362}
363
364pub struct PluginLoader {
371 trusted_dirs: Vec<PathBuf>,
373}
374
375impl PluginLoader {
376 pub fn new() -> Self {
378 Self { trusted_dirs: Vec::new() }
379 }
380
381 pub fn add_trusted_dir(&mut self, path: PathBuf) -> &mut Self {
387 let path = normalize_trusted_dir(path);
388 if !self.trusted_dirs.contains(&path) {
389 warn_if_insecure_trusted_dir(&path);
390 self.trusted_dirs.push(path);
391 }
392 self
393 }
394
395 pub fn trusted_dirs(&self) -> &[PathBuf] {
397 &self.trusted_dirs
398 }
399
400 pub fn load_plugin(&self, plugin_path: &Path) -> Result<Box<dyn NativePluginTrait>> {
409 debug!("Loading native plugin from {:?}", plugin_path);
410
411 let plugin_path = self.ensure_trusted_path(plugin_path, "Plugin path")?;
412
413 let lib_path = self.find_library_file(&plugin_path)?;
415 let lib_path = self.ensure_trusted_path(&lib_path, "Plugin library path")?;
416
417 let library = unsafe { Library::new(&lib_path) }
428 .with_context(|| format!("Failed to load dynamic library at {lib_path:?}"))?;
429
430 let plugin = NativePlugin::new(library, plugin_path.clone())?;
431
432 info!(
433 "Loaded native plugin '{}' v{} from {:?}",
434 plugin.metadata.name, plugin.metadata.version, plugin_path
435 );
436
437 Ok(Box::new(plugin))
438 }
439
440 pub fn discover_plugins(&self) -> Result<Vec<Box<dyn NativePluginTrait>>> {
445 let mut plugins = Vec::new();
446
447 for dir in &self.trusted_dirs {
448 warn_if_insecure_trusted_dir(dir);
449 if !dir.exists() {
450 continue;
451 }
452
453 match self.discover_plugins_in_dir(dir) {
454 Ok(mut dir_plugins) => plugins.append(&mut dir_plugins),
455 Err(e) => {
456 warn!("Failed to discover plugins in {:?}: {}", dir, e);
457 }
458 }
459 }
460
461 Ok(plugins)
462 }
463
464 fn is_in_trusted_dir(&self, path: &Path) -> bool {
466 self.trusted_dirs.iter().any(|dir| path.starts_with(dir))
467 }
468
469 fn ensure_trusted_path(&self, path: &Path, label: &str) -> Result<PathBuf> {
470 let path = canonicalize_existing_path(path, label)?;
471 if self.is_in_trusted_dir(&path) {
472 Ok(path)
473 } else {
474 Err(anyhow!("{label} {path:?} is not in a trusted directory"))
475 }
476 }
477
478 fn find_library_file(&self, plugin_dir: &Path) -> Result<PathBuf> {
480 if !plugin_dir.is_dir() {
481 return Err(anyhow!("Plugin path is not a directory"));
482 }
483
484 let metadata_path = plugin_dir.join("plugin.json");
486 if !metadata_path.exists() {
487 return Err(anyhow!("No plugin.json found in {plugin_dir:?}"));
488 }
489
490 let lib_name = self.get_library_name_from_metadata(&metadata_path)?;
492
493 let lib_path = plugin_dir.join(&lib_name);
494 if lib_path.exists() {
495 return Ok(lib_path);
496 }
497
498 let alternatives = self.get_alternative_library_names(&lib_name);
500 for alt in alternatives {
501 let alt_path = plugin_dir.join(alt);
502 if alt_path.exists() {
503 return Ok(alt_path);
504 }
505 }
506
507 Err(anyhow!("No dynamic library found in {plugin_dir:?}. Expected one of: {lib_name}, or alternatives"))
508 }
509
510 fn get_library_name_from_metadata(&self, metadata_path: &Path) -> Result<String> {
512 let metadata_content = std::fs::read_to_string(metadata_path).context("Failed to read plugin metadata")?;
513 let metadata: serde_json::Value =
514 serde_json::from_str(&metadata_content).context("Invalid plugin metadata JSON")?;
515
516 let name = metadata["name"]
517 .as_str()
518 .ok_or_else(|| anyhow!("Plugin metadata missing 'name' field"))?;
519
520 Ok(self.library_filename(name))
521 }
522
523 fn get_alternative_library_names(&self, base_name: &str) -> Vec<String> {
525 let mut alternatives = Vec::new();
526
527 if let Some(stripped) = base_name.strip_prefix("lib") {
529 alternatives.push(stripped.to_string());
530 } else {
531 alternatives.push(format!("lib{base_name}"));
532 }
533
534 let base = base_name.trim_prefix("lib");
536 #[cfg(target_os = "macos")]
537 {
538 alternatives.push(format!("{base}.dylib"));
539 alternatives.push(format!("lib{base}.dylib"));
540 }
541 #[cfg(target_os = "linux")]
542 {
543 alternatives.push(format!("{}.so", base));
544 alternatives.push(format!("lib{}.so", base));
545 }
546 #[cfg(target_os = "windows")]
547 {
548 alternatives.push(format!("{}.dll", base));
549 alternatives.push(format!("lib{}.dll", base));
550 }
551
552 alternatives
553 }
554
555 fn discover_plugins_in_dir(&self, dir: &Path) -> Result<Vec<Box<dyn NativePluginTrait>>> {
557 let mut plugins = Vec::new();
558
559 for entry in std::fs::read_dir(dir)? {
560 let entry = entry?;
561 let path = entry.path();
562
563 if vtcode_commons::walk::entry_is_dir(&entry) && path.join("plugin.json").exists() {
565 match self.load_plugin(&path) {
566 Ok(plugin) => plugins.push(plugin),
567 Err(e) => {
568 warn!("Failed to load plugin at {:?}: {}", path, e);
569 }
570 }
571 }
572 }
573
574 Ok(plugins)
575 }
576
577 pub fn library_filename(&self, name: &str) -> String {
579 #[cfg(target_os = "macos")]
580 {
581 format!("lib{name}.dylib")
582 }
583 #[cfg(target_os = "linux")]
584 {
585 format!("lib{}.so", name)
586 }
587 #[cfg(target_os = "windows")]
588 {
589 format!("{}.dll", name)
590 }
591 #[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))]
592 {
593 format!("lib{}", name)
594 }
595 }
596}
597
598impl Default for PluginLoader {
599 fn default() -> Self {
600 Self::new()
601 }
602}
603
604pub fn validate_plugin_structure(plugin_dir: &Path) -> Result<Vec<String>> {
606 let mut errors = Vec::new();
607
608 if !plugin_dir.join("plugin.json").exists() {
610 errors.push("Missing plugin.json".to_string());
611 }
612
613 let has_lib = std::fs::read_dir(plugin_dir)
615 .map(|entries| {
616 entries.filter_map(|e| e.ok()).any(|entry| {
617 let path = entry.path();
618 let ext = path.extension().and_then(|e| e.to_str());
619 matches!(ext, Some("dylib") | Some("so") | Some("dll"))
620 })
621 })
622 .unwrap_or(false);
623
624 if !has_lib {
625 errors.push("No dynamic library found (.dylib, .so, or .dll)".to_string());
626 }
627
628 if let Ok(content) = std::fs::read_to_string(plugin_dir.join("plugin.json")) {
630 if let Ok(metadata) = serde_json::from_str::<serde_json::Value>(&content) {
631 if metadata["name"].as_str().is_none() {
632 errors.push("plugin.json missing required 'name' field".to_string());
633 }
634 if metadata["description"].as_str().is_none() {
635 errors.push("plugin.json missing required 'description' field".to_string());
636 }
637 if metadata["version"].as_str().is_none() {
638 errors.push("plugin.json missing required 'version' field".to_string());
639 }
640 } else {
641 errors.push("Invalid JSON in plugin.json".to_string());
642 }
643 }
644
645 Ok(errors)
646}
647
648#[cfg(test)]
649mod tests;