Skip to main content

eov_plugin_api/
manifest.rs

1//! Plugin manifest parsing and validation.
2
3use crate::{IconDescriptor, PluginError, PluginResult};
4use serde::{Deserialize, Serialize};
5use std::path::{Path, PathBuf};
6
7/// A toolbar button declared in the manifest.
8#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
9pub struct ManifestToolbarButton {
10    pub button_id: String,
11    pub tooltip: String,
12    pub action_id: String,
13    /// Inline SVG icon data. If omitted, the plugin's top-level icon is used.
14    pub icon_svg: Option<String>,
15}
16
17#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
18pub struct PluginEnvironment {
19    /// Host application version constraint.
20    pub version: String,
21}
22
23/// The parsed contents of a `plugin.toml` manifest.
24#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
25pub struct PluginManifest {
26    /// Unique, stable identifier for the plugin (e.g. `"example_plugin"`).
27    pub id: String,
28    /// Human-readable name shown in the UI.
29    pub name: String,
30    /// Semantic version string.
31    pub version: String,
32    /// Optional human-readable description for management interfaces.
33    #[serde(default)]
34    pub description: Option<String>,
35    /// Optional source repository for management and provenance display.
36    #[serde(default)]
37    pub repository: Option<String>,
38    /// Relative path to the `.slint` UI file (from the plugin root).
39    /// Optional — plugins that are pure viewport filters may omit this.
40    #[serde(default)]
41    pub entry_ui: Option<String>,
42    /// Name of the exported Slint component inside `entry_ui`.
43    /// Optional — plugins that are pure viewport filters may omit this.
44    #[serde(default)]
45    pub entry_component: Option<String>,
46    /// Optional icon for the toolbar button.
47    pub icon: Option<IconDescriptor>,
48    /// Toolbar buttons declared in the manifest.
49    #[serde(default)]
50    pub toolbar_buttons: Vec<ManifestToolbarButton>,
51    /// Host application requirements for the plugin.
52    pub environment: PluginEnvironment,
53}
54
55/// Name of the manifest file inside each plugin directory.
56pub const MANIFEST_FILENAME: &str = "plugin.toml";
57
58impl PluginManifest {
59    /// Parse a manifest from a TOML string, validating required fields.
60    pub fn from_toml(toml_str: &str, plugin_id_hint: &str) -> PluginResult<Self> {
61        let manifest: Self = toml::from_str(toml_str).map_err(|e| PluginError::Manifest {
62            plugin_id: plugin_id_hint.to_string(),
63            message: format!("TOML parse error: {e}"),
64        })?;
65        manifest.validate()?;
66        Ok(manifest)
67    }
68
69    /// Load a manifest from a file path.
70    pub fn from_file(path: &Path) -> PluginResult<Self> {
71        let dir_name = path
72            .parent()
73            .and_then(|p| p.file_name())
74            .and_then(|n| n.to_str())
75            .unwrap_or("<unknown>");
76        let contents = std::fs::read_to_string(path).map_err(|e| PluginError::Manifest {
77            plugin_id: dir_name.to_string(),
78            message: format!("failed to read {}: {e}", path.display()),
79        })?;
80        Self::from_toml(&contents, dir_name)
81    }
82
83    /// Validate semantic constraints beyond TOML structure.
84    fn validate(&self) -> PluginResult<()> {
85        if self.id.is_empty() {
86            return Err(PluginError::Manifest {
87                plugin_id: self.id.clone(),
88                message: "'id' must not be empty".into(),
89            });
90        }
91        if self.name.is_empty() {
92            return Err(PluginError::Manifest {
93                plugin_id: self.id.clone(),
94                message: "'name' must not be empty".into(),
95            });
96        }
97        if self.version.is_empty() {
98            return Err(PluginError::Manifest {
99                plugin_id: self.id.clone(),
100                message: "'version' must not be empty".into(),
101            });
102        }
103        if let Some(ref entry_ui) = self.entry_ui {
104            if entry_ui.is_empty() {
105                return Err(PluginError::Manifest {
106                    plugin_id: self.id.clone(),
107                    message: "'entry_ui' must not be empty when specified".into(),
108                });
109            }
110            // entry_ui must be a relative path
111            if Path::new(entry_ui).is_absolute() {
112                return Err(PluginError::Manifest {
113                    plugin_id: self.id.clone(),
114                    message: format!("'entry_ui' must be a relative path, got '{entry_ui}'"),
115                });
116            }
117            // Reject path traversal
118            if entry_ui.contains("..") {
119                return Err(PluginError::Manifest {
120                    plugin_id: self.id.clone(),
121                    message: format!("'entry_ui' must not contain '..', got '{entry_ui}'"),
122                });
123            }
124        }
125        if let Some(ref entry_component) = self.entry_component
126            && entry_component.is_empty()
127        {
128            return Err(PluginError::Manifest {
129                plugin_id: self.id.clone(),
130                message: "'entry_component' must not be empty when specified".into(),
131            });
132        }
133        // Validate icon file path if present
134        if let Some(IconDescriptor::File { path }) = &self.icon {
135            if path.is_absolute() {
136                return Err(PluginError::Manifest {
137                    plugin_id: self.id.clone(),
138                    message: format!("icon file path must be relative, got '{}'", path.display()),
139                });
140            }
141            if path.to_string_lossy().contains("..") {
142                return Err(PluginError::Manifest {
143                    plugin_id: self.id.clone(),
144                    message: format!(
145                        "icon file path must not contain '..', got '{}'",
146                        path.display()
147                    ),
148                });
149            }
150        }
151        Ok(())
152    }
153
154    /// Resolve the `entry_ui` to an absolute path given the plugin root.
155    /// Returns `None` if `entry_ui` is not set.
156    pub fn resolve_entry_ui(&self, plugin_root: &Path) -> Option<PathBuf> {
157        self.entry_ui.as_ref().map(|ui| plugin_root.join(ui))
158    }
159
160    /// Validate that referenced files actually exist on disk.
161    pub fn validate_files(&self, plugin_root: &Path) -> PluginResult<()> {
162        if let Some(ui_path) = self.resolve_entry_ui(plugin_root)
163            && !ui_path.exists()
164        {
165            return Err(PluginError::MissingFile {
166                plugin_id: self.id.clone(),
167                path: ui_path,
168            });
169        }
170        if let Some(IconDescriptor::File { path }) = &self.icon {
171            let icon_path = plugin_root.join(path);
172            if !icon_path.exists() {
173                return Err(PluginError::MissingFile {
174                    plugin_id: self.id.clone(),
175                    path: icon_path,
176                });
177            }
178        }
179        Ok(())
180    }
181}
182
183#[cfg(test)]
184mod tests {
185    use super::*;
186
187    const VALID_TOML: &str = r#"
188id = "test_plugin"
189name = "Test Plugin"
190version = "1.0.0"
191description = "A test plugin"
192repository = "https://github.com/example/test-plugin"
193entry_ui = "ui/panel.slint"
194entry_component = "Panel"
195
196[environment]
197version = ">=0.4.1"
198
199[icon]
200kind = "svg"
201data = "<svg/>"
202"#;
203
204    #[test]
205    fn parse_valid_manifest() {
206        let m = PluginManifest::from_toml(VALID_TOML, "test").unwrap();
207        assert_eq!(m.id, "test_plugin");
208        assert_eq!(m.name, "Test Plugin");
209        assert_eq!(m.version, "1.0.0");
210        assert_eq!(m.description.as_deref(), Some("A test plugin"));
211        assert_eq!(
212            m.repository.as_deref(),
213            Some("https://github.com/example/test-plugin")
214        );
215        assert_eq!(m.entry_ui.as_deref(), Some("ui/panel.slint"));
216        assert_eq!(m.entry_component.as_deref(), Some("Panel"));
217        assert_eq!(
218            m.icon,
219            Some(IconDescriptor::Svg {
220                data: "<svg/>".into()
221            })
222        );
223    }
224
225    #[test]
226    fn reject_missing_id() {
227        let toml = r#"
228name = "Test"
229version = "1.0.0"
230entry_ui = "ui/p.slint"
231entry_component = "P"
232
233[environment]
234version = ">=0.4.1"
235"#;
236        let err = PluginManifest::from_toml(toml, "hint").unwrap_err();
237        assert!(err.to_string().contains("TOML parse error"));
238    }
239
240    #[test]
241    fn reject_empty_id() {
242        let toml = r#"
243id = ""
244name = "Test"
245version = "1.0.0"
246entry_ui = "ui/p.slint"
247entry_component = "P"
248
249[environment]
250version = ">=0.4.1"
251"#;
252        let err = PluginManifest::from_toml(toml, "hint").unwrap_err();
253        assert!(err.to_string().contains("'id' must not be empty"));
254    }
255
256    #[test]
257    fn reject_absolute_entry_ui() {
258        let toml = r#"
259id = "abs"
260name = "Test"
261version = "1.0.0"
262entry_ui = "/etc/evil.slint"
263entry_component = "Evil"
264
265[environment]
266version = ">=0.4.1"
267"#;
268        let err = PluginManifest::from_toml(toml, "hint").unwrap_err();
269        assert!(err.to_string().contains("relative path"));
270    }
271
272    #[test]
273    fn reject_path_traversal_in_entry_ui() {
274        let toml = r#"
275id = "trav"
276name = "Test"
277version = "1.0.0"
278entry_ui = "../escape/evil.slint"
279entry_component = "Evil"
280
281[environment]
282version = ">=0.4.1"
283"#;
284        let err = PluginManifest::from_toml(toml, "hint").unwrap_err();
285        assert!(err.to_string().contains(".."));
286    }
287
288    #[test]
289    fn resolve_entry_ui_relative_to_root() {
290        let m = PluginManifest::from_toml(VALID_TOML, "test").unwrap();
291        let resolved = m.resolve_entry_ui(Path::new("/plugins/test_plugin"));
292        assert_eq!(
293            resolved,
294            Some(PathBuf::from("/plugins/test_plugin/ui/panel.slint"))
295        );
296    }
297
298    #[test]
299    fn validate_files_missing_ui() {
300        let m = PluginManifest::from_toml(VALID_TOML, "test").unwrap();
301        let err = m
302            .validate_files(Path::new("/nonexistent/plugin/root"))
303            .unwrap_err();
304        match err {
305            PluginError::MissingFile { plugin_id, .. } => {
306                assert_eq!(plugin_id, "test_plugin");
307            }
308            other => panic!("expected MissingFile, got {other:?}"),
309        }
310    }
311
312    #[test]
313    fn parse_manifest_without_icon() {
314        let toml = r#"
315id = "no_icon"
316name = "No Icon Plugin"
317version = "0.1.0"
318entry_ui = "ui/panel.slint"
319entry_component = "Panel"
320
321[environment]
322version = ">=0.4.1"
323"#;
324        let m = PluginManifest::from_toml(toml, "no_icon").unwrap();
325        assert!(m.icon.is_none());
326    }
327
328    #[test]
329    fn parse_manifest_without_optional_metadata() {
330        let m = PluginManifest::from_toml(
331            r#"
332id = "legacy"
333name = "Legacy"
334version = "0.1.0"
335
336[environment]
337version = ">=0.4.1"
338"#,
339            "legacy",
340        )
341        .unwrap();
342        assert!(m.description.is_none());
343        assert!(m.repository.is_none());
344    }
345
346    #[test]
347    fn reject_absolute_icon_path() {
348        let toml = r#"
349id = "bad_icon"
350name = "Test"
351version = "1.0.0"
352entry_ui = "ui/p.slint"
353entry_component = "P"
354
355[environment]
356version = ">=0.4.1"
357
358[icon]
359kind = "file"
360path = "/etc/icon.png"
361"#;
362        let err = PluginManifest::from_toml(toml, "hint").unwrap_err();
363        assert!(err.to_string().contains("icon file path must be relative"));
364    }
365}