Skip to main content

graphrt_plugin/
discover.rs

1//! Plugin discovery, installation and integrity checks.
2
3use std::path::{Path, PathBuf};
4
5use sha2::{Digest, Sha256};
6
7use crate::error::PluginError;
8use crate::manifest::{LoadedManifest, manifest_in};
9
10/// Environment variable listing extra plugin directories.
11pub const PLUGIN_PATH_ENV: &str = "GRAPHRT_PLUGIN_PATH";
12
13/// Default plugin search paths: `$GRAPHRT_PLUGIN_PATH` entries, then `~/.graphrt/plugins`.
14pub fn default_plugin_paths() -> Vec<PathBuf> {
15    let mut paths: Vec<PathBuf> = match std::env::var_os(PLUGIN_PATH_ENV) {
16        Some(v) => std::env::split_paths(&v).filter(|p| !p.as_os_str().is_empty()).collect(),
17        None => Vec::new(),
18    };
19    if let Some(dir) = default_install_dir() {
20        paths.push(dir);
21    }
22    paths
23}
24
25/// `~/.graphrt/plugins`, if a home directory is known.
26pub fn default_install_dir() -> Option<PathBuf> {
27    let home = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE"))?;
28    Some(PathBuf::from(home).join(".graphrt").join("plugins"))
29}
30
31/// Find plugin manifests under `paths`. A path that is itself a plugin directory
32/// is returned directly; otherwise its direct subdirectories are scanned.
33/// Missing paths are skipped. Results are sorted for determinism.
34pub fn discover(paths: &[PathBuf]) -> Vec<PathBuf> {
35    let mut found = Vec::new();
36    for path in paths {
37        if let Some(manifest) = manifest_in(path) {
38            found.push(manifest);
39            continue;
40        }
41        let Ok(entries) = std::fs::read_dir(path) else { continue };
42        let mut dirs: Vec<PathBuf> = entries.filter_map(Result::ok).map(|e| e.path()).filter(|p| p.is_dir()).collect();
43        dirs.sort();
44        found.extend(dirs.iter().filter_map(|d| manifest_in(d)));
45    }
46    found
47}
48
49/// Lowercase hex SHA-256 of a file, read in chunks (no whole-file buffer).
50pub fn sha256_file(path: &Path) -> Result<String, PluginError> {
51    use std::io::Read;
52    let io = |e: std::io::Error| PluginError::Io { path: path.to_path_buf(), message: e.to_string() };
53    let mut file = std::fs::File::open(path).map_err(io)?;
54    let mut hasher = Sha256::new();
55    let mut buf = vec![0u8; 64 * 1024];
56    loop {
57        let n = file.read(&mut buf).map_err(io)?;
58        if n == 0 {
59            break;
60        }
61        hasher.update(buf.get(..n).unwrap_or_default());
62    }
63    Ok(hasher.finalize().iter().map(|b| format!("{b:02x}")).collect())
64}
65
66/// Verify every `checksums` entry of a manifest.
67///
68/// Limits (see `docs/plugins.md`): the hashes live in the manifest they protect,
69/// so they detect corruption and partial edits, not an attacker who can rewrite
70/// the plugin directory; files are hashed and then executed by path. Keep plugin
71/// directories writable only by the operator. Symlinked files are rejected so a
72/// pinned path cannot be redirected outside the plugin directory.
73pub fn verify_checksums(plugin: &LoadedManifest) -> Result<(), PluginError> {
74    for (file, expected) in &plugin.manifest.checksums {
75        let path = plugin.resolve(file);
76        let meta = std::fs::symlink_metadata(&path)
77            .map_err(|e| PluginError::Io { path: path.clone(), message: e.to_string() })?;
78        if !meta.file_type().is_file() {
79            return Err(PluginError::Manifest(format!(
80                "plugin `{}`: checksum path `{file}` must be a regular file (not a symlink or directory)",
81                plugin.manifest.name
82            )));
83        }
84        let actual = sha256_file(&path)?;
85        if !actual.eq_ignore_ascii_case(expected.trim()) {
86            return Err(PluginError::Checksum { plugin: plugin.manifest.name.clone(), file: file.clone() });
87        }
88    }
89    Ok(())
90}
91
92/// Copy the plugin in `src` into `<dest_root>/<name>` (replacing an existing copy)
93/// and return the installed manifest.
94pub fn install_from_dir(src: &Path, dest_root: &Path) -> Result<LoadedManifest, PluginError> {
95    let source = LoadedManifest::from_dir(src)?;
96    verify_checksums(&source)?;
97    let target = dest_root.join(&source.manifest.name);
98    let staging = dest_root.join(format!(".{}.installing", source.manifest.name));
99    let io = |path: &Path, e: std::io::Error| PluginError::Io { path: path.to_path_buf(), message: e.to_string() };
100    std::fs::create_dir_all(dest_root).map_err(|e| io(dest_root, e))?;
101    if staging.exists() {
102        std::fs::remove_dir_all(&staging).map_err(|e| io(&staging, e))?;
103    }
104    copy_dir(&source.dir, &staging)?;
105    if target.exists() {
106        std::fs::remove_dir_all(&target).map_err(|e| io(&target, e))?;
107    }
108    std::fs::rename(&staging, &target).map_err(|e| io(&target, e))?;
109    LoadedManifest::from_dir(&target)
110}
111
112/// Clone a git repository (optionally at `rev`, a branch or tag) and install the
113/// plugin at its root. Requires the `git` executable.
114///
115/// For a repository holding several plugins in subdirectories, use
116/// [`install_from_git_subdir`].
117#[cfg(feature = "git")]
118pub fn install_from_git(url: &str, rev: Option<&str>, dest_root: &Path) -> Result<LoadedManifest, PluginError> {
119    clone_and_install(url, rev, None, dest_root)
120}
121
122/// Clone a git repository (optionally at `rev`, a branch or tag) and install the
123/// plugin in its subdirectory `subdir` (for example `whatsapp-api` in a
124/// monorepo with one plugin per directory). Requires the `git` executable.
125///
126/// `subdir` must be a relative path inside the repository: absolute paths,
127/// `..` components and symlinks anywhere along the path are rejected. Only the
128/// subdirectory's contents are installed, after the same manifest, name and
129/// checksum checks as [`install_from_dir`].
130///
131/// # Errors
132/// [`PluginError::Install`] for an unsafe or missing `subdir` or a failed
133/// clone; any error of [`install_from_dir`] for the plugin itself.
134///
135/// # Example
136/// ```no_run
137/// # fn demo() -> Result<(), graphrt_plugin::PluginError> {
138/// let dest = graphrt_plugin::default_install_dir().unwrap_or_default();
139/// graphrt_plugin::install_from_git_subdir(
140///     "https://github.com/BimaPangestu28/graphrt-plugins",
141///     Some("main"),
142///     "whatsapp-api",
143///     &dest,
144/// )?;
145/// # Ok(()) }
146/// ```
147#[cfg(feature = "git")]
148pub fn install_from_git_subdir(
149    url: &str,
150    rev: Option<&str>,
151    subdir: &str,
152    dest_root: &Path,
153) -> Result<LoadedManifest, PluginError> {
154    let relative = validate_subdir(subdir)?;
155    clone_and_install(url, rev, Some(&relative), dest_root)
156}
157
158#[cfg(feature = "git")]
159fn clone_and_install(
160    url: &str,
161    rev: Option<&str>,
162    subdir: Option<&Path>,
163    dest_root: &Path,
164) -> Result<LoadedManifest, PluginError> {
165    if url.starts_with('-') || rev.is_some_and(|r| r.starts_with('-')) {
166        return Err(PluginError::Install("invalid git url or revision".into()));
167    }
168    let checkout = std::env::temp_dir().join(format!(
169        "graphrt-plugin-{}-{}",
170        std::process::id(),
171        std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or(0)
172    ));
173    let result = clone_repository(url, rev, &checkout).and_then(|()| match subdir {
174        Some(relative) => resolve_subdir(&checkout, relative).and_then(|dir| install_from_dir(&dir, dest_root)),
175        None => install_from_dir(&checkout, dest_root),
176    });
177    let _cleanup = std::fs::remove_dir_all(&checkout);
178    result
179}
180
181#[cfg(feature = "git")]
182fn clone_repository(url: &str, rev: Option<&str>, checkout: &Path) -> Result<(), PluginError> {
183    let mut cmd = std::process::Command::new("git");
184    cmd.args(["clone", "--depth", "1", "--quiet"]);
185    if let Some(rev) = rev {
186        cmd.args(["--branch", rev]);
187    }
188    cmd.arg("--").arg(url).arg(checkout);
189    let output = cmd.output().map_err(|e| PluginError::Install(format!("cannot run git: {e}")))?;
190    if !output.status.success() {
191        return Err(PluginError::Install(format!(
192            "git clone failed: {}",
193            String::from_utf8_lossy(&output.stderr).trim()
194        )));
195    }
196    Ok(())
197}
198
199/// Check that `subdir` is a non-empty relative path without `..`, and return it
200/// with `.` components dropped.
201#[cfg(feature = "git")]
202fn validate_subdir(subdir: &str) -> Result<PathBuf, PluginError> {
203    use std::path::Component;
204    let invalid = |reason: &str| PluginError::Install(format!("invalid subdirectory `{subdir}`: {reason}"));
205    let mut relative = PathBuf::new();
206    for component in Path::new(subdir).components() {
207        match component {
208            Component::Normal(part) => relative.push(part),
209            Component::CurDir => {}
210            Component::ParentDir => return Err(invalid("`..` is not allowed")),
211            Component::RootDir | Component::Prefix(_) => {
212                return Err(invalid("must be a path relative to the repository root"));
213            }
214        }
215    }
216    if relative.as_os_str().is_empty() {
217        return Err(invalid("must name a directory inside the repository"));
218    }
219    Ok(relative)
220}
221
222/// Walk `relative` inside `checkout`, requiring every component to be a real
223/// directory (not a symlink), so the plugin cannot come from outside the clone.
224#[cfg(feature = "git")]
225fn resolve_subdir(checkout: &Path, relative: &Path) -> Result<PathBuf, PluginError> {
226    let mut dir = checkout.to_path_buf();
227    for part in relative.components() {
228        dir.push(part);
229        let shown = dir.strip_prefix(checkout).unwrap_or(&dir).display().to_string();
230        let meta = std::fs::symlink_metadata(&dir)
231            .map_err(|_| PluginError::Install(format!("subdirectory `{shown}` does not exist in the repository")))?;
232        if meta.file_type().is_symlink() {
233            return Err(PluginError::Install(format!("subdirectory `{shown}` is a symlink, which is not allowed")));
234        }
235        if !meta.is_dir() {
236            return Err(PluginError::Install(format!("subdirectory `{shown}` is not a directory")));
237        }
238    }
239    if manifest_in(&dir).is_none() {
240        return Err(PluginError::Install(format!(
241            "subdirectory `{}` has no plugin manifest (graphrt-plugin.json or .yaml)",
242            relative.display()
243        )));
244    }
245    Ok(dir)
246}
247
248fn copy_dir(src: &Path, dst: &Path) -> Result<(), PluginError> {
249    let io = |path: &Path, e: std::io::Error| PluginError::Io { path: path.to_path_buf(), message: e.to_string() };
250    std::fs::create_dir_all(dst).map_err(|e| io(dst, e))?;
251    for entry in std::fs::read_dir(src).map_err(|e| io(src, e))? {
252        let entry = entry.map_err(|e| io(src, e))?;
253        let name = entry.file_name();
254        if name == ".git" {
255            continue;
256        }
257        let from = entry.path();
258        let to = dst.join(&name);
259        let file_type = entry.file_type().map_err(|e| io(&from, e))?;
260        if file_type.is_dir() {
261            copy_dir(&from, &to)?;
262        } else if file_type.is_file() {
263            std::fs::copy(&from, &to).map_err(|e| io(&from, e))?;
264        }
265        // Symlinks are skipped: they could point outside the plugin directory.
266    }
267    Ok(())
268}
269
270#[cfg(test)]
271mod tests {
272    use super::*;
273
274    fn temp(name: &str) -> PathBuf {
275        let p = std::env::temp_dir().join(format!("graphrt-plugin-test-{}-{name}", std::process::id()));
276        let _ = std::fs::remove_dir_all(&p);
277        std::fs::create_dir_all(&p).unwrap();
278        p
279    }
280
281    fn write_plugin(dir: &Path, name: &str, checksums: serde_json::Value) {
282        std::fs::create_dir_all(dir).unwrap();
283        std::fs::write(dir.join("run.sh"), "echo hi").unwrap();
284        let manifest = serde_json::json!({
285            "name": name, "runtime": "process", "command": "sh", "args": ["run.sh"], "checksums": checksums
286        });
287        std::fs::write(dir.join("graphrt-plugin.json"), manifest.to_string()).unwrap();
288    }
289
290    #[test]
291    fn discovers_and_installs() {
292        let root = temp("discover");
293        write_plugin(&root.join("b"), "b", serde_json::json!({}));
294        write_plugin(&root.join("a"), "a", serde_json::json!({}));
295        std::fs::create_dir_all(root.join("empty")).unwrap();
296        let found = discover(&[root.clone(), root.join("missing")]);
297        assert_eq!(found.len(), 2);
298        assert!(found[0].ends_with("a/graphrt-plugin.json"));
299        // A plugin directory passed directly.
300        assert_eq!(discover(&[root.join("a")]).len(), 1);
301
302        let dest = temp("install");
303        let installed = install_from_dir(&root.join("a"), &dest).unwrap();
304        assert_eq!(installed.manifest.name, "a");
305        assert!(dest.join("a").join("run.sh").is_file());
306        // Reinstall replaces.
307        assert!(install_from_dir(&root.join("a"), &dest).is_ok());
308    }
309
310    #[test]
311    fn checksums_are_enforced() {
312        let root = temp("checksum");
313        let digest = {
314            std::fs::write(root.join("probe"), "echo hi").unwrap();
315            sha256_file(&root.join("probe")).unwrap()
316        };
317        write_plugin(&root.join("ok"), "ok", serde_json::json!({"run.sh": digest}));
318        assert!(verify_checksums(&LoadedManifest::from_dir(&root.join("ok")).unwrap()).is_ok());
319        write_plugin(&root.join("bad"), "bad", serde_json::json!({"run.sh": "00ff"}));
320        let bad = LoadedManifest::from_dir(&root.join("bad")).unwrap();
321        assert!(matches!(verify_checksums(&bad), Err(PluginError::Checksum { .. })));
322        assert!(install_from_dir(&root.join("bad"), &temp("dest-bad")).is_err());
323    }
324
325    /// Run `git` in `dir`, with an identity so commits work on any machine.
326    #[cfg(feature = "git")]
327    fn git(dir: &Path, args: &[&str]) {
328        let status = std::process::Command::new("git")
329            .args(["-c", "user.name=test", "-c", "user.email=test@example.com", "-c", "init.defaultBranch=main"])
330            .args(args)
331            .current_dir(dir)
332            .output()
333            .unwrap();
334        assert!(status.status.success(), "git {args:?}: {}", String::from_utf8_lossy(&status.stderr));
335    }
336
337    #[cfg(feature = "git")]
338    fn has_git() -> bool {
339        std::process::Command::new("git").arg("--version").output().is_ok_and(|o| o.status.success())
340    }
341
342    /// Commit everything in `repo` and return its `file://` URL (so `--depth` applies).
343    #[cfg(feature = "git")]
344    fn commit_repo(repo: &Path) -> String {
345        git(repo, &["init", "--quiet"]);
346        git(repo, &["add", "-A"]);
347        git(repo, &["commit", "--quiet", "-m", "fixture"]);
348        git(repo, &["tag", "v1"]);
349        format!("file://{}", repo.display())
350    }
351
352    #[cfg(feature = "git")]
353    #[test]
354    fn installs_plugins_from_monorepo_subdirectories() {
355        if !has_git() {
356            eprintln!("skipping: git is required");
357            return;
358        }
359        let repo = temp("mono-repo");
360        write_plugin(&repo.join("alpha"), "alpha", serde_json::json!({}));
361        write_plugin(&repo.join("nested/beta"), "beta", serde_json::json!({}));
362        std::fs::write(repo.join("README.md"), "collection").unwrap();
363        let url = commit_repo(&repo);
364        let dest = temp("mono-dest");
365
366        let alpha = install_from_git_subdir(&url, Some("v1"), "alpha", &dest).unwrap();
367        assert_eq!(alpha.manifest.name, "alpha");
368        assert!(dest.join("alpha/run.sh").is_file());
369        // Only the subdirectory is copied: nothing from the repository root.
370        assert!(!dest.join("alpha/README.md").exists());
371        assert!(!dest.join("alpha/nested").exists());
372
373        let beta = install_from_git_subdir(&url, None, "./nested/beta/", &dest).unwrap();
374        assert_eq!(beta.manifest.name, "beta");
375        assert!(dest.join("beta/graphrt-plugin.json").is_file());
376    }
377
378    #[cfg(feature = "git")]
379    #[test]
380    fn root_install_from_git_is_unchanged() {
381        if !has_git() {
382            eprintln!("skipping: git is required");
383            return;
384        }
385        let repo = temp("root-repo");
386        write_plugin(&repo, "rooted", serde_json::json!({}));
387        let url = commit_repo(&repo);
388        let dest = temp("root-dest");
389        let installed = install_from_git(&url, Some("v1"), &dest).unwrap();
390        assert_eq!(installed.manifest.name, "rooted");
391        assert!(dest.join("rooted/run.sh").is_file());
392        assert!(!dest.join("rooted/.git").exists());
393    }
394
395    #[cfg(feature = "git")]
396    #[test]
397    fn unsafe_or_missing_subdirectories_are_rejected() {
398        if !has_git() {
399            eprintln!("skipping: git is required");
400            return;
401        }
402        let outside = temp("mono-outside");
403        write_plugin(&outside.join("evil"), "evil", serde_json::json!({}));
404        let repo = temp("mono-bad-repo");
405        write_plugin(&repo.join("good"), "good", serde_json::json!({}));
406        std::fs::create_dir_all(repo.join("docs")).unwrap();
407        std::fs::write(repo.join("docs/index.md"), "no manifest here").unwrap();
408        std::fs::write(repo.join("file.txt"), "not a dir").unwrap();
409        write_plugin(&repo.join("bad-sum"), "bad-sum", serde_json::json!({"run.sh": "00ff"}));
410        #[cfg(unix)]
411        std::os::unix::fs::symlink(outside.join("evil"), repo.join("escape")).unwrap();
412        #[cfg(unix)]
413        std::os::unix::fs::symlink("good", repo.join("alias")).unwrap();
414        let url = commit_repo(&repo);
415        let dest = temp("mono-bad-dest");
416
417        let message = |subdir: &str| match install_from_git_subdir(&url, None, subdir, &dest) {
418            Err(e) => e.to_string(),
419            Ok(m) => format!("unexpectedly installed {}", m.manifest.name),
420        };
421        assert!(message("..").contains("`..` is not allowed"), "{}", message(".."));
422        assert!(message("good/../../x").contains("`..` is not allowed"));
423        assert!(message("/etc").contains("relative to the repository root"));
424        assert!(message("").contains("must name a directory"));
425        assert!(message(".").contains("must name a directory"));
426        assert!(message("missing").contains("does not exist"));
427        assert!(message("file.txt").contains("not a directory"));
428        assert!(message("docs").contains("has no plugin manifest"));
429        assert!(matches!(install_from_git_subdir(&url, None, "bad-sum", &dest), Err(PluginError::Checksum { .. })));
430        #[cfg(unix)]
431        {
432            assert!(message("escape").contains("is a symlink"), "{}", message("escape"));
433            assert!(message("alias").contains("is a symlink"));
434        }
435        // Nothing was installed by any rejected attempt.
436        assert_eq!(std::fs::read_dir(&dest).unwrap().count(), 0);
437    }
438
439    #[test]
440    fn sha256_known_value() {
441        let root = temp("sha");
442        std::fs::write(root.join("f"), "abc").unwrap();
443        assert_eq!(
444            sha256_file(&root.join("f")).unwrap(),
445            "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
446        );
447    }
448}