Skip to main content

vault_core/
plugin.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright the UnENVerse contributors.
3//! Plugin manifests and the registry of installed plugins (protocol `unv-plugin-rpc/1`).
4//!
5//! A plugin is an external program in `<plugins dir>/<name>/` with a `plugin.json` manifest. It runs
6//! with the user's rights, as any program the user starts would; nothing here sandboxes it. What the
7//! registry does give is a record of what the user agreed to (the capabilities in the manifest and
8//! the SHA-256 of the program at install time) so a replaced binary is noticed before it is called.
9//! A plugin is never handed the master key, other entries or signing keys: the host passes it only
10//! the parameters of one operation and the credential slots the user bound to it.
11
12use rusqlite::{params, Connection, OptionalExtension};
13use serde::{Deserialize, Serialize};
14use sha2::{Digest, Sha256};
15use std::path::{Path, PathBuf};
16
17pub const PROTOCOL: &str = "unv-plugin-rpc/1";
18
19/// What a plugin may be asked to do. The user sees this list when enabling it.
20pub const CAPABILITIES: &[&str] = &["destination", "notifier", "issuer", "importer"];
21
22#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
23pub struct Manifest {
24    pub name: String,
25    pub version: String,
26    pub protocol: String,
27    /// The program, relative to the plugin's directory.
28    pub exec: String,
29    #[serde(default)]
30    pub args: Vec<String>,
31    pub capabilities: Vec<String>,
32    /// Named credential slots the user binds to vault entries; the plugin never sees an entry it was not given.
33    #[serde(default)]
34    pub slots: Vec<String>,
35    #[serde(default)]
36    pub description: String,
37}
38
39fn plain(name: &str) -> bool {
40    !name.is_empty()
41        && name.len() <= 64
42        && name
43            .chars()
44            .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-' || c == '_')
45}
46
47impl Manifest {
48    pub fn parse(text: &str) -> Result<Self, String> {
49        let m: Manifest = serde_json::from_str(text).map_err(|e| format!("plugin.json: {e}"))?;
50        m.validate()?;
51        Ok(m)
52    }
53
54    pub fn validate(&self) -> Result<(), String> {
55        if !plain(&self.name) {
56            return Err(format!(
57                "plugin name '{}' must be lowercase letters, digits, '-' or '_'",
58                self.name
59            ));
60        }
61        if self.protocol != PROTOCOL {
62            return Err(format!(
63                "plugin speaks '{}', this host speaks '{PROTOCOL}'",
64                self.protocol
65            ));
66        }
67        if self.version.trim().is_empty() {
68            return Err("plugin version is empty".into());
69        }
70        // A rooted path ("/bin/sh", "\\x", "C:\\x") or a ".." step leaves the plugin's directory; on
71        // Windows "/bin/sh" is not `is_absolute()` (no drive), so look at the components instead.
72        let exec = Path::new(&self.exec);
73        if self.exec.is_empty()
74            || exec.is_absolute()
75            || self.exec.starts_with(['/', '\\'])
76            || exec.components().any(|c| {
77                matches!(
78                    c,
79                    std::path::Component::ParentDir
80                        | std::path::Component::RootDir
81                        | std::path::Component::Prefix(_)
82                )
83            })
84        {
85            return Err("plugin exec must be a path inside the plugin's own directory".into());
86        }
87        if self.capabilities.is_empty() {
88            return Err("a plugin must declare at least one capability".into());
89        }
90        if let Some(bad) = self
91            .capabilities
92            .iter()
93            .find(|c| !CAPABILITIES.contains(&c.as_str()))
94        {
95            return Err(format!("unknown capability '{bad}'"));
96        }
97        if let Some(bad) = self.slots.iter().find(|s| !plain(s)) {
98            return Err(format!("slot name '{bad}' must be a plain name"));
99        }
100        Ok(())
101    }
102}
103
104/// SHA-256 of the program file, as lowercase hex: the provenance recorded at install and re-checked
105/// before each call.
106pub fn provenance(program: &Path) -> Result<String, String> {
107    let bytes = std::fs::read(program).map_err(|e| format!("{}: {e}", program.display()))?;
108    Ok(Sha256::digest(bytes)
109        .iter()
110        .map(|b| format!("{b:02x}"))
111        .collect())
112}
113
114/// A plugin found on disk and not yet installed.
115#[derive(Clone, Debug, PartialEq, Eq)]
116pub struct Discovered {
117    pub dir: PathBuf,
118    pub manifest: Manifest,
119}
120
121impl Discovered {
122    pub fn program(&self) -> PathBuf {
123        self.dir.join(&self.manifest.exec)
124    }
125}
126
127/// Reads `<dir>/<name>/plugin.json` for every subdirectory. A broken manifest is reported with
128/// its path and does not hide the others.
129pub fn discover(dir: &Path) -> (Vec<Discovered>, Vec<String>) {
130    let mut found = Vec::new();
131    let mut problems = Vec::new();
132    let Ok(read) = std::fs::read_dir(dir) else {
133        return (found, problems);
134    };
135    let mut dirs: Vec<PathBuf> = read
136        .flatten()
137        .map(|e| e.path())
138        .filter(|p| p.is_dir())
139        .collect();
140    dirs.sort();
141    for d in dirs {
142        let file = d.join("plugin.json");
143        let Ok(text) = std::fs::read_to_string(&file) else {
144            continue;
145        };
146        match Manifest::parse(&text) {
147            Ok(manifest) => found.push(Discovered { dir: d, manifest }),
148            Err(e) => problems.push(format!("{}: {e}", file.display())),
149        }
150    }
151    (found, problems)
152}
153
154#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
155pub struct Installed {
156    pub name: String,
157    pub version: String,
158    pub hash: String,
159    pub dir: String,
160    pub capabilities: Vec<String>,
161    pub slots: Vec<String>,
162    pub enabled: bool,
163    pub installed_at: String,
164}
165
166pub fn init_schema(conn: &Connection) -> Result<(), String> {
167    conn.execute_batch(
168        "CREATE TABLE IF NOT EXISTS plugins (
169             name TEXT PRIMARY KEY, version TEXT NOT NULL, hash TEXT NOT NULL, dir TEXT NOT NULL,
170             capabilities TEXT NOT NULL, slots TEXT NOT NULL, enabled INTEGER NOT NULL,
171             installed_at TEXT NOT NULL
172         );",
173    )
174    .map_err(|e| e.to_string())
175}
176
177/// Records a plugin as installed and disabled. Installing again replaces the record (a new
178/// version or hash) and disables it: the user agrees to the new capabilities by enabling it.
179pub fn install(conn: &Connection, found: &Discovered) -> Result<Installed, String> {
180    let m = &found.manifest;
181    let hash = provenance(&found.program())?;
182    let row = Installed {
183        name: m.name.clone(),
184        version: m.version.clone(),
185        hash,
186        dir: found.dir.to_string_lossy().into_owned(),
187        capabilities: m.capabilities.clone(),
188        slots: m.slots.clone(),
189        enabled: false,
190        installed_at: crate::iso_now(),
191    };
192    conn.execute(
193        "INSERT OR REPLACE INTO plugins (name, version, hash, dir, capabilities, slots, enabled, installed_at)
194         VALUES (?1, ?2, ?3, ?4, ?5, ?6, 0, ?7)",
195        params![
196            row.name,
197            row.version,
198            row.hash,
199            row.dir,
200            serde_json::to_string(&row.capabilities).map_err(|e| e.to_string())?,
201            serde_json::to_string(&row.slots).map_err(|e| e.to_string())?,
202            row.installed_at
203        ],
204    )
205    .map_err(|e| e.to_string())?;
206    Ok(row)
207}
208
209fn from_row(r: &rusqlite::Row<'_>) -> rusqlite::Result<Installed> {
210    let list = |i: usize| -> rusqlite::Result<Vec<String>> {
211        let text: String = r.get(i)?;
212        Ok(serde_json::from_str(&text).unwrap_or_default())
213    };
214    Ok(Installed {
215        name: r.get(0)?,
216        version: r.get(1)?,
217        hash: r.get(2)?,
218        dir: r.get(3)?,
219        capabilities: list(4)?,
220        slots: list(5)?,
221        enabled: r.get::<_, i64>(6)? != 0,
222        installed_at: r.get(7)?,
223    })
224}
225
226const COLUMNS: &str = "name, version, hash, dir, capabilities, slots, enabled, installed_at";
227
228pub fn get(conn: &Connection, name: &str) -> Result<Option<Installed>, String> {
229    conn.query_row(
230        &format!("SELECT {COLUMNS} FROM plugins WHERE name = ?1"),
231        [name],
232        from_row,
233    )
234    .optional()
235    .map_err(|e| e.to_string())
236}
237
238pub fn list(conn: &Connection) -> Result<Vec<Installed>, String> {
239    let mut stmt = conn
240        .prepare(&format!("SELECT {COLUMNS} FROM plugins ORDER BY name"))
241        .map_err(|e| e.to_string())?;
242    let rows = stmt.query_map([], from_row).map_err(|e| e.to_string())?;
243    rows.map(|r| r.map_err(|e| e.to_string())).collect()
244}
245
246pub fn set_enabled(conn: &Connection, name: &str, enabled: bool) -> Result<(), String> {
247    let n = conn
248        .execute(
249            "UPDATE plugins SET enabled = ?2 WHERE name = ?1",
250            params![name, enabled as i64],
251        )
252        .map_err(|e| e.to_string())?;
253    if n == 0 {
254        return Err(format!("No plugin named {name}"));
255    }
256    Ok(())
257}
258
259pub fn remove(conn: &Connection, name: &str) -> Result<bool, String> {
260    conn.execute("DELETE FROM plugins WHERE name = ?1", [name])
261        .map(|n| n > 0)
262        .map_err(|e| e.to_string())
263}
264
265/// The installed program still matches what the user installed.
266pub fn check_provenance(installed: &Installed, manifest: &Manifest) -> Result<(), String> {
267    let program = Path::new(&installed.dir).join(&manifest.exec);
268    let now = provenance(&program)?;
269    if now == installed.hash {
270        Ok(())
271    } else {
272        Err(format!(
273            "plugin '{}' changed since it was installed (was {}, is {}); install it again to accept the new program",
274            installed.name,
275            &installed.hash[..12.min(installed.hash.len())],
276            &now[..12.min(now.len())]
277        ))
278    }
279}
280
281#[cfg(test)]
282mod tests {
283    use super::*;
284
285    fn manifest(extra: &str) -> String {
286        format!(
287            r#"{{"name":"ntfy","version":"1.0.0","protocol":"unv-plugin-rpc/1","exec":"run.sh","capabilities":["notifier"]{extra}}}"#
288        )
289    }
290
291    #[test]
292    fn a_valid_manifest_parses_and_defaults_are_empty() {
293        let m = Manifest::parse(&manifest("")).unwrap();
294        assert_eq!(m.name, "ntfy");
295        assert!(m.slots.is_empty() && m.args.is_empty());
296    }
297
298    #[test]
299    fn a_manifest_cannot_name_a_program_outside_its_directory_or_an_unknown_capability() {
300        assert!(Manifest::parse(&manifest(r#","slots":["Bad Name"]"#))
301            .unwrap_err()
302            .contains("slot name"));
303        let bad =
304            |from: &str, to: &str| Manifest::parse(&manifest("").replace(from, to)).unwrap_err();
305        assert!(bad("run.sh", "../run.sh").contains("inside"));
306        assert!(bad("run.sh", "/bin/sh").contains("inside"));
307        assert!(bad("\"ntfy\"", "\"Not Plain\"").contains("lowercase"));
308        assert!(bad("rpc/1", "rpc/2").contains("speaks"));
309        assert!(bad("notifier", "root").contains("unknown capability"));
310        assert!(bad("[\"notifier\"]", "[]").contains("at least one"));
311        assert!(bad("\"1.0.0\"", "\"  \"").contains("version is empty"));
312        assert!(Manifest::parse("{").unwrap_err().contains("plugin.json"));
313    }
314
315    fn plugin_dir() -> std::path::PathBuf {
316        let d = std::env::temp_dir().join(format!("vc-plug-{}", crate::new_uuid()));
317        std::fs::create_dir_all(d.join("ntfy")).unwrap();
318        std::fs::write(d.join("ntfy/plugin.json"), manifest("")).unwrap();
319        std::fs::write(d.join("ntfy/run.sh"), "#!/bin/sh\n").unwrap();
320        d
321    }
322
323    #[test]
324    fn discovery_reports_a_broken_manifest_without_hiding_the_others() {
325        let d = plugin_dir();
326        std::fs::create_dir_all(d.join("broken")).unwrap();
327        std::fs::write(d.join("broken/plugin.json"), "{}").unwrap();
328        std::fs::create_dir_all(d.join("no-manifest")).unwrap();
329        let (found, problems) = discover(&d);
330        assert_eq!(found.len(), 1);
331        assert_eq!(found[0].manifest.name, "ntfy");
332        assert_eq!(problems.len(), 1);
333        assert!(problems[0].contains("broken"));
334        assert_eq!(discover(&d.join("absent")), (vec![], vec![]));
335        let _ = std::fs::remove_dir_all(&d);
336    }
337
338    #[test]
339    fn install_enable_and_a_replaced_program_is_noticed() {
340        let d = plugin_dir();
341        let conn = Connection::open_in_memory().unwrap();
342        init_schema(&conn).unwrap();
343        let (found, _) = discover(&d);
344        let row = install(&conn, &found[0]).unwrap();
345        assert!(!row.enabled, "installing never enables");
346        assert_eq!(get(&conn, "ntfy").unwrap().unwrap(), row);
347        set_enabled(&conn, "ntfy", true).unwrap();
348        assert!(list(&conn).unwrap()[0].enabled);
349        let installed = get(&conn, "ntfy").unwrap().unwrap();
350        check_provenance(&installed, &found[0].manifest).unwrap();
351        std::fs::write(d.join("ntfy/run.sh"), "#!/bin/sh\necho changed\n").unwrap();
352        let err = check_provenance(&installed, &found[0].manifest).unwrap_err();
353        assert!(err.contains("changed since it was installed"), "{err}");
354        // Installing again accepts the new program and disables the plugin until it is enabled.
355        let again = install(&conn, &found[0]).unwrap();
356        assert_ne!(again.hash, installed.hash);
357        assert!(!get(&conn, "ntfy").unwrap().unwrap().enabled);
358        assert!(set_enabled(&conn, "absent", true).is_err());
359        assert!(remove(&conn, "ntfy").unwrap());
360        assert!(!remove(&conn, "ntfy").unwrap());
361        let _ = std::fs::remove_dir_all(&d);
362    }
363}