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// #5426: the `plugins` directory name moved to `crate::paths::plugins_dir`,
82// which owns the `.trusty-code` → `.claude` → `.open-mpm` precedence for it.
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 the project's resolved `plugins/` directory.
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: the directory comes from [`crate::paths::plugins_dir`], so a project
149/// that has moved to `.trusty-code/plugins/` is scanned there and one still on
150/// `.claude/plugins/` keeps working (#5426). Each immediate subdirectory is one
151/// plugin root, resolved via `load_plugin_root`. A missing/unreadable directory
152/// yields an empty list (never an error — a project simply using no plugins is
153/// the common case, mirroring `agents::discover_agents`'s missing-dir handling).
154/// Non-directory entries are skipped. Sorted by resolved name.
155/// Test: `tests::discover_plugin_roots_missing_dir_is_empty`,
156/// `tests::discover_plugin_roots_finds_subdirs`,
157/// `tests::discover_plugin_roots_honors_manifest_name_override`,
158/// `paths::tests::plugins_dir_prefers_trusty_code`.
159pub fn discover_plugin_roots(project_root: &Path) -> Vec<PluginRoot> {
160 // #5426: resolved, not joined — `.trusty-code/plugins` then `.claude/plugins`.
161 let plugins_dir = crate::paths::plugins_dir(project_root).path;
162 let Ok(entries) = std::fs::read_dir(&plugins_dir) else {
163 tracing::debug!(
164 "plugins dir not found or unreadable: {}",
165 plugins_dir.display()
166 );
167 return Vec::new();
168 };
169
170 let mut roots: Vec<PluginRoot> = entries
171 .flatten()
172 .filter(|entry| entry.path().is_dir())
173 .filter_map(|entry| {
174 let path = entry.path();
175 let dir_name = path.file_name()?.to_str()?.to_string();
176 Some(load_plugin_root(&path, &dir_name))
177 })
178 .collect();
179 roots.sort_by(|a, b| a.name.cmp(&b.name));
180 roots
181}
182
183/// Resolve one plugin subdirectory into a [`PluginRoot`].
184///
185/// Why: factored out of [`discover_plugin_roots`] so the
186/// manifest-or-convention resolution (name, agents dir, skills dir) is a
187/// single, independently readable unit.
188/// What: reads `<plugin_dir>/.claude-plugin/plugin.json` if present; a
189/// missing or malformed manifest degrades to `dir_name` +
190/// the `agents`/`skills` directory convention (never an error — see the
191/// module doc's "no manifest" case). When a manifest IS present and
192/// declares any [`LATER_PHASE_MANIFEST_KEYS`], logs one aggregated
193/// `tracing::debug!` naming them. `agents`/`skills` overrides route through
194/// [`safe_plugin_subdir`] — `plugin.json` is hostile input (#3547).
195/// Test: `tests::discover_plugin_roots_honors_manifest_name_override`,
196/// `tests::discover_plugin_roots_honors_path_overrides`,
197/// `tests::discover_plugin_roots_falls_back_without_manifest`,
198/// `tests::discover_plugin_roots_warns_on_later_phase_keys`,
199/// `tests::load_plugin_root_rejects_absolute_agents_override`,
200/// `tests::load_plugin_root_rejects_dotdot_skills_override`.
201fn load_plugin_root(plugin_dir: &Path, dir_name: &str) -> PluginRoot {
202 let manifest_path = plugin_dir.join(".claude-plugin").join("plugin.json");
203 let manifest: Option<PluginManifest> = std::fs::read_to_string(&manifest_path)
204 .ok()
205 .and_then(|raw| serde_json::from_str(&raw).ok());
206
207 let name = manifest
208 .as_ref()
209 .and_then(|m| m.name.clone())
210 .unwrap_or_else(|| dir_name.to_string());
211
212 let agents_dir = match manifest.as_ref().and_then(|m| m.agents.clone()) {
213 Some(rel) => safe_plugin_subdir(plugin_dir, &rel, "agents", &name, "agents"),
214 None => plugin_dir.join("agents"),
215 };
216 let skills_dir = match manifest.as_ref().and_then(|m| m.skills.clone()) {
217 Some(rel) => safe_plugin_subdir(plugin_dir, &rel, "skills", &name, "skills"),
218 None => plugin_dir.join("skills"),
219 };
220
221 if let Some(m) = &manifest {
222 let later_phase: Vec<&str> = LATER_PHASE_MANIFEST_KEYS
223 .iter()
224 .copied()
225 .filter(|k| m.other.contains_key(*k))
226 .collect();
227 if !later_phase.is_empty() {
228 tracing::debug!(
229 "plugin '{name}' declares plugin.json key(s) {} — tcode Phase 1 ingests \
230 agents+skills only; ignored until a later phase (#3539)",
231 later_phase.join(", ")
232 );
233 }
234 }
235
236 PluginRoot {
237 agents_dir,
238 skills_dir,
239 root: plugin_dir.to_path_buf(),
240 name,
241 }
242}
243
244/// Validate and resolve a `plugin.json` `agents`/`skills` path override
245/// against `plugin_dir`, rejecting anything that could escape it
246/// (code-critic PR #3547 review, CRITICAL 1).
247///
248/// Why: `plugin.json` is THIRD-PARTY, caller-controlled content.
249/// `PathBuf::join` REPLACES the base entirely when the joined component is
250/// absolute (`plugin_dir.join("/etc")` == `/etc`), and a relative
251/// `../../..` override escapes upward even though it isn't absolute —
252/// either lets a malicious `plugin.json` point `agents`/`skills` at an
253/// arbitrary host directory (e.g. `~/.ssh`), which discovery would then
254/// scan and load `.md`/`SKILL.md` files out of.
255/// What: rejects `rel` outright (before any join) when it is absolute or
256/// contains a `..` component — this alone blocks every practical escape and
257/// keeps the warning specific about which shape failed. As defense in
258/// depth, the accepted candidate is additionally required to canonicalize
259/// to a path contained within `plugin_dir`'s own canonicalization (this
260/// also catches a symlink planted inside `plugin_dir` that resolves
261/// outside it). Any rejection logs one `tracing::warn!` naming the plugin,
262/// field, and offending value, and falls back to `plugin_dir.join(default)`
263/// — the un-overridden convention — rather than ever returning the
264/// untrusted path. `default` itself (`"agents"`/`"skills"`, never
265/// attacker-controlled) is never routed through this validation.
266/// Test: `tests::load_plugin_root_rejects_absolute_agents_override`,
267/// `tests::load_plugin_root_rejects_dotdot_skills_override`,
268/// `tests::discover_plugin_roots_honors_path_overrides`.
269fn safe_plugin_subdir(
270 plugin_dir: &Path,
271 rel: &str,
272 default: &str,
273 plugin_name: &str,
274 field: &str,
275) -> PathBuf {
276 let fallback = || plugin_dir.join(default);
277
278 let rel_path = Path::new(rel);
279 if rel_path.is_absolute()
280 || rel_path
281 .components()
282 .any(|c| matches!(c, std::path::Component::ParentDir))
283 {
284 tracing::warn!(
285 "plugin '{plugin_name}' plugin.json '{field}' override {rel:?} is absolute or \
286 contains '..' — rejected as a path-traversal attempt, falling back to the \
287 default '{default}' convention (#3547)"
288 );
289 return fallback();
290 }
291
292 let joined = plugin_dir.join(rel);
293 match (plugin_dir.canonicalize(), joined.canonicalize()) {
294 (Ok(canon_root), Ok(canon_joined)) if canon_joined.starts_with(&canon_root) => joined,
295 _ => {
296 tracing::warn!(
297 "plugin '{plugin_name}' plugin.json '{field}' override {rel:?} does not resolve \
298 within the plugin directory — rejected, falling back to the default \
299 '{default}' convention (#3547)"
300 );
301 fallback()
302 }
303 }
304}
305
306/// Whether `name` is a well-formed `<plugin>:<local>` namespaced dispatch
307/// name — the ONE shape every plugin-aware caller (`agents::resolve_agent`,
308/// `plugins::agents::find_plugin_agent_config`,
309/// `plugins::skills::resolve_plugin_skill_body`,
310/// `skills::FsSkillResolver::resolve`, `tools::delegate::DelegateToAgentTool`,
311/// the CLI's `run-task` validation, `runner::agent_config_exists`) accepts
312/// (code-critic PR #3547 review, CRITICAL 2 / HIGH 3 / HIGH 4).
313///
314/// Why: a namespaced name's `local` segment is joined onto a plugin's
315/// `agents_dir`/`skills_dir` — e.g. `plugins::skills::resolve_plugin_skill_body`
316/// builds `skills_dir.join(skill_name).join("SKILL.md")` directly from the
317/// caller-supplied (and, via `use_skill`, LLM-supplied) segment. Restricting
318/// BOTH segments to `agents::protocol::validate_agent_name`'s existing safe
319/// charset (`[a-z0-9-]+`, 1-64 chars — reused, not re-derived, so the two
320/// concepts of "a safe catalog name" never drift apart) makes a traversal
321/// payload like `foo:../../../../x` or `foo:/etc/passwd` syntactically
322/// impossible to construct: the charset contains no `/` and no `.` at all,
323/// so no join built from a validated segment can ever leave the directory
324/// it was joined onto, regardless of what the discovered catalog happens to
325/// list (closes the residual gap where a plugin's own frontmatter could
326/// declare a spoofed `name:` that would otherwise appear "known").
327/// What: `true` only for EXACTLY two `:`-separated segments, each accepted
328/// by `agents::protocol::validate_agent_name`. Zero or one segment (a plain
329/// name), more than two (multiple colons), or either segment failing the
330/// charset/length check all return `false`.
331/// Test: `tests::is_valid_namespaced_name_accepts_two_safe_segments`,
332/// `tests::is_valid_namespaced_name_rejects_traversal_segment`,
333/// `tests::is_valid_namespaced_name_rejects_absolute_segment`,
334/// `tests::is_valid_namespaced_name_rejects_plain_name`,
335/// `tests::is_valid_namespaced_name_rejects_extra_colon`.
336pub fn is_valid_namespaced_name(name: &str) -> bool {
337 let segments: Vec<&str> = name.splitn(3, ':').collect();
338 match segments.as_slice() {
339 [plugin, local] => {
340 crate::agents::protocol::validate_agent_name(plugin).is_ok()
341 && crate::agents::protocol::validate_agent_name(local).is_ok()
342 }
343 _ => false,
344 }
345}
346
347/// Whether `leaf`'s canonicalized path is contained within `container`'s
348/// own canonicalization — the LEAF-FILE-IDENTITY guard neither
349/// [`safe_plugin_subdir`] (guards a `plugin.json` directory override) nor
350/// [`is_valid_namespaced_name`] (guards the dispatch NAME) provides
351/// (code-critic PR #3547 re-review, CRITICAL 5, CWE-59).
352///
353/// Why: `std::fs::read_to_string`, `Path::is_dir`, and `Path::is_file` all
354/// FOLLOW symlinks. A validated directory (`agents_dir`/`skills_dir`) and a
355/// validated namespaced NAME together still say nothing about what the
356/// resulting `<dir>/<name>` (or `<dir>/<name>/SKILL.md`) path actually
357/// points AT on disk — a hostile plugin can make that exact leaf entry (or
358/// an intermediate path component, e.g. `skills/<name>` itself) a symlink
359/// to an arbitrary host file/directory (`~/.ssh/id_rsa`). Reading it would
360/// feed the target's content into an LLM prompt verbatim once the
361/// (legitimately namespaced, legitimately-directoried) name is dispatched.
362/// What: canonicalizes both `leaf` and `container`; `true` only when BOTH
363/// canonicalize successfully AND the canonicalized `leaf` starts with the
364/// canonicalized `container`. A leaf that fails to canonicalize (broken
365/// symlink, race, doesn't exist) is treated as NOT contained — fail
366/// closed, never fail open into "assume safe". Because `canonicalize`
367/// resolves EVERY symlink in the path (not merely the final component),
368/// ONE call here catches a symlinked leaf file, a symlinked intermediate
369/// directory, or both, uniformly — callers do not need a separate check
370/// for "is the containing directory itself a symlink".
371/// Test: `tests::path_is_contained_accepts_real_file_within_container`,
372/// `tests::path_is_contained_rejects_symlink_escaping_container`,
373/// `tests::path_is_contained_rejects_nonexistent_leaf`.
374pub(crate) fn path_is_contained(leaf: &Path, container: &Path) -> bool {
375 match (leaf.canonicalize(), container.canonicalize()) {
376 (Ok(canon_leaf), Ok(canon_container)) => canon_leaf.starts_with(&canon_container),
377 _ => false,
378 }
379}
380
381/// Recover a project root from a `.claude/agents` or `.claude/skills`
382/// directory two levels below it.
383///
384/// Why: `agents::protocol::AgentsCatalogState`/`skills::protocol::SkillsCatalogState`
385/// and `skills::FsSkillResolver` already hold a resolved `.claude/agents` or
386/// `.claude/skills` directory (see `binding::ProjectBinding::agents_dir`,
387/// `skills::locate_skills_dir`) — both are always exactly `<root>/.claude/<x>`.
388/// Deriving the root from that existing path lets every plugin-aware call
389/// site (`agents::resolve_agent`, `agents::protocol::agents_list`,
390/// `skills::protocol::skills_list`, `skills::FsSkillResolver::new`) opt into
391/// plugin discovery without a new `project_root` parameter threaded through
392/// their existing signatures/constructors.
393/// What: `dir.parent().parent()` — works identically whether `dir` is the
394/// `.claude/agents` convention or the legacy `.open-mpm/agents` one, since
395/// both are exactly two segments below the root. Returns `None` when `dir`
396/// has fewer than two ancestors (e.g. a bare relative path in tests).
397/// Test: `tests::project_root_two_levels_up_recovers_root`,
398/// `tests::project_root_two_levels_up_none_when_too_shallow`.
399pub(crate) fn project_root_two_levels_up(dot_claude_child_dir: &Path) -> Option<PathBuf> {
400 dot_claude_child_dir
401 .parent()?
402 .parent()
403 .map(Path::to_path_buf)
404}
405
406#[cfg(test)]
407#[path = "mod_tests.rs"]
408mod tests;