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