From 6a4258165de8eebe911824e76dd321a876ae917d Mon Sep 17 00:00:00 2001 From: blockmandev <194144408+blockmandev@users.noreply.github.com> Date: Wed, 21 Oct 2026 21:33:00 -0600 Subject: [PATCH] plugins: a project's plugin is used only once approved, as its files are A plugin in /.incode/plugins/ arrives with whatever was cloned, and its hooks ran commands, its servers started programs and its skills and commands were told to the agent, with no approval: a repository could run a command on the first tool call. Now none of a project's plugin is used until the operator approves it: - src/plugin_approvals.rs: a fingerprint of the plugin folder (every entry's path and bytes, sorted and length-framed; .git left out) and the store /plugin-approvals.json. An approval is the plugin's name and that fingerprint, so any change to the plugin leaves it out again until approved again, the rule a project's .mcp.json servers follow. A symbolic link anywhere in the plugin makes it unapprovable: its target could change without the plugin changing. A store that cannot be read is said, never read as approved. - plugins::discover_usable is the one gate. session_hooks, session_servers, session_skills and custom_commands::Registry::load all take their plugins through it; the plugins left out are said once, with Registry::load's warnings (REPL, --acp and -t), with how to approve each. - `incode plugin approve ` approves a project's plugin as it is now; `incode plugin list` shows each one's state; the completion table offers `approve`. The operator's own plugins (~/.incode/plugins/) need no approval. plugins::discover_here lost its last caller to the gate and is removed. Tests: through discover_usable with the data dir pointed at a temp folder, a project plugin is left out and said, used once approved, and left out again when its hooks change, while the operator's is used as is; the fingerprint follows content and ignores .git; a plugin holding a symlink cannot be approved; a broken store is reported and trusts nothing. Controls: with the gate passing every plugin, or with links fingerprinted, the tests fail. Follow-up: an interactive "approve now?" question in the REPL, as .mcp.json servers have. --- README.md | 9 ++ src/custom_commands.rs | 4 +- src/lib.rs | 1 + src/main.rs | 2 +- src/plugin_approvals.rs | 325 ++++++++++++++++++++++++++++++++++++++++ src/plugins.rs | 139 +++++++++++++++-- 6 files changed, 465 insertions(+), 15 deletions(-) create mode 100644 src/plugin_approvals.rs diff --git a/README.md b/README.md index da7321a..ea9f6a4 100644 --- a/README.md +++ b/README.md @@ -687,6 +687,15 @@ A plugin's hooks and servers run with your authority; install only what you would run yourself. Skills and hooks are read for the directory incode was started in. +**A project's plugins must be approved.** A plugin in the workspace's +`.incode/plugins/` arrives with whatever you cloned, so none of it — hooks, +MCP servers, skills, commands — is used until you run `incode plugin approve +`, which approves it as its files are now (a fingerprint of every file, +`.git` left out). Any change to it afterwards leaves it out again until you +approve it again. A session says which were left out; `incode plugin list` +shows each one's state. Yours in `~/.incode/plugins/` need no approval. +Approvals are kept in `~/.incode/plugin-approvals.json`. + ### Output styles An output style is a way of answering you choose: a Markdown file whose body diff --git a/src/custom_commands.rs b/src/custom_commands.rs index 209e943..3a4325e 100644 --- a/src/custom_commands.rs +++ b/src/custom_commands.rs @@ -139,7 +139,9 @@ impl Registry { /// The commands for this workspace, this operator and their plugins. #[must_use] pub fn load(workspace: &Path) -> Self { - let plugins = crate::plugins::discover(workspace); + // Only plugins that may be used (a project's must be approved); the + // ones left out arrive as problems and are said with the warnings. + let plugins = crate::plugins::discover_usable(workspace); let mut registry = Self::load_from( &workspace.join(PROJECT_DIR), &crate::admin::AdminConfig::default_dir().join(USER_DIR), diff --git a/src/lib.rs b/src/lib.rs index 326eaf3..ec2096a 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -39,6 +39,7 @@ pub mod owner; pub mod parallel; pub mod permissions; pub mod plan; +pub mod plugin_approvals; pub mod plugins; pub mod recall; pub mod recorder; diff --git a/src/main.rs b/src/main.rs index 45c92b3..c7a5fa6 100644 --- a/src/main.rs +++ b/src/main.rs @@ -249,7 +249,7 @@ const COMPLETION: completions::Command = { Value::None, "In this workspace's .incode/plugins", )], - verbs: &["list", "add", "update", "remove", "help"], + verbs: &["list", "add", "update", "remove", "approve", "help"], subcommands: &[], }, Command { diff --git a/src/plugin_approvals.rs b/src/plugin_approvals.rs new file mode 100644 index 0000000..8080620 --- /dev/null +++ b/src/plugin_approvals.rs @@ -0,0 +1,325 @@ +//! Approval for a project's plugins: a plugin in `/.incode/plugins/` +//! arrives with whatever was cloned, and its hooks run commands, its servers +//! start programs and its skills and commands are told to the agent. So none +//! of it is used until the operator approves that plugin, as it is now. +//! +//! The operator's own plugins (`~/.incode/plugins/`) need no approval: they +//! put them there. +//! +//! # What an approval is +//! +//! The plugin's name and a fingerprint of its folder ([`fingerprint`]): every +//! file's path and bytes, `.git` left out. Any change to the plugin — a new +//! hook, an edited server command — makes a new fingerprint, and the plugin is +//! left out again until it is approved again. The same rule as a project's +//! `.mcp.json` servers (`mcp_config::approval_key`). +//! +//! Kept in `/plugin-approvals.json` as `{"approved": [keys]}`. +//! +//! # Wired to +//! +//! - [`usable`] is the one gate: `plugins::session_hooks`, +//! `plugins::session_servers`, `plugins::session_skills` and +//! `custom_commands::Registry::load` take their plugins through it. +//! - `incode plugin approve ` (`plugins::cli`) calls [`approve`]; +//! `incode plugin list` shows [`state`]. + +use std::collections::BTreeSet; +use std::path::Path; + +use sha2::{Digest, Sha256}; + +use crate::plugins::{Plugin, Scope}; + +/// The store, in incode's data directory. +pub const FILE: &str = "plugin-approvals.json"; + +/// The folder left out of a fingerprint: its history, not its content. +const SKIPPED: &str = ".git"; + +#[derive(Debug, Default, serde::Serialize, serde::Deserialize)] +struct Store { + #[serde(default)] + approved: BTreeSet, +} + +/// A fingerprint of everything in `root`: each entry's path relative to it, +/// sorted, with a file's bytes, length-framed so no two folders hash alike by +/// accident. `.git` is left out. +/// +/// # Errors +/// +/// A file or folder could not be read, or one is a symbolic link — whose +/// target could change without the plugin changing, so it cannot be approved. +pub fn fingerprint(root: &Path) -> Result { + let mut entries = Vec::new(); + collect(root, root, &mut entries)?; + entries.sort(); + let mut hasher = Sha256::new(); + for (relative, kind, content) in &entries { + for part in [relative.as_bytes(), kind.as_bytes(), content.as_slice()] { + hasher.update((part.len() as u64).to_le_bytes()); + hasher.update(part); + } + } + Ok(format!("{:x}", hasher.finalize())) +} + +/// Every entry under `dir`, as (path relative to `root` with `/`, kind, +/// content). A symbolic link anywhere is an error: see the check below. +fn collect( + root: &Path, + dir: &Path, + out: &mut Vec<(String, &'static str, Vec)>, +) -> Result<(), String> { + let entries = std::fs::read_dir(dir).map_err(|e| format!("{}: {e}", dir.display()))?; + for entry in entries { + let entry = entry.map_err(|e| format!("{}: {e}", dir.display()))?; + let path = entry.path(); + if entry.file_name() == SKIPPED { + continue; + } + let relative = path + .strip_prefix(root) + .map_err(|e| e.to_string())? + .to_string_lossy() + .replace('\\', "/"); + let meta = + std::fs::symlink_metadata(&path).map_err(|e| format!("{}: {e}", path.display()))?; + // A link is refused, not fingerprinted: its target can sit outside + // the plugin and change without the plugin changing, so an approval + // could not cover what the loaders would read through it. + if meta.file_type().is_symlink() { + return Err(format!( + "{} is a symbolic link; a project's plugin may not contain one", + path.display() + )); + } else if meta.is_dir() { + out.push((relative, "dir", Vec::new())); + collect(root, &path, out)?; + } else { + let bytes = std::fs::read(&path).map_err(|e| format!("{}: {e}", path.display()))?; + out.push((relative, "file", bytes)); + } + } + Ok(()) +} + +/// What `plugin` is approved as: its name and its folder's fingerprint. +/// +/// # Errors +/// +/// The folder could not be read. +pub fn key(plugin: &Plugin) -> Result { + Ok(format!( + "{}:{}", + plugin.manifest.name, + fingerprint(&plugin.root)? + )) +} + +/// The approvals in `data_dir`. A missing file is none; one that cannot be +/// read or parsed is an error, said by the caller — never quietly none. +fn read(data_dir: &Path) -> Result { + let path = data_dir.join(FILE); + match std::fs::read_to_string(&path) { + Ok(text) => serde_json::from_str(&text).map_err(|e| format!("{}: {e}", path.display())), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Store::default()), + Err(e) => Err(format!("{}: {e}", path.display())), + } +} + +/// Approve `plugin` as it is now. +/// +/// # Errors +/// +/// The folder or the store could not be read, or the store not written. +pub fn approve(data_dir: &Path, plugin: &Plugin) -> Result<(), String> { + let mut store = read(data_dir)?; + store.approved.insert(key(plugin)?); + std::fs::create_dir_all(data_dir).map_err(|e| format!("{}: {e}", data_dir.display()))?; + let path = data_dir.join(FILE); + let text = serde_json::to_string_pretty(&store).map_err(|e| e.to_string())?; + std::fs::write(&path, text).map_err(|e| format!("{}: {e}", path.display())) +} + +/// Where `plugin` stands. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum State { + /// The operator's own: no approval needed. + Own, + /// A project's, approved as it is now. + Approved, + /// A project's, not approved — or changed since it was. + NotApproved, + /// A project's whose approval could not be checked: why. + Unknown(String), +} + +/// Where `plugin` stands, against the approvals in `data_dir`. +#[must_use] +pub fn state(data_dir: &Path, plugin: &Plugin) -> State { + if plugin.scope == Scope::User { + return State::Own; + } + match (read(data_dir), key(plugin)) { + (Ok(store), Ok(key)) if store.approved.contains(&key) => State::Approved, + (Ok(_), Ok(_)) => State::NotApproved, + (Err(why), _) | (_, Err(why)) => State::Unknown(why), + } +} + +/// The plugins that may be used: the operator's own, and a project's only +/// when approved as they are now. Each one left out is named, with how to +/// approve it. +#[must_use] +pub fn usable(data_dir: &Path, plugins: Vec) -> (Vec, Vec) { + let mut kept = Vec::new(); + let mut left_out = Vec::new(); + for plugin in plugins { + match state(data_dir, &plugin) { + State::Own | State::Approved => kept.push(plugin), + State::NotApproved => left_out.push(format!( + "plugin `{}` (this project's) is not used: it is not approved, or changed since \ + it was. Look at {} and run `incode plugin approve {}` to use it", + plugin.manifest.name, + plugin.root.display(), + plugin.manifest.name + )), + State::Unknown(why) => left_out.push(format!( + "plugin `{}` (this project's) is not used: its approval could not be checked \ + ({why})", + plugin.manifest.name + )), + } + } + (kept, left_out) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn write(path: &Path, text: &str) { + std::fs::create_dir_all(path.parent().expect("parent")).expect("dir"); + std::fs::write(path, text).expect("write"); + } + + fn plugin(dir: &Path, scope: Scope) -> Plugin { + let root = dir.join("cloned"); + write( + &root.join("plugin.toml"), + "name = \"cloned\"\nversion = \"1\"\n", + ); + write(&root.join("hooks.json"), r#"{"pre_tool_use": ["check"]}"#); + Plugin { + manifest: crate::plugins::Manifest { + name: "cloned".into(), + version: "1".into(), + description: String::new(), + }, + root, + scope, + } + } + + /// **A PROJECT'S PLUGIN IS NOT USED UNTIL APPROVED, AND NOT AFTER IT + /// CHANGES.** The operator's own needs nothing. + #[test] + fn a_project_plugin_is_used_only_as_it_was_approved() { + let dir = tempfile::tempdir().expect("dir"); + let data = tempfile::tempdir().expect("data"); + let project = plugin(dir.path(), Scope::Project); + + let (kept, left_out) = usable(data.path(), vec![project.clone()]); + assert!(kept.is_empty()); + assert!( + left_out[0].contains("incode plugin approve cloned"), + "{left_out:?}" + ); + + approve(data.path(), &project).expect("approve"); + assert_eq!(state(data.path(), &project), State::Approved); + assert_eq!(usable(data.path(), vec![project.clone()]).0.len(), 1); + + // A new hook after the approval: left out again. + write( + &project.root.join("hooks.json"), + r#"{"pre_tool_use": ["curl evil"]}"#, + ); + assert_eq!(state(data.path(), &project), State::NotApproved); + assert!(usable(data.path(), vec![project]).0.is_empty()); + + let own = plugin(&dir.path().join("mine"), Scope::User); + assert_eq!(state(data.path(), &own), State::Own); + } + + /// The fingerprint covers every file and its bytes, and leaves out `.git`. + #[test] + fn the_fingerprint_follows_content_not_history() { + let dir = tempfile::tempdir().expect("dir"); + let root = dir.path(); + write(&root.join("a.txt"), "one"); + let first = fingerprint(root).expect("fingerprint"); + write(&root.join(".git/HEAD"), "ref: x"); + assert_eq!( + fingerprint(root).expect("fingerprint"), + first, + ".git counted" + ); + write(&root.join("sub/b.txt"), "two"); + let second = fingerprint(root).expect("fingerprint"); + assert_ne!(second, first, "a new file was not counted"); + write(&root.join("sub/b.txt"), "TWO"); + assert_ne!( + fingerprint(root).expect("fingerprint"), + second, + "an edit was not counted" + ); + } + + /// **A LINK IS NOT APPROVABLE.** A plugin file pointing outside the plugin + /// could change without the fingerprint changing, so a plugin holding one + /// cannot be approved and is left out, saying why. + #[test] + fn a_plugin_with_a_symbolic_link_cannot_be_approved() { + let dir = tempfile::tempdir().expect("dir"); + let data = tempfile::tempdir().expect("data"); + let outside = dir.path().join("outside.json"); + std::fs::write(&outside, r#"{"pre_tool_use": ["check"]}"#).expect("outside"); + let project = plugin(dir.path(), Scope::Project); + std::fs::remove_file(project.root.join("hooks.json")).expect("remove"); + #[cfg(unix)] + let linked = std::os::unix::fs::symlink(&outside, project.root.join("hooks.json")); + #[cfg(windows)] + let linked = std::os::windows::fs::symlink_file(&outside, project.root.join("hooks.json")); + if let Err(e) = linked { + eprintln!( + "a_plugin_with_a_symbolic_link_cannot_be_approved: SKIPPED (no symlink: {e})" + ); + return; + } + assert!(fingerprint(&project.root) + .expect_err("a link was fingerprinted") + .contains("symbolic link")); + assert!(approve(data.path(), &project).is_err()); + let (kept, left_out) = usable(data.path(), vec![project]); + assert!(kept.is_empty()); + assert!(left_out[0].contains("symbolic link"), "{left_out:?}"); + } + + /// A store that cannot be read is said, never taken as "nothing approved" + /// silently, nor as "everything". + #[test] + fn a_broken_store_is_reported_not_trusted() { + let dir = tempfile::tempdir().expect("dir"); + let data = tempfile::tempdir().expect("data"); + std::fs::write(data.path().join(FILE), "{not json").expect("broken"); + let project = plugin(dir.path(), Scope::Project); + assert!(matches!(state(data.path(), &project), State::Unknown(_))); + let (kept, left_out) = usable(data.path(), vec![project]); + assert!(kept.is_empty()); + assert!(left_out[0].contains("could not be checked"), "{left_out:?}"); + assert!(approve(data.path(), &plugin(dir.path(), Scope::Project)).is_err()); + } +} diff --git a/src/plugins.rs b/src/plugins.rs index 95856a8..6cab1d5 100644 --- a/src/plugins.rs +++ b/src/plugins.rs @@ -121,13 +121,29 @@ pub fn discover(workspace: &Path) -> Found { discover_in(Some(&project_dir(workspace)), &user_dir()) } -/// The plugins for the process's own directory — for the loaders that are -/// not handed a workspace (skills, hooks). +/// The plugins of `workspace` that may be USED: the operator's own, and a +/// project's only as approved (`crate::plugin_approvals::usable`). Each one +/// left out is a problem line saying how to approve it. +/// +/// Every consumer of a plugin's content goes through this: `session_hooks`, +/// `session_servers`, `session_skills` and `custom_commands::Registry::load` +/// (whose warnings are where the left-out lines are shown, once). #[must_use] -pub fn discover_here() -> Found { +pub fn discover_usable(workspace: &Path) -> Found { + let found = discover(workspace); + let (plugins, left_out) = + crate::plugin_approvals::usable(&crate::admin::AdminConfig::default_dir(), found.plugins); + Found { + plugins, + problems: found.problems.into_iter().chain(left_out).collect(), + } +} + +/// [`discover_usable`] for the process's own directory. +fn usable_here() -> Vec { match std::env::current_dir() { - Ok(cwd) => discover(&cwd), - Err(_) => discover_in(None, &user_dir()), + Ok(cwd) => discover_usable(&cwd).plugins, + Err(_) => discover_in(None, &user_dir()).plugins, } } @@ -415,18 +431,14 @@ impl Plugin { /// Every plugin's skills, for the process's own directory. #[must_use] pub fn session_skills() -> Vec { - discover_here() - .plugins - .iter() - .flat_map(Plugin::skills) - .collect() + usable_here().iter().flat_map(Plugin::skills).collect() } /// Every plugin's hook commands, for the process's own directory. A plugin /// whose `hooks.json` does not parse contributes none, and is traced. #[must_use] pub fn session_hooks() -> crate::hooks::HookConfig { - hooks_of(&discover_here().plugins) + hooks_of(&usable_here()) } /// The hook commands of `plugins`, merged in order. @@ -464,7 +476,9 @@ fn hooks_of(plugins: &[Plugin]) -> crate::hooks::HookConfig { pub(crate) fn session_servers(workspace: &Path) -> (Vec, Vec) { let mut specs = Vec::new(); let mut said = Vec::new(); - for plugin in discover(workspace).plugins { + // Unapproved project plugins are left out here and SAID by + // `custom_commands::Registry::load`, so the line appears once. + for plugin in discover_usable(workspace).plugins { match plugin.servers() { Ok(found) => specs.extend(found), Err(why) => said.push(format!("plugin `{}`: {why}", plugin.manifest.name)), @@ -483,6 +497,12 @@ USAGE: incode plugin add [--project] incode plugin update [name] [--project] incode plugin remove [--project] + incode plugin approve + +`approve` lets a plugin in this workspace's .incode/plugins/ be used, as its +files are now: until then its hooks, servers, skills and commands are left +out, and any change to it needs approving again. Yours in ~/.incode/plugins/ +need no approval. `update` fetches a plugin again from where it was added: a fresh clone of its git URL, or a fresh copy of its folder. With no name, every plugin in @@ -520,11 +540,38 @@ pub fn cli(args: &[String], workspace: &Path) -> Result { ["remove", name] | ["rm", name] => { remove(name, &target).map(|path| format!("removed {}", path.display())) } + ["approve", name] => approve_named( + name, + &discover(workspace), + &crate::admin::AdminConfig::default_dir(), + ), ["-h"] | ["--help"] | ["help"] => Ok(USAGE.to_string()), _ => Err(USAGE.to_string()), } } +/// `incode plugin approve `: approve the project's plugin `name` as its +/// files are now (`crate::plugin_approvals`). +fn approve_named(name: &str, found: &Found, data_dir: &Path) -> Result { + let Some(plugin) = found.plugins.iter().find(|p| p.manifest.name == name) else { + return Err(format!( + "no plugin `{name}` here; `incode plugin list` lists them" + )); + }; + if plugin.scope == Scope::User { + return Ok(format!( + "`{name}` is yours ({}): it needs no approval", + plugin.root.display() + )); + } + crate::plugin_approvals::approve(data_dir, plugin)?; + Ok(format!( + "approved `{name}` as its files are now ({}); a change to it needs approving again\n{}", + plugin.root.display(), + contents(plugin) + )) +} + /// What `incode plugin list` prints. #[must_use] pub fn listing(found: &Found) -> String { @@ -532,10 +579,23 @@ pub fn listing(found: &Found) -> String { if found.plugins.is_empty() { out.push_str("No plugins installed.\n"); } + let data_dir = crate::admin::AdminConfig::default_dir(); for plugin in &found.plugins { let m = &plugin.manifest; + let approval = match crate::plugin_approvals::state(&data_dir, plugin) { + crate::plugin_approvals::State::Own => String::new(), + crate::plugin_approvals::State::Approved => " approved as it is\n".to_string(), + crate::plugin_approvals::State::NotApproved => format!( + " NOT APPROVED, so not used — `incode plugin approve {}` once you have \ + read it\n", + m.name + ), + crate::plugin_approvals::State::Unknown(why) => { + format!(" approval could not be checked: {why}\n") + } + }; out.push_str(&format!( - "{} {} ({}) — {}\n {}\n {}\n", + "{} {} ({}) — {}\n {}\n {}\n{approval}", m.name, if m.version.is_empty() { "-" @@ -937,6 +997,59 @@ mod tests { assert!(found.problems.iter().any(|p| p.contains("broken"))); } + /// **A CLONED REPOSITORY'S PLUGIN IS NOT USED UNTIL APPROVED.** Through + /// the real gate (`discover_usable`, the data dir pointed at a temp + /// folder): left out and said, used once `plugin approve` is run, left + /// out again when its hooks change. The operator's own is used as is. + #[test] + fn a_project_plugin_is_used_only_once_approved_as_it_is() { + let ws = tempfile::tempdir().expect("ws"); + let data = tempfile::tempdir().expect("data"); + let root = plugin(&project_dir(ws.path()), "cloned", "d"); + write(&root.join("hooks.json"), r#"{"pre_tool_use": ["check"]}"#); + let mine = plugin(&data.path().join(PLUGINS_DIR), "mine", "d"); + write(&mine.join("hooks.json"), r#"{"pre_tool_use": ["mine"]}"#); + + let _guard = crate::brief::ENV_LOCK + .lock() + .unwrap_or_else(|e| e.into_inner()); + let saved = std::env::var_os(crate::admin::DATA_DIR_ENV); + std::env::set_var(crate::admin::DATA_DIR_ENV, data.path()); + let names = |found: &Found| -> Vec { + found + .plugins + .iter() + .map(|p| p.manifest.name.clone()) + .collect() + }; + + let before = discover_usable(ws.path()); + let left_out = before.problems.join("\n"); + let approved = approve_named("cloned", &discover(ws.path()), data.path()); + let after = discover_usable(ws.path()); + write( + &root.join("hooks.json"), + r#"{"pre_tool_use": ["curl evil"]}"#, + ); + let changed = discover_usable(ws.path()); + let mine_needs_none = approve_named("mine", &discover(ws.path()), data.path()); + + match saved { + Some(value) => std::env::set_var(crate::admin::DATA_DIR_ENV, value), + None => std::env::remove_var(crate::admin::DATA_DIR_ENV), + } + assert_eq!(names(&before), ["mine"]); + assert!( + left_out.contains("incode plugin approve cloned"), + "{left_out}" + ); + assert!(approved.expect("approve").starts_with("approved `cloned`")); + assert_eq!(names(&after), ["cloned", "mine"]); + assert_eq!(names(&changed), ["mine"], "a changed plugin was still used"); + assert!(mine_needs_none.expect("own").contains("needs no approval")); + assert!(approve_named("nope", &discover(ws.path()), data.path()).is_err()); + } + /// **A CLONED REPOSITORY'S PLUGIN DOES NOT CHECK YOUR PROMPTS.** A /// project plugin's `user_prompt_submit` is dropped — that folder comes /// with whatever was cloned, and the event runs on the first line typed —