1pub mod host;
21pub mod loader;
22pub mod registry;
23
24use anyhow::Result;
25use rma_common::{Finding, Language};
26use serde::{Deserialize, Serialize};
27use std::path::Path;
28use thiserror::Error;
29use tracing::{debug, info, warn};
30
31#[derive(Error, Debug)]
33pub enum PluginError {
34 #[error("Failed to load plugin: {0}")]
35 LoadError(String),
36
37 #[error("Plugin execution failed: {0}")]
38 ExecutionError(String),
39
40 #[error("Invalid plugin interface: {0}")]
41 InterfaceError(String),
42
43 #[error("Plugin not found: {0}")]
44 NotFound(String),
45
46 #[error("WASM error: {0}")]
47 WasmError(#[from] anyhow::Error),
48}
49
50#[derive(Debug, Clone, Serialize, Deserialize)]
52pub struct PluginMetadata {
53 pub name: String,
54 pub version: String,
55 pub description: String,
56 pub author: Option<String>,
57 pub languages: Vec<Language>,
58 pub rules: Vec<String>,
59}
60
61pub struct Plugin {
63 pub metadata: PluginMetadata,
64 instance: wasmtime::Instance,
65 store: wasmtime::Store<host::HostState>,
66}
67
68impl Plugin {
69 pub fn analyze(&mut self, source: &str, language: Language) -> Result<Vec<Finding>> {
71 host::call_analyze(&mut self.store, &self.instance, source, language)
72 }
73}
74
75#[derive(Debug, Clone, Serialize, Deserialize)]
77pub struct PluginInput {
78 pub source: String,
79 pub file_path: String,
80 pub language: String,
81}
82
83#[derive(Debug, Clone, Serialize, Deserialize)]
85pub struct PluginOutput {
86 pub findings: Vec<PluginFinding>,
87}
88
89#[derive(Debug, Clone, Serialize, Deserialize)]
91pub struct PluginFinding {
92 pub rule_id: String,
93 pub message: String,
94 pub severity: String,
95 pub start_line: usize,
96 pub start_column: usize,
97 pub end_line: usize,
98 pub end_column: usize,
99 pub snippet: Option<String>,
100 pub suggestion: Option<String>,
101}
102
103impl From<PluginFinding> for Finding {
104 fn from(pf: PluginFinding) -> Self {
105 let mut finding = Finding {
106 id: format!(
107 "plugin-{}-{}-{}",
108 pf.rule_id, pf.start_line, pf.start_column
109 ),
110 rule_id: pf.rule_id,
111 message: pf.message,
112 severity: match pf.severity.to_lowercase().as_str() {
113 "critical" => rma_common::Severity::Critical,
114 "error" => rma_common::Severity::Error,
115 "warning" => rma_common::Severity::Warning,
116 _ => rma_common::Severity::Info,
117 },
118 location: rma_common::SourceLocation::new(
119 std::path::PathBuf::new(),
120 pf.start_line,
121 pf.start_column,
122 pf.end_line,
123 pf.end_column,
124 ),
125 language: Language::Unknown,
126 snippet: pf.snippet,
127 suggestion: pf.suggestion,
128 fix: None,
129 confidence: rma_common::Confidence::Medium,
130 category: rma_common::FindingCategory::Quality,
131 subcategory: None,
132 technology: None,
133 impact: None,
134 likelihood: None,
135 source: rma_common::FindingSource::Plugin,
136 fingerprint: None,
137 properties: None,
138 occurrence_count: None,
139 additional_locations: None,
140 };
141 finding.compute_fingerprint();
142 finding
143 }
144}
145
146pub struct PluginManager {
148 registry: registry::PluginRegistry,
149 engine: wasmtime::Engine,
150}
151
152impl PluginManager {
153 pub fn new() -> Result<Self> {
155 let mut config = wasmtime::Config::new();
156 config.wasm_component_model(true);
157 config.async_support(false);
158
159 let engine = wasmtime::Engine::new(&config)?;
160
161 Ok(Self {
162 registry: registry::PluginRegistry::new(),
163 engine,
164 })
165 }
166
167 pub fn load_plugin(&mut self, path: &Path) -> Result<String, PluginError> {
169 info!("Loading plugin from {:?}", path);
170
171 let wasm_bytes = std::fs::read(path)
172 .map_err(|e| PluginError::LoadError(format!("Failed to read file: {}", e)))?;
173
174 let module = wasmtime::Module::new(&self.engine, &wasm_bytes)
175 .map_err(|e| PluginError::LoadError(format!("Failed to compile WASM: {}", e)))?;
176
177 let mut store = wasmtime::Store::new(&self.engine, host::HostState::new());
178
179 let linker = host::create_linker(&self.engine)?;
181
182 let instance = linker
183 .instantiate(&mut store, &module)
184 .map_err(|e| PluginError::LoadError(format!("Failed to instantiate: {}", e)))?;
185
186 let metadata = host::get_plugin_metadata(&mut store, &instance)?;
188 let plugin_name = metadata.name.clone();
189
190 let plugin = Plugin {
191 metadata,
192 instance,
193 store,
194 };
195
196 self.registry.register(plugin)?;
197
198 Ok(plugin_name)
199 }
200
201 pub fn load_plugins_from_dir(&mut self, dir: &Path) -> Result<Vec<String>> {
203 let mut loaded = Vec::new();
204
205 if !dir.exists() {
206 debug!("Plugin directory {:?} does not exist", dir);
207 return Ok(loaded);
208 }
209
210 for entry in std::fs::read_dir(dir)? {
211 let entry = entry?;
212 let path = entry.path();
213
214 if path.extension().map(|e| e == "wasm").unwrap_or(false) {
215 match self.load_plugin(&path) {
216 Ok(name) => {
217 info!("Loaded plugin: {}", name);
218 loaded.push(name);
219 }
220 Err(e) => {
221 warn!("Failed to load plugin {:?}: {}", path, e);
222 }
223 }
224 }
225 }
226
227 Ok(loaded)
228 }
229
230 pub fn analyze(&mut self, source: &str, language: Language) -> Result<Vec<Finding>> {
232 self.registry.analyze_all(source, language)
233 }
234
235 pub fn list_plugins(&self) -> Vec<&PluginMetadata> {
237 self.registry.list()
238 }
239
240 pub fn unload_plugin(&mut self, name: &str) -> Result<(), PluginError> {
242 self.registry.unregister(name)
243 }
244}
245
246impl Default for PluginManager {
247 fn default() -> Self {
248 Self::new().expect("Failed to create plugin manager")
249 }
250}
251
252#[cfg(test)]
253mod tests {
254 use super::*;
255
256 #[test]
257 fn test_plugin_manager_creation() {
258 let manager = PluginManager::new();
259 assert!(manager.is_ok());
260 }
261
262 #[test]
263 fn test_plugin_finding_conversion() {
264 let pf = PluginFinding {
265 rule_id: "test-rule".to_string(),
266 message: "Test message".to_string(),
267 severity: "warning".to_string(),
268 start_line: 10,
269 start_column: 5,
270 end_line: 10,
271 end_column: 15,
272 snippet: Some("test code".to_string()),
273 suggestion: None,
274 };
275
276 let finding: Finding = pf.into();
277 assert_eq!(finding.rule_id, "test-rule");
278 assert_eq!(finding.severity, rma_common::Severity::Warning);
279 }
280}