From ddfa6f4603e229dfdab441bc57da5c71d108914e Mon Sep 17 00:00:00 2001 From: archae0pteryx Date: Wed, 28 Oct 2026 07:24:29 -0700 Subject: [PATCH 1/3] Refuse a skill or local plugin whose tree holds a symlink that leaves the source at any hop or dangles. --- crates/skillz-harness/src/agent_skills/mod.rs | 21 +- .../src/agents/claude/marketplace.rs | 1 + .../src/agents/codex/plugins.rs | 1 + crates/skillz-harness/src/agents/mod.rs | 3 + crates/skillz-harness/src/agents/plugin.rs | 67 ++++- crates/skillz-harness/src/contained.rs | 238 ++++++++++++++++++ crates/skillz-harness/src/lib.rs | 1 + crates/skillz-harness/src/test_support.rs | 7 + src/app/install/mod.rs | 197 +++++++++++++-- src/app/install/skills.rs | 51 +++- tests/conformance.rs | 1 + 11 files changed, 554 insertions(+), 34 deletions(-) create mode 100644 crates/skillz-harness/src/contained.rs diff --git a/crates/skillz-harness/src/agent_skills/mod.rs b/crates/skillz-harness/src/agent_skills/mod.rs index 1af579a..3297f06 100644 --- a/crates/skillz-harness/src/agent_skills/mod.rs +++ b/crates/skillz-harness/src/agent_skills/mod.rs @@ -16,17 +16,26 @@ pub use validate::{Violation, validate}; /// Frontmatter names of every skill (a directory holding `SKILL.md`) under `root`, recursively, /// sorted and without repeats: the names `npx skills --skill` matches. pub fn skill_names_under(root: &std::path::Path) -> anyhow::Result> { - let mut names = Vec::new(); - crate::fswalk::walk(root, &mut |path, is_dir| { - if is_dir { - names.extend(skill_name(path)); - } - })?; + let mut names: Vec = skills_under(root)? + .into_iter() + .map(|(name, _)| name) + .collect(); names.sort(); names.dedup(); Ok(names) } +/// Each skill under `root`: its frontmatter name and its directory. `skill_names_under` is its names. +pub fn skills_under(root: &std::path::Path) -> anyhow::Result> { + let mut skills = Vec::new(); + crate::fswalk::walk(root, &mut |path, is_dir| { + if is_dir && let Some(name) = skill_name(path) { + skills.push((name, path.to_path_buf())); + } + })?; + Ok(skills) +} + /// The file that makes a directory a skill. pub const SKILL_FILE: &str = "SKILL.md"; diff --git a/crates/skillz-harness/src/agents/claude/marketplace.rs b/crates/skillz-harness/src/agents/claude/marketplace.rs index 1e8ee1b..b625b25 100644 --- a/crates/skillz-harness/src/agents/claude/marketplace.rs +++ b/crates/skillz-harness/src/agents/claude/marketplace.rs @@ -333,6 +333,7 @@ mod tests { marketplace: "mp".into(), plugins: s(&["p1", "p2"]), skills: Default::default(), + refused: vec![], } } diff --git a/crates/skillz-harness/src/agents/codex/plugins.rs b/crates/skillz-harness/src/agents/codex/plugins.rs index e626035..6ba36e2 100644 --- a/crates/skillz-harness/src/agents/codex/plugins.rs +++ b/crates/skillz-harness/src/agents/codex/plugins.rs @@ -768,6 +768,7 @@ mod tests { marketplace: "mp".into(), plugins: vec!["a".into(), "b".into()], skills: Default::default(), + refused: vec![], }; let steps = Codex diff --git a/crates/skillz-harness/src/agents/mod.rs b/crates/skillz-harness/src/agents/mod.rs index 2941fb0..1a33f87 100644 --- a/crates/skillz-harness/src/agents/mod.rs +++ b/crates/skillz-harness/src/agents/mod.rs @@ -26,6 +26,9 @@ pub struct PluginOffer { pub plugins: Vec, /// Skill names supplied by local plugin sources, keyed by plugin name. pub skills: std::collections::BTreeMap>, + /// Plugins refused because a symlink in their local tree resolves outside the source (directly, + /// through a chain, or dangling). Never also in `plugins` or `skills`. + pub refused: Vec, } pub trait Harness { diff --git a/crates/skillz-harness/src/agents/plugin.rs b/crates/skillz-harness/src/agents/plugin.rs index ebfb65f..80bfbeb 100644 --- a/crates/skillz-harness/src/agents/plugin.rs +++ b/crates/skillz-harness/src/agents/plugin.rs @@ -3,6 +3,7 @@ use std::path::{Component, Path, PathBuf}; use anyhow::Context; use super::PluginOffer; +use crate::contained::Containment; use crate::read_optional::read_dir; pub(super) fn skill_names(root: &Path) -> anyhow::Result> { @@ -68,7 +69,8 @@ fn cli_arg(v: &serde_json::Value) -> Option<&str> { /// plugin's skills are, which differs per agent; `manifests` are the plugin manifests to read, /// in order). `None` when the file is missing or names no marketplace; malformed marketplace JSON /// is an error, a malformed plugin manifest is ignored. Option-like (`-x`) names are dropped -/// since they end up as CLI args. +/// since they end up as CLI args. A local plugin whose tree holds a symlink leaving the source +/// is refused whole, since its agent copies that tree. pub(super) fn read_marketplace( path: &Path, root: &Path, @@ -93,7 +95,9 @@ pub(super) fn read_marketplace( .filter_map(|p| cli_arg(&p["name"]).map(|name| (name.to_string(), p))) .collect(); let mut skills = std::collections::BTreeMap::new(); + let mut refused = Vec::new(); let root = root.canonicalize()?; + let mut containment = Containment::new(&root)?; for (name, plugin) in &entries { let source = plugin["source"].as_str().or_else(|| { (plugin["source"]["source"] == "local") @@ -109,6 +113,10 @@ pub(super) fn read_marketplace( if !plugin_root.is_dir() { continue; } + if containment.escapes(&plugin_root)? { + refused.push(name.clone()); + continue; + } skills.insert( name.clone(), offered_skills( @@ -122,8 +130,13 @@ pub(super) fn read_marketplace( } Ok(Some(PluginOffer { marketplace: name.into(), - plugins: entries.into_iter().map(|(name, _)| name).collect(), + plugins: entries + .into_iter() + .map(|(name, _)| name) + .filter(|name| !refused.contains(name)) + .collect(), skills, + refused, })) } @@ -203,7 +216,7 @@ mod tests { use super::*; use crate::agents::{Harness, claude::Claude, codex::Codex}; use crate::model::{Agent, Scope}; - use crate::test_support::skill; + use crate::test_support::{link, skill}; use serde_json::{Value, json}; #[test] @@ -370,12 +383,48 @@ mod tests { "plugins/p/.claude-plugin/plugin.json", json!({"name":"p", "skills":"./extra"}), ); - let claude = offer(&root, Agent::Claude); - let codex = offer(&root, Agent::Codex); - assert!(!claude.skills.contains_key("escape")); - assert!(!codex.skills.contains_key("escape")); - assert_eq!(claude.skills["p"], ["safe"]); - assert!(codex.skills["p"].is_empty()); + for agent in [Agent::Claude, Agent::Codex] { + let offer = offer(&root, agent); + assert!(offer.skills.is_empty()); + assert_eq!(offer.refused, ["p"]); + } + } + + #[test] + fn a_local_plugin_holding_an_escaping_symlink_is_refused_whole() { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path().join("market"); + std::fs::write(dir.path().join("secret"), "").unwrap(); + skill(&root, "plugins/leaky-skill/skills/alpha"); + skill(&root, "plugins/leaky-skill/skills/beta"); + link( + &root, + "plugins/leaky-skill/skills/beta/x", + dir.path().join("secret"), + ); + skill(&root, "plugins/leaky-hooks/skills/gamma"); + link( + &root, + "plugins/leaky-hooks/hooks", + dir.path().join("secret"), + ); + skill(&root, "plugins/clean/skills/delta"); + marketplace( + &root, + json!([ + {"name":"leaky-skill", "source":"./plugins/leaky-skill"}, + {"name":"leaky-hooks", "source":"./plugins/leaky-hooks"}, + {"name":"clean", "source":"./plugins/clean"}, + {"name":"remote", "source":{"source":"github", "repo":"o/r"}} + ]), + ); + for agent in [Agent::Claude, Agent::Codex] { + let offer = offer(&root, agent); + + assert_eq!(offer.plugins, ["clean", "remote"]); + assert_eq!(offer.refused, ["leaky-skill", "leaky-hooks"]); + assert_eq!(offer.skills.keys().collect::>(), ["clean"]); + } } #[test] diff --git a/crates/skillz-harness/src/contained.rs b/crates/skillz-harness/src/contained.rs new file mode 100644 index 0000000..83e8543 --- /dev/null +++ b/crates/skillz-harness/src/contained.rs @@ -0,0 +1,238 @@ +//! Whether a source tree's symlinks stay inside it. npx, claude and codex copy what a skill or +//! plugin directory links to, so a link that leaves the source would carry the user's own files +//! into an install, and one that only passes outside could be repointed between check and copy. + +use std::collections::{HashMap, HashSet}; +use std::ffi::OsString; +use std::path::{Path, PathBuf}; + +use anyhow::Context; + +/// More symlinks than this while resolving one path is a loop, as the OS treats it. +const MAX_HOPS: usize = 40; + +/// Symlinks under a source tree that leave it. One per scan; memoised by canonical directory. +pub struct Containment { + root: PathBuf, + /// The real directories each scanned directory's entries reach; `None` for a directory with an + /// entry that leaves the root. + reached: HashMap>>, +} + +impl Containment { + pub fn new(root: &Path) -> anyhow::Result { + let root = root + .canonicalize() + .with_context(|| format!("reading {}", root.display()))?; + Ok(Containment { + root, + reached: HashMap::new(), + }) + } + + /// Whether `dir` or anything under it is a symlink that leaves the root at any hop, dangles, + /// or links to a directory that does. + pub fn escapes(&mut self, dir: &Path) -> anyhow::Result { + let Some(start) = self.resolve(&self.root, dir)? else { + return Ok(true); + }; + let mut seen = HashSet::new(); + let mut pending = vec![start]; + while let Some(dir) = pending.pop() { + if !seen.insert(dir.clone()) { + continue; + } + match self.reached_from(&dir)? { + Some(dirs) => pending.extend(dirs.iter().cloned()), + None => return Ok(true), + } + } + Ok(false) + } + + fn reached_from(&mut self, dir: &Path) -> anyhow::Result<&Option>> { + if !self.reached.contains_key(dir) { + let reached = self.scan(dir)?; + self.reached.insert(dir.to_path_buf(), reached); + } + Ok(&self.reached[dir]) + } + + fn scan(&self, dir: &Path) -> anyhow::Result>> { + let mut dirs = vec![]; + let entries = + std::fs::read_dir(dir).with_context(|| format!("reading {}", dir.display()))?; + for entry in entries { + match self.resolve(dir, Path::new(&entry?.file_name()))? { + Some(real) if real.is_dir() => dirs.push(real), + Some(_) => {} + None => return Ok(None), + } + } + Ok(Some(dirs)) + } + + /// Where `path`, taken from the real directory `from`, really is, following one symlink at a + /// time as the OS does. `None` when a step lands outside the root other than on the way down + /// to it, a link dangles, or the links loop. + fn resolve(&self, from: &Path, path: &Path) -> anyhow::Result> { + let mut real = from.to_path_buf(); + let mut steps = reversed_steps(path); + let mut hops = 0; + while let Some(step) = steps.pop() { + if step == "." { + continue; + } + if step == ".." { + real.pop(); + continue; + } + let next = real.join(&step); + let kind = match std::fs::symlink_metadata(&next) { + Ok(metadata) => metadata.file_type(), + Err(error) + if matches!( + error.kind(), + std::io::ErrorKind::NotFound | std::io::ErrorKind::NotADirectory + ) => + { + return Ok(None); + } + Err(error) => { + return Err(error).with_context(|| format!("reading {}", next.display())); + } + }; + if kind.is_symlink() { + hops += 1; + if hops > MAX_HOPS { + return Ok(None); + } + let target = std::fs::read_link(&next) + .with_context(|| format!("reading {}", next.display()))?; + steps.extend(reversed_steps(&target)); + } else if self.within_reach(&next) { + real = next; + } else { + return Ok(None); + } + } + Ok(real.starts_with(&self.root).then_some(real)) + } + + /// Inside the root, or one of the real directories above it that a path down to it passes. + fn within_reach(&self, real: &Path) -> bool { + real.starts_with(&self.root) || self.root.starts_with(real) + } +} + +fn reversed_steps(path: &Path) -> Vec { + path.components() + .rev() + .map(|step| step.as_os_str().to_owned()) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::test_support::{link, skill}; + + /// A source at `/src` holding `skill/`, and a sibling directory `/outside` with a file. + fn source() -> (tempfile::TempDir, PathBuf, PathBuf) { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path().join("src"); + let outside = dir.path().join("outside"); + skill(&root, "skill"); + std::fs::create_dir_all(&outside).unwrap(); + std::fs::write(outside.join("file"), "").unwrap(); + (dir, root, outside) + } + + fn skill_escapes(root: &Path) -> bool { + Containment::new(root) + .unwrap() + .escapes(&root.join("skill")) + .unwrap() + } + + #[test] + fn a_link_straight_out_of_the_source_escapes() { + let (_dir, root, outside) = source(); + link(&root, "skill/x", outside.join("file")); + + assert!(skill_escapes(&root)); + } + + #[test] + fn a_chain_whose_last_link_leaves_the_source_escapes() { + let (_dir, root, outside) = source(); + link(&root, "skill/a", "b"); + link(&root, "skill/b", outside.join("file")); + + assert!(skill_escapes(&root)); + } + + #[test] + fn a_chain_that_passes_outside_and_comes_back_escapes() { + let (_dir, root, outside) = source(); + std::fs::write(root.join("z"), "").unwrap(); + link(&outside, "y", root.join("z")); + link(&root, "skill/a", outside.join("y")); + + assert!(skill_escapes(&root)); + } + + #[test] + fn a_dangling_link_escapes() { + let (_dir, root, _) = source(); + link(&root, "skill/a", "missing"); + + assert!(skill_escapes(&root)); + } + + #[test] + fn links_that_resolve_through_each_other_forever_escape_like_a_dangling_link() { + let (_dir, root, _) = source(); + link(&root, "skill/a", "b"); + link(&root, "skill/b", "a"); + + assert!(skill_escapes(&root)); + } + + #[test] + fn a_link_to_a_directory_holding_an_escaping_link_escapes() { + let (_dir, root, outside) = source(); + link(&root, "shared/x", outside.join("file")); + link(&root, "skill/lib", "../shared"); + + assert!(skill_escapes(&root)); + } + + #[test] + fn links_that_stay_inside_the_source_do_not_escape() { + let (_dir, root, _) = source(); + std::fs::create_dir_all(root.join("shared")).unwrap(); + std::fs::write(root.join("shared/file"), "").unwrap(); + link(&root, "skill/ref", "../shared/file"); + link(&root, "skill/absolute", root.join("shared")); + + assert!(!skill_escapes(&root)); + } + + #[test] + fn a_link_loop_is_scanned_once_and_does_not_escape() { + let (_dir, root, _) = source(); + link(&root, "skill/loop", ".."); + + assert!(!skill_escapes(&root)); + } + + #[test] + fn a_skill_directory_that_is_itself_an_escaping_link_escapes() { + let (_dir, root, outside) = source(); + std::fs::remove_dir_all(root.join("skill")).unwrap(); + link(&root, "skill", &outside); + + assert!(skill_escapes(&root)); + } +} diff --git a/crates/skillz-harness/src/lib.rs b/crates/skillz-harness/src/lib.rs index 4db6a7a..b30dcd4 100644 --- a/crates/skillz-harness/src/lib.rs +++ b/crates/skillz-harness/src/lib.rs @@ -5,6 +5,7 @@ pub mod action; pub mod agent_skills; pub mod agents; pub mod clone; +pub mod contained; pub mod cost; pub mod env; pub mod fswalk; diff --git a/crates/skillz-harness/src/test_support.rs b/crates/skillz-harness/src/test_support.rs index f0ac14e..a1ab643 100644 --- a/crates/skillz-harness/src/test_support.rs +++ b/crates/skillz-harness/src/test_support.rs @@ -107,6 +107,13 @@ pub fn skill(root: &Path, rel: &str) { ); } +/// A symlink at `root/rel` to `target`, with the directories above it. +pub fn link(root: &Path, rel: &str, target: impl AsRef) { + let path = root.join(rel); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::os::unix::fs::symlink(target, path).unwrap(); +} + pub fn skills_fixture(root: &Path) { for rel in [ "skills/tdd", diff --git a/src/app/install/mod.rs b/src/app/install/mod.rs index b860567..4143d87 100644 --- a/src/app/install/mod.rs +++ b/src/app/install/mod.rs @@ -10,7 +10,6 @@ use std::path::{Path, PathBuf}; use crate::app::prompt::Prompter; use crate::app::review::{Group, PlanView, Verdict}; use skillz_harness::action::{self, Action}; -use skillz_harness::agent_skills::skill_names_under; use skillz_harness::agents::{Harness, PluginOffer, adapter_for}; use skillz_harness::env::Env; use skillz_harness::model::{Agent, Scope}; @@ -94,7 +93,15 @@ fn plan(ctx: &Ctx, req: &InstallRequest, tree: &Tree) -> anyhow::Result { plan.lines.extend(lines); plan.steps.extend(steps); @@ -109,6 +116,7 @@ fn plan(ctx: &Ctx, req: &InstallRequest, tree: &Tree) -> anyhow::Result anyhow::Result( + ctx: &Ctx<'a>, + req: &InstallRequest, + tree: &Tree, + agent: Agent, +) -> anyhow::Result> { + let Some(adapter) = adapter_for(ctx.adapters, agent) else { + return Ok(None); + }; + Ok(adapter + .plugin_offer(tree.src, req.scope)? + .map(|offer| (adapter, offer))) +} + +/// The plan line for what `who` does not install because a symlink in it leaves the source. +fn escaping_symlinks(who: &str, names: &[String]) -> String { + format!( + "{who}: not installed, a symlink in them leaves the source: {}", + names.join(", ") + ) +} + /// What one agent does with the plugins a source offers. enum AgentPlugins { - /// The source offers it none, so its skills go through `npx skills`. + /// The source offers it none it can install, so its skills go through `npx skills`. Unoffered, /// The user picked no plugins. Declined, @@ -137,14 +168,13 @@ fn agent_plugins( ctx: &Ctx, req: &InstallRequest, tree: &Tree, - agent: Agent, + adapter: &dyn Harness, + offer: &PluginOffer, ) -> anyhow::Result { - let Some(adapter) = adapter_for(ctx.adapters, agent) else { - return Ok(AgentPlugins::Unoffered); - }; - let Some(offer) = adapter.plugin_offer(tree.src, req.scope)? else { + if offer.plugins.is_empty() { return Ok(AgentPlugins::Unoffered); - }; + } + let agent = adapter.agent(); let chosen: Vec = match &req.selection { SkillSelection::Interactive => { let title = format!("{agent} plugins to install"); @@ -156,9 +186,9 @@ fn agent_plugins( } SkillSelection::All => offer.plugins.clone(), SkillSelection::Patterns(_) => { - let available = skill_names_under(tree.src)?; + let available = skills::source_skills(tree.src)?.offered; let selected = skills::select_skills(&available, &req.selection); - if selected.is_empty() || !left_out(&offer, &selected).is_empty() { + if selected.is_empty() || !left_out(offer, &selected).is_empty() { return Ok(AgentPlugins::Unoffered); } offer @@ -177,7 +207,7 @@ fn agent_plugins( if chosen.is_empty() { return Ok(AgentPlugins::Unoffered); } - let named: Vec = chosen.iter().map(|name| describe(&offer, name)).collect(); + let named: Vec = chosen.iter().map(|name| describe(offer, name)).collect(); let mut lines = vec![format!( "{agent}: {} from {}", named.join(", "), @@ -189,7 +219,7 @@ fn agent_plugins( .iter() .all(|plugin| offer.skills.contains_key(plugin)); if req.selection == SkillSelection::All && known { - let skipped = left_out(&offer, &skill_names_under(tree.src)?); + let skipped = left_out(offer, &skills::source_skills(tree.src)?.offered); if !skipped.is_empty() { lines.push(format!( "{agent}: not installed, no plugin supplies them (name them with --skill): {}", @@ -198,7 +228,7 @@ fn agent_plugins( } } Ok( - match adapter.plan_add_source(&offer, &chosen, tree.source, req.scope, ctx.env) { + match adapter.plan_add_source(offer, &chosen, tree.source, req.scope, ctx.env) { Ok(steps) => AgentPlugins::Install { lines, steps }, Err(refusal) => AgentPlugins::Refused(format!("{agent}: {refusal:#}")), }, @@ -275,6 +305,7 @@ mod tests { .iter() .map(|(plugin, names)| (plugin.to_string(), s(names))) .collect(), + refused: vec![], } } @@ -696,6 +727,144 @@ mod tests { assert!(runner.calls().is_empty()); } + /// A link at `root/rel` to a file beside the source, outside it. + fn escaping_link(root: &Path, rel: &str) { + let secret = root.parent().unwrap().join("secret"); + std::fs::write(&secret, "").unwrap(); + link(root, rel, secret); + } + + fn leaky_skills_fixture(root: &Path) { + skills_fixture(root); + skill(root, "skills/leaky"); + escaping_link(root, "skills/leaky/secret"); + } + + fn leaky_plugins_fixture(root: &Path) { + skill(root, "plugins/p1/skills/alpha"); + escaping_link(root, "plugins/p1/skills/alpha/secret"); + skill(root, "plugins/p2/skills/beta"); + std::fs::create_dir_all(root.join(".claude-plugin")).unwrap(); + std::fs::write( + root.join(".claude-plugin/marketplace.json"), + r#"{"name":"mp","plugins":[{"name":"p1","source":"./plugins/p1"},{"name":"p2","source":"./plugins/p2"}]}"#, + ) + .unwrap(); + } + + #[test] + fn a_skill_with_an_escaping_symlink_is_not_offered_and_is_shown_skipped() { + let fx = project_with(leaky_skills_fixture); + let runner = FakeRunner::new(|_| {}); + let prompter = ScriptedPrompter::new(&[0], true); + let request = req(&fx, "repo", SkillSelection::Interactive); + + run_install(&fx, &request, &runner, &prompter).unwrap(); + + assert_eq!( + prompter.offered.borrow()[0], + s(&["caveman-commit", "git-commit", "tdd", "zeta"]) + ); + assert_eq!( + prompter.plans.borrow()[0], + [(Group::Install, 1), (Group::Skip, 1)] + ); + } + + #[test] + fn all_leaves_a_skill_with_an_escaping_symlink_out_of_the_npx_arguments() { + let fx = project_with(leaky_skills_fixture); + let runner = FakeRunner::new(|_| {}); + let request = req(&fx, "repo", SkillSelection::All); + + run_install(&fx, &request, &runner, &ScriptedPrompter::new(&[], true)).unwrap(); + + let calls = runner.calls(); + assert_eq!(calls.len(), 1); + assert!(calls[0].1.contains(&"tdd".to_string())); + assert!(!calls[0].1.contains(&"leaky".to_string())); + } + + #[test] + fn naming_only_a_skill_with_an_escaping_symlink_fails_and_runs_nothing() { + let fx = project_with(leaky_skills_fixture); + let runner = FakeRunner::new(|_| {}); + let prompter = ScriptedPrompter::new(&[], true); + let request = req(&fx, "repo", SkillSelection::Patterns(s(&["leaky"]))); + + let result = run_install(&fx, &request, &runner, &prompter); + + assert!(result.is_err()); + assert!(runner.calls().is_empty()); + assert!(prompter.plans.borrow().is_empty()); + } + + #[test] + fn a_name_carried_by_one_escaping_directory_is_refused_for_all_of_them() { + let fx = project_with(|root| { + skill(root, "skills/tdd"); + skill(root, "clean/dup"); + skill(root, "leaky/dup"); + escaping_link(root, "leaky/dup/secret"); + }); + let runner = FakeRunner::new(|_| {}); + let prompter = ScriptedPrompter::new(&[], true); + let request = req(&fx, "repo", SkillSelection::All); + + run_install(&fx, &request, &runner, &prompter).unwrap(); + + assert!(!runner.calls()[0].1.contains(&"dup".to_string())); + assert_eq!( + prompter.plans.borrow()[0], + [(Group::Install, 1), (Group::Skip, 1)] + ); + } + + #[test] + fn a_plugin_with_an_escaping_skill_is_refused_and_its_sibling_still_installs() { + let fx = project_with(leaky_plugins_fixture); + let runner = FakeRunner::new(|_| {}); + let prompter = ScriptedPrompter::new(&[0], true); + let request = req(&fx, "repo", SkillSelection::Interactive); + + run_install(&fx, &request, &runner, &prompter).unwrap(); + + assert_eq!(prompter.offered.borrow()[0], s(&["p2"])); + assert_eq!( + prompter.plans.borrow()[0], + [(Group::Install, 1), (Group::Skip, 1)] + ); + assert_eq!( + runner.calls()[1].1, + s(&["plugin", "install", "p2@mp", "--scope", "local"]) + ); + } + + #[test] + fn a_source_whose_every_plugin_and_skill_is_refused_fails_and_runs_nothing() { + let fx = project_with(|root| { + leaky_plugins_fixture(root); + std::fs::remove_dir_all(root.join("plugins/p2")).unwrap(); + std::fs::write( + root.join(".claude-plugin/marketplace.json"), + r#"{"name":"mp","plugins":[{"name":"p1","source":"./plugins/p1"}]}"#, + ) + .unwrap(); + }); + let runner = FakeRunner::new(|_| {}); + let prompter = ScriptedPrompter::new(&[0], true); + let request = InstallRequest { + agents: vec![Agent::Claude, Agent::Codex], + ..req(&fx, "repo", SkillSelection::Interactive) + }; + + let result = run_install(&fx, &request, &runner, &prompter); + + assert!(result.is_err()); + assert!(runner.calls().is_empty()); + assert!(prompter.plans.borrow().is_empty()); + } + #[test] fn a_source_with_nothing_installable_is_an_error() { let fx = project_with(|root| std::fs::create_dir_all(root).unwrap()); diff --git a/src/app/install/skills.rs b/src/app/install/skills.rs index 3d4b84c..7cbf2ba 100644 --- a/src/app/install/skills.rs +++ b/src/app/install/skills.rs @@ -1,17 +1,49 @@ +use std::collections::BTreeSet; +use std::path::Path; + use crate::app::matcher::pattern_matches; use crate::app::prompt::Prompter; use skillz_harness::action::Action; -use skillz_harness::agent_skills::skill_names_under; +use skillz_harness::agent_skills::skills_under; +use skillz_harness::contained::Containment; use skillz_harness::model::Agent; use skillz_harness::npx::commands; use super::global::confirm_duplicates; -use super::{Ctx, InstallRequest, SkillSelection, Tree}; +use super::{Ctx, InstallRequest, SkillSelection, Tree, escaping_symlinks}; /// The `npx skills add` step for the skills the user picks from the tree. pub(super) struct SkillsPlan { pub line: String, pub step: Action, + /// The skills refused for a symlink that leaves the source, when there are any. + pub skipped: Option, +} + +/// The skill names under a tree: those to offer, and those refused because a directory carrying +/// the name holds a symlink that leaves the source. +pub(super) struct SourceSkills { + pub offered: Vec, + pub refused: Vec, +} + +pub(super) fn source_skills(src: &Path) -> anyhow::Result { + let mut containment = Containment::new(src)?; + let mut offered = BTreeSet::new(); + let mut refused = BTreeSet::new(); + for (name, dir) in skills_under(src)? { + if containment.escapes(&dir)? { + refused.insert(name); + } else { + offered.insert(name); + } + } + // `npx skills --skill` picks by name, not directory, so one escaping copy refuses the name. + offered.retain(|name| !refused.contains(name)); + Ok(SourceSkills { + offered: offered.into_iter().collect(), + refused: refused.into_iter().collect(), + }) } /// Pick skills found under the tree to install with `npx skills add `. `None` when the @@ -22,7 +54,10 @@ pub(super) fn plan( tree: &Tree, agents: &[Agent], ) -> anyhow::Result> { - let names = skill_names_under(tree.src)?; + let SourceSkills { + offered: names, + refused, + } = source_skills(tree.src)?; anyhow::ensure!( !names.is_empty(), "found no marketplace, plugin or skills in {}", @@ -35,10 +70,15 @@ pub(super) fn plan( return Ok(None); } let (program, args) = commands::add_command(tree.source, &chosen, agents, req.scope); - let names: Vec = agents.iter().map(ToString::to_string).collect(); + let agents = agents + .iter() + .map(ToString::to_string) + .collect::>() + .join(", "); Ok(Some(SkillsPlan { - line: format!("{}: skills {}", names.join(", "), chosen.join(", ")), + line: format!("{agents}: skills {}", chosen.join(", ")), step: Action::required(&program, args, &ctx.env.project), + skipped: (!refused.is_empty()).then(|| escaping_symlinks(&agents, &refused)), })) } @@ -87,6 +127,7 @@ pub(super) fn select_skills(names: &[String], selection: &SkillSelection) -> Vec mod tests { use super::*; use crate::app::install::test_support::*; + use skillz_harness::agent_skills::skill_names_under; /// Run the installer on the fixture's `repo/`, handing npx the source `"o/r"`. fn run( diff --git a/tests/conformance.rs b/tests/conformance.rs index 2a6f389..b183e28 100644 --- a/tests/conformance.rs +++ b/tests/conformance.rs @@ -86,6 +86,7 @@ impl Harness for Fake { marketplace: "mp".into(), plugins: vec![PLUGIN.into()], skills: Default::default(), + refused: vec![], })) } fn plan_add_source( From daeea640489b216f9622e749db0770838f60299e Mon Sep 17 00:00:00 2001 From: archae0pteryx Date: Wed, 28 Oct 2026 07:35:05 -0700 Subject: [PATCH 2/3] Refuse a local plugin whose source path is itself a symlink that leaves the source or dangles. --- crates/skillz-harness/src/agents/plugin.rs | 88 ++++++++++++++++++++-- 1 file changed, 80 insertions(+), 8 deletions(-) diff --git a/crates/skillz-harness/src/agents/plugin.rs b/crates/skillz-harness/src/agents/plugin.rs index 80bfbeb..4ae0d2d 100644 --- a/crates/skillz-harness/src/agents/plugin.rs +++ b/crates/skillz-harness/src/agents/plugin.rs @@ -107,16 +107,22 @@ pub(super) fn read_marketplace( let Some(source) = source.filter(|source| source.starts_with("./")) else { continue; }; + // Checked before `contained_path`, which cannot tell a source linked out of the root or + // dangling from one that is simply missing. + let linked = root.join(source); + if lexically_inside(source) + && (linked.exists() || through_a_link(&root, source)) + && containment.escapes(&linked)? + { + refused.push(name.clone()); + continue; + } let Some(plugin_root) = contained_path(&root, source)? else { continue; }; if !plugin_root.is_dir() { continue; } - if containment.escapes(&plugin_root)? { - refused.push(name.clone()); - continue; - } skills.insert( name.clone(), offered_skills( @@ -128,6 +134,7 @@ pub(super) fn read_marketplace( )?, ); } + skills.retain(|name, _| !refused.contains(name)); Ok(Some(PluginOffer { marketplace: name.into(), plugins: entries @@ -187,12 +194,24 @@ pub(super) fn declared_skill_paths(doc: &serde_json::Value) -> Option bool { + Path::new(relative) + .components() + .all(|part| matches!(part, Component::Normal(_) | Component::CurDir)) +} + +/// Whether a symlink sits on `relative`'s way down from `root`, dangling or not. +fn through_a_link(root: &Path, relative: &str) -> bool { + let mut path = root.to_path_buf(); + Path::new(relative).components().any(|part| { + path.push(part); + std::fs::symlink_metadata(&path).is_ok_and(|metadata| metadata.is_symlink()) + }) +} + /// Reject lexical escapes and symlinks that resolve outside the source being inspected. fn contained_path(root: &Path, relative: &str) -> anyhow::Result> { - if Path::new(relative) - .components() - .any(|part| !matches!(part, Component::Normal(_) | Component::CurDir)) - { + if !lexically_inside(relative) { return Ok(None); } let path = root.join(relative); @@ -385,6 +404,59 @@ mod tests { ); for agent in [Agent::Claude, Agent::Codex] { let offer = offer(&root, agent); + assert!(offer.plugins.is_empty()); + assert!(offer.skills.is_empty()); + assert_eq!(offer.refused, ["escape", "p"]); + } + } + + #[test] + fn a_plugin_source_reached_through_an_escaping_or_dangling_link_is_refused() { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path().join("market"); + let outside = dir.path().join("outside"); + skill(&outside, "p/skills/secret"); + skill(&root, "plugins/ok/skills/safe"); + link(&root, "plugins/lnk", &outside); + link(&root, "plugins/dang", "nowhere"); + link(&root, "middle", &outside); + marketplace( + &root, + json!([ + {"name":"lnk", "source":"./plugins/lnk"}, + {"name":"dang", "source":"./plugins/dang"}, + {"name":"viaobj", "source":{"source":"local", "path":"./plugins/lnk"}}, + {"name":"mid", "source":"./middle/p"}, + {"name":"missing", "source":"./plugins/missing"}, + {"name":"ok", "source":"./plugins/ok"} + ]), + ); + for agent in [Agent::Claude, Agent::Codex] { + let offer = offer(&root, agent); + + assert_eq!(offer.plugins, ["missing", "ok"]); + assert_eq!(offer.refused, ["lnk", "dang", "viaobj", "mid"]); + assert_eq!(offer.skills.keys().collect::>(), ["ok"]); + } + } + + #[test] + fn a_name_refused_for_one_entry_is_not_also_offered_by_another() { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path().join("market"); + skill(&root, "plugins/clean/skills/safe"); + link(&root, "plugins/leaky", "nowhere"); + marketplace( + &root, + json!([ + {"name":"p", "source":"./plugins/clean"}, + {"name":"p", "source":"./plugins/leaky"} + ]), + ); + for agent in [Agent::Claude, Agent::Codex] { + let offer = offer(&root, agent); + + assert!(offer.plugins.is_empty()); assert!(offer.skills.is_empty()); assert_eq!(offer.refused, ["p"]); } From 80fa8df223ecfcab59237c5fb8f0f4eac941fa42 Mon Sep 17 00:00:00 2001 From: archae0pteryx Date: Wed, 28 Oct 2026 07:39:52 -0700 Subject: [PATCH 3/3] Skip a plugin source that is a file inside the source again instead of failing the whole offer. --- crates/skillz-harness/src/agents/plugin.rs | 27 ++++++++++++++++++++++ crates/skillz-harness/src/contained.rs | 3 +++ 2 files changed, 30 insertions(+) diff --git a/crates/skillz-harness/src/agents/plugin.rs b/crates/skillz-harness/src/agents/plugin.rs index 4ae0d2d..9e4aae1 100644 --- a/crates/skillz-harness/src/agents/plugin.rs +++ b/crates/skillz-harness/src/agents/plugin.rs @@ -440,6 +440,33 @@ mod tests { } } + #[test] + fn a_plugin_source_that_is_a_file_is_skipped_unless_a_link_to_it_leaves_the_source() { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path().join("market"); + std::fs::write(dir.path().join("secret"), "").unwrap(); + skill(&root, "plugins/ok/skills/safe"); + std::fs::write(root.join("plugins/afile"), "").unwrap(); + link(&root, "plugins/flink", "afile"); + link(&root, "plugins/outlink", dir.path().join("secret")); + marketplace( + &root, + json!([ + {"name":"file", "source":"./plugins/afile"}, + {"name":"flink", "source":"./plugins/flink"}, + {"name":"outlink", "source":"./plugins/outlink"}, + {"name":"ok", "source":"./plugins/ok"} + ]), + ); + for agent in [Agent::Claude, Agent::Codex] { + let offer = offer(&root, agent); + + assert_eq!(offer.plugins, ["file", "flink", "ok"]); + assert_eq!(offer.refused, ["outlink"]); + assert_eq!(offer.skills.keys().collect::>(), ["ok"]); + } + } + #[test] fn a_name_refused_for_one_entry_is_not_also_offered_by_another() { let dir = tempfile::tempdir().unwrap(); diff --git a/crates/skillz-harness/src/contained.rs b/crates/skillz-harness/src/contained.rs index 83e8543..ca1eb9c 100644 --- a/crates/skillz-harness/src/contained.rs +++ b/crates/skillz-harness/src/contained.rs @@ -36,6 +36,9 @@ impl Containment { let Some(start) = self.resolve(&self.root, dir)? else { return Ok(true); }; + if !start.is_dir() { + return Ok(false); + } let mut seen = HashSet::new(); let mut pending = vec![start]; while let Some(dir) = pending.pop() {