trusty_code/plugins/mod.rs
1//! Claude Code plugin ingestion, Phase 1: local-directory agents + skills
2//! only (issue #3539).
3//!
4//! Why: Claude Code plugins package reusable agents/skills (and, in later
5//! phases, commands/hooks/MCP servers) for drop-in use by a harness. tcode
6//! already parses the exact on-disk formats a plugin ships agents
7//! (`.md`+frontmatter, see `agents::md_loader`) and skills (`SKILL.md`,
8//! progressive disclosure, see `crate::skills`) in — so Phase 1 is a
9//! discovery + namespacing layer over those existing parsers, not a new
10//! format. Phase 1 is deliberately narrow (#3539's locked scope): a plugin
11//! is a LOCAL directory under `<project_root>/.claude/plugins/<plugin>/`
12//! (no marketplace/git fetch), and only `agents/` + `skills/` are ingested
13//! (no commands/hooks/MCP — later phases). Plugin entries are ADDITIVE
14//! ONLY: they are namespaced `<plugin>:<name>` in every surface that lists
15//! or resolves them, so they can never collide with — and therefore never
16//! override — an unnamespaced project or embedded/bundled name.
17//! What: [`PluginRoot`] is one discovered plugin (resolved name + its
18//! agents/skills directories, honoring `.claude-plugin/plugin.json`'s
19//! `name`/`agents`/`skills` overrides when present). [`discover_plugin_roots`]
20//! scans `<project_root>/.claude/plugins/` for plugin subdirectories.
21//! [`project_root_two_levels_up`] is the shared seam every integration point
22//! (`agents::protocol::agents_list`, `agents::resolve_agent`,
23//! `skills::protocol::skills_list`, `skills::FsSkillResolver`) uses to
24//! recover a project root from the `.claude/agents` or `.claude/skills`
25//! directory it already holds, without threading a new parameter through
26//! every call site. Submodules [`agents`] and [`skills`] do the actual
27//! agent/skill discovery, namespacing, and resolution.
28//! Test: `tests::*` here cover manifest parsing (present/absent/malformed,
29//! name/agents/skills overrides, later-phase key detection) and
30//! `discover_plugin_roots` scanning; `agents::tests`/`skills::tests` cover
31//! the per-domain ingestion contracts.
32//!
33//! ## Security: plugin content is HOSTILE input (issue #3547)
34//!
35//! Everything under `.claude/plugins/` — `plugin.json`, agent/skill
36//! directory names, and frontmatter content — is THIRD-PARTY, not authored
37//! by the project owner the way `.claude/agents|skills/` is. Two path-join
38//! sites are therefore treated as adversarial and validated BEFORE any
39//! filesystem join, exactly like `agents::protocol::validate_agent_name`
40//! already treats a caller-supplied catalog name:
41//! `load_plugin_root` validates a `plugin.json` `agents`/`skills`
42//! override (a `PathBuf::join` of an absolute or `..`-bearing override
43//! escapes `plugin_dir` outright — code-critic PR #3547 review, CRITICAL 1)
44//! and [`is_valid_namespaced_name`] validates every caller-supplied
45//! `<plugin>:<local>` dispatch name (a raw local segment containing `/` or
46//! `..` escapes the plugin's `agents_dir`/`skills_dir` — CRITICAL 2 / HIGH
47//! 3) before [`agents::find_plugin_agent_config`]/
48//! [`skills::resolve_plugin_skill_body`] ever join it onto a directory.
49//! A third, independent hole (re-review, CRITICAL 5, CWE-59): the
50//! DIRECTORY-path and NAME guards above say nothing about the LEAF FILE a
51//! validated name resolves to — `std::fs::read_to_string`,
52//! `Path::is_dir`/`is_file` all FOLLOW symlinks, so a plugin can ship
53//! `agents/leak.md` (or a `skills/<name>/SKILL.md`, or even `skills/<name>`
54//! itself) as a symlink to an arbitrary host file/directory (e.g.
55//! `~/.ssh/id_rsa`); discovery would read the TARGET's content as that
56//! agent's system prompt or skill body, which then reaches an LLM prompt
57//! verbatim once dispatched. [`path_is_contained`] closes this: every
58//! point a discovered `.md`/`SKILL.md` file's content is actually read
59//! (`agents::load_plugin_agent`, `skills::discover_one_plugin_skills`,
60//! `skills::resolve_plugin_skill_body`) canonicalizes the full leaf path
61//! and requires it stay contained within the already-validated
62//! `agents_dir`/`skills_dir` — since `canonicalize` resolves every symlink
63//! in the path, not just the final component, one check catches a
64//! symlinked leaf file, a symlinked intermediate directory, or both.
65//!
66//! [`PluginRoot`]: crate::plugins::PluginRoot
67//! [`discover_plugin_roots`]: crate::plugins::discover_plugin_roots
68//! [`project_root_two_levels_up`]: crate::plugins::project_root_two_levels_up
69//! [`is_valid_namespaced_name`]: crate::plugins::is_valid_namespaced_name
70//! [`agents::find_plugin_agent_config`]: crate::plugins::agents::find_plugin_agent_config
71//! [`skills::resolve_plugin_skill_body`]: crate::plugins::skills::resolve_plugin_skill_body
72//! [`path_is_contained`]: crate::plugins::path_is_contained
73
74pub mod agents;
75pub mod skills;
76
77use std::path::{Path, PathBuf};
78
79use serde::Deserialize;
80
81/// The `.claude/plugins` directory name, relative to a project root.
82const PLUGINS_DIRNAME: &str = "plugins";
83
84/// `.claude-plugin/plugin.json` keys Phase 1 recognizes as later-phase
85/// surfaces (commands/hooks/MCP) — present but intentionally unimplemented,
86/// per #3539's scope.
87///
88/// Why: names the exact set `load_plugin_root` checks for so a plugin
89/// author sees a debug log explaining why e.g. its `hooks` declaration had
90/// no effect, rather than silent nothing.
91const LATER_PHASE_MANIFEST_KEYS: &[&str] = &["commands", "hooks", "mcpServers", "mcp"];
92
93/// One discovered plugin: its resolved name and the directories its agents
94/// and skills live under.
95///
96/// Why: the resolved `name` (manifest `name:`, falling back to the
97/// directory name) is what every namespaced `<plugin>:<local-name>` entry
98/// uses — it may differ from the on-disk subdirectory name, so callers must
99/// always go through this struct rather than re-deriving a plugin's
100/// identity from its path.
101/// What: `root` is the plugin's own directory
102/// (`<project_root>/.claude/plugins/<dir>`); `agents_dir`/`skills_dir` are
103/// already-joined, ready-to-scan paths (manifest overrides applied, or the
104/// `agents`/`skills` convention when absent) — neither is guaranteed to
105/// exist on disk.
106/// Test: `tests::discover_plugin_roots_*`.
107#[derive(Debug, Clone)]
108pub struct PluginRoot {
109 /// Resolved plugin name — manifest `name:`, or the directory name.
110 pub name: String,
111 /// The plugin's own root directory.
112 pub root: PathBuf,
113 /// Where this plugin's `*.md` agents live.
114 pub agents_dir: PathBuf,
115 /// Where this plugin's `<skill>/SKILL.md` skills live.
116 pub skills_dir: PathBuf,
117}
118
119/// The subset of `.claude-plugin/plugin.json` Phase 1 understands.
120///
121/// Why: a plugin manifest is optional (#3539 — a plugin with no manifest
122/// falls back to the directory name + the `agents`/`skills` convention);
123/// when present, Phase 1 only acts on `name`/`agents`/`skills` — every
124/// other key (description, version, author, and the later-phase
125/// `commands`/`hooks`/`mcpServers`) is captured in `other` purely so
126/// `load_plugin_root` can detect and log the later-phase ones, never to
127/// drive behavior.
128/// Test: `tests::discover_plugin_roots_honors_manifest_name_override`,
129/// `tests::discover_plugin_roots_honors_path_overrides`,
130/// `tests::discover_plugin_roots_warns_on_later_phase_keys`.
131#[derive(Debug, Default, Deserialize)]
132struct PluginManifest {
133 #[serde(default)]
134 name: Option<String>,
135 #[serde(default)]
136 agents: Option<String>,
137 #[serde(default)]
138 skills: Option<String>,
139 #[serde(flatten)]
140 other: serde_json::Map<String, serde_json::Value>,
141}
142
143/// Discover every plugin under `<project_root>/.claude/plugins/`.
144///
145/// Why: the single scan point [`agents::discover_plugin_agents`],
146/// [`skills::discover_plugin_skills`], and the namespaced-name resolvers in
147/// both submodules all build on.
148/// What: each immediate subdirectory of `.claude/plugins/` is one plugin
149/// root, resolved via `load_plugin_root`. A missing/unreadable
150/// `.claude/plugins/` directory yields an empty list (never an error — a
151/// project simply using no plugins is the common case, mirroring
152/// `agents::discover_agents`'s missing-dir handling). Non-directory entries
153/// are skipped. Sorted by resolved name.
154/// Test: `tests::discover_plugin_roots_missing_dir_is_empty`,
155/// `tests::discover_plugin_roots_finds_subdirs`,
156/// `tests::discover_plugin_roots_honors_manifest_name_override`.
157pub fn discover_plugin_roots(project_root: &Path) -> Vec<PluginRoot> {
158 let plugins_dir = project_root.join(".claude").join(PLUGINS_DIRNAME);
159 let Ok(entries) = std::fs::read_dir(&plugins_dir) else {
160 tracing::debug!(
161 "plugins dir not found or unreadable: {}",
162 plugins_dir.display()
163 );
164 return Vec::new();
165 };
166
167 let mut roots: Vec<PluginRoot> = entries
168 .flatten()
169 .filter(|entry| entry.path().is_dir())
170 .filter_map(|entry| {
171 let path = entry.path();
172 let dir_name = path.file_name()?.to_str()?.to_string();
173 Some(load_plugin_root(&path, &dir_name))
174 })
175 .collect();
176 roots.sort_by(|a, b| a.name.cmp(&b.name));
177 roots
178}
179
180/// Resolve one plugin subdirectory into a [`PluginRoot`].
181///
182/// Why: factored out of [`discover_plugin_roots`] so the
183/// manifest-or-convention resolution (name, agents dir, skills dir) is a
184/// single, independently readable unit.
185/// What: reads `<plugin_dir>/.claude-plugin/plugin.json` if present; a
186/// missing or malformed manifest degrades to `dir_name` +
187/// the `agents`/`skills` directory convention (never an error — see the
188/// module doc's "no manifest" case). When a manifest IS present and
189/// declares any [`LATER_PHASE_MANIFEST_KEYS`], logs one aggregated
190/// `tracing::debug!` naming them. `agents`/`skills` overrides route through
191/// [`safe_plugin_subdir`] — `plugin.json` is hostile input (#3547).
192/// Test: `tests::discover_plugin_roots_honors_manifest_name_override`,
193/// `tests::discover_plugin_roots_honors_path_overrides`,
194/// `tests::discover_plugin_roots_falls_back_without_manifest`,
195/// `tests::discover_plugin_roots_warns_on_later_phase_keys`,
196/// `tests::load_plugin_root_rejects_absolute_agents_override`,
197/// `tests::load_plugin_root_rejects_dotdot_skills_override`.
198fn load_plugin_root(plugin_dir: &Path, dir_name: &str) -> PluginRoot {
199 let manifest_path = plugin_dir.join(".claude-plugin").join("plugin.json");
200 let manifest: Option<PluginManifest> = std::fs::read_to_string(&manifest_path)
201 .ok()
202 .and_then(|raw| serde_json::from_str(&raw).ok());
203
204 let name = manifest
205 .as_ref()
206 .and_then(|m| m.name.clone())
207 .unwrap_or_else(|| dir_name.to_string());
208
209 let agents_dir = match manifest.as_ref().and_then(|m| m.agents.clone()) {
210 Some(rel) => safe_plugin_subdir(plugin_dir, &rel, "agents", &name, "agents"),
211 None => plugin_dir.join("agents"),
212 };
213 let skills_dir = match manifest.as_ref().and_then(|m| m.skills.clone()) {
214 Some(rel) => safe_plugin_subdir(plugin_dir, &rel, "skills", &name, "skills"),
215 None => plugin_dir.join("skills"),
216 };
217
218 if let Some(m) = &manifest {
219 let later_phase: Vec<&str> = LATER_PHASE_MANIFEST_KEYS
220 .iter()
221 .copied()
222 .filter(|k| m.other.contains_key(*k))
223 .collect();
224 if !later_phase.is_empty() {
225 tracing::debug!(
226 "plugin '{name}' declares plugin.json key(s) {} — tcode Phase 1 ingests \
227 agents+skills only; ignored until a later phase (#3539)",
228 later_phase.join(", ")
229 );
230 }
231 }
232
233 PluginRoot {
234 agents_dir,
235 skills_dir,
236 root: plugin_dir.to_path_buf(),
237 name,
238 }
239}
240
241/// Validate and resolve a `plugin.json` `agents`/`skills` path override
242/// against `plugin_dir`, rejecting anything that could escape it
243/// (code-critic PR #3547 review, CRITICAL 1).
244///
245/// Why: `plugin.json` is THIRD-PARTY, caller-controlled content.
246/// `PathBuf::join` REPLACES the base entirely when the joined component is
247/// absolute (`plugin_dir.join("/etc")` == `/etc`), and a relative
248/// `../../..` override escapes upward even though it isn't absolute —
249/// either lets a malicious `plugin.json` point `agents`/`skills` at an
250/// arbitrary host directory (e.g. `~/.ssh`), which discovery would then
251/// scan and load `.md`/`SKILL.md` files out of.
252/// What: rejects `rel` outright (before any join) when it is absolute or
253/// contains a `..` component — this alone blocks every practical escape and
254/// keeps the warning specific about which shape failed. As defense in
255/// depth, the accepted candidate is additionally required to canonicalize
256/// to a path contained within `plugin_dir`'s own canonicalization (this
257/// also catches a symlink planted inside `plugin_dir` that resolves
258/// outside it). Any rejection logs one `tracing::warn!` naming the plugin,
259/// field, and offending value, and falls back to `plugin_dir.join(default)`
260/// — the un-overridden convention — rather than ever returning the
261/// untrusted path. `default` itself (`"agents"`/`"skills"`, never
262/// attacker-controlled) is never routed through this validation.
263/// Test: `tests::load_plugin_root_rejects_absolute_agents_override`,
264/// `tests::load_plugin_root_rejects_dotdot_skills_override`,
265/// `tests::discover_plugin_roots_honors_path_overrides`.
266fn safe_plugin_subdir(
267 plugin_dir: &Path,
268 rel: &str,
269 default: &str,
270 plugin_name: &str,
271 field: &str,
272) -> PathBuf {
273 let fallback = || plugin_dir.join(default);
274
275 let rel_path = Path::new(rel);
276 if rel_path.is_absolute()
277 || rel_path
278 .components()
279 .any(|c| matches!(c, std::path::Component::ParentDir))
280 {
281 tracing::warn!(
282 "plugin '{plugin_name}' plugin.json '{field}' override {rel:?} is absolute or \
283 contains '..' — rejected as a path-traversal attempt, falling back to the \
284 default '{default}' convention (#3547)"
285 );
286 return fallback();
287 }
288
289 let joined = plugin_dir.join(rel);
290 match (plugin_dir.canonicalize(), joined.canonicalize()) {
291 (Ok(canon_root), Ok(canon_joined)) if canon_joined.starts_with(&canon_root) => joined,
292 _ => {
293 tracing::warn!(
294 "plugin '{plugin_name}' plugin.json '{field}' override {rel:?} does not resolve \
295 within the plugin directory — rejected, falling back to the default \
296 '{default}' convention (#3547)"
297 );
298 fallback()
299 }
300 }
301}
302
303/// Whether `name` is a well-formed `<plugin>:<local>` namespaced dispatch
304/// name — the ONE shape every plugin-aware caller (`agents::resolve_agent`,
305/// `plugins::agents::find_plugin_agent_config`,
306/// `plugins::skills::resolve_plugin_skill_body`,
307/// `skills::FsSkillResolver::resolve`, `tools::delegate::DelegateToAgentTool`,
308/// the CLI's `run-task` validation, `runner::agent_config_exists`) accepts
309/// (code-critic PR #3547 review, CRITICAL 2 / HIGH 3 / HIGH 4).
310///
311/// Why: a namespaced name's `local` segment is joined onto a plugin's
312/// `agents_dir`/`skills_dir` — e.g. `plugins::skills::resolve_plugin_skill_body`
313/// builds `skills_dir.join(skill_name).join("SKILL.md")` directly from the
314/// caller-supplied (and, via `use_skill`, LLM-supplied) segment. Restricting
315/// BOTH segments to `agents::protocol::validate_agent_name`'s existing safe
316/// charset (`[a-z0-9-]+`, 1-64 chars — reused, not re-derived, so the two
317/// concepts of "a safe catalog name" never drift apart) makes a traversal
318/// payload like `foo:../../../../x` or `foo:/etc/passwd` syntactically
319/// impossible to construct: the charset contains no `/` and no `.` at all,
320/// so no join built from a validated segment can ever leave the directory
321/// it was joined onto, regardless of what the discovered catalog happens to
322/// list (closes the residual gap where a plugin's own frontmatter could
323/// declare a spoofed `name:` that would otherwise appear "known").
324/// What: `true` only for EXACTLY two `:`-separated segments, each accepted
325/// by `agents::protocol::validate_agent_name`. Zero or one segment (a plain
326/// name), more than two (multiple colons), or either segment failing the
327/// charset/length check all return `false`.
328/// Test: `tests::is_valid_namespaced_name_accepts_two_safe_segments`,
329/// `tests::is_valid_namespaced_name_rejects_traversal_segment`,
330/// `tests::is_valid_namespaced_name_rejects_absolute_segment`,
331/// `tests::is_valid_namespaced_name_rejects_plain_name`,
332/// `tests::is_valid_namespaced_name_rejects_extra_colon`.
333pub fn is_valid_namespaced_name(name: &str) -> bool {
334 let segments: Vec<&str> = name.splitn(3, ':').collect();
335 match segments.as_slice() {
336 [plugin, local] => {
337 crate::agents::protocol::validate_agent_name(plugin).is_ok()
338 && crate::agents::protocol::validate_agent_name(local).is_ok()
339 }
340 _ => false,
341 }
342}
343
344/// Whether `leaf`'s canonicalized path is contained within `container`'s
345/// own canonicalization — the LEAF-FILE-IDENTITY guard neither
346/// [`safe_plugin_subdir`] (guards a `plugin.json` directory override) nor
347/// [`is_valid_namespaced_name`] (guards the dispatch NAME) provides
348/// (code-critic PR #3547 re-review, CRITICAL 5, CWE-59).
349///
350/// Why: `std::fs::read_to_string`, `Path::is_dir`, and `Path::is_file` all
351/// FOLLOW symlinks. A validated directory (`agents_dir`/`skills_dir`) and a
352/// validated namespaced NAME together still say nothing about what the
353/// resulting `<dir>/<name>` (or `<dir>/<name>/SKILL.md`) path actually
354/// points AT on disk — a hostile plugin can make that exact leaf entry (or
355/// an intermediate path component, e.g. `skills/<name>` itself) a symlink
356/// to an arbitrary host file/directory (`~/.ssh/id_rsa`). Reading it would
357/// feed the target's content into an LLM prompt verbatim once the
358/// (legitimately namespaced, legitimately-directoried) name is dispatched.
359/// What: canonicalizes both `leaf` and `container`; `true` only when BOTH
360/// canonicalize successfully AND the canonicalized `leaf` starts with the
361/// canonicalized `container`. A leaf that fails to canonicalize (broken
362/// symlink, race, doesn't exist) is treated as NOT contained — fail
363/// closed, never fail open into "assume safe". Because `canonicalize`
364/// resolves EVERY symlink in the path (not merely the final component),
365/// ONE call here catches a symlinked leaf file, a symlinked intermediate
366/// directory, or both, uniformly — callers do not need a separate check
367/// for "is the containing directory itself a symlink".
368/// Test: `tests::path_is_contained_accepts_real_file_within_container`,
369/// `tests::path_is_contained_rejects_symlink_escaping_container`,
370/// `tests::path_is_contained_rejects_nonexistent_leaf`.
371pub(crate) fn path_is_contained(leaf: &Path, container: &Path) -> bool {
372 match (leaf.canonicalize(), container.canonicalize()) {
373 (Ok(canon_leaf), Ok(canon_container)) => canon_leaf.starts_with(&canon_container),
374 _ => false,
375 }
376}
377
378/// Recover a project root from a `.claude/agents` or `.claude/skills`
379/// directory two levels below it.
380///
381/// Why: `agents::protocol::AgentsCatalogState`/`skills::protocol::SkillsCatalogState`
382/// and `skills::FsSkillResolver` already hold a resolved `.claude/agents` or
383/// `.claude/skills` directory (see `binding::ProjectBinding::agents_dir`,
384/// `skills::locate_skills_dir`) — both are always exactly `<root>/.claude/<x>`.
385/// Deriving the root from that existing path lets every plugin-aware call
386/// site (`agents::resolve_agent`, `agents::protocol::agents_list`,
387/// `skills::protocol::skills_list`, `skills::FsSkillResolver::new`) opt into
388/// plugin discovery without a new `project_root` parameter threaded through
389/// their existing signatures/constructors.
390/// What: `dir.parent().parent()` — works identically whether `dir` is the
391/// `.claude/agents` convention or the legacy `.open-mpm/agents` one, since
392/// both are exactly two segments below the root. Returns `None` when `dir`
393/// has fewer than two ancestors (e.g. a bare relative path in tests).
394/// Test: `tests::project_root_two_levels_up_recovers_root`,
395/// `tests::project_root_two_levels_up_none_when_too_shallow`.
396pub(crate) fn project_root_two_levels_up(dot_claude_child_dir: &Path) -> Option<PathBuf> {
397 dot_claude_child_dir
398 .parent()?
399 .parent()
400 .map(Path::to_path_buf)
401}
402
403#[cfg(test)]
404#[path = "mod_tests.rs"]
405mod tests;