返回 CodeWhale
manifest.rs
根目录 / crates / plugins / src / manifest.rs
1 use std::collections::{BTreeMap, BTreeSet, HashMap};
2 use std::fs;
3 use std::io::Read;
4 use std::path::{Component, Path, PathBuf};
5
6 use semver::Version;
7 use serde::{Deserialize, Serialize};
8 use sha2::{Digest, Sha256};
9
10 #[cfg(any(test, feature = "test-support"))]
11 use super::activation::CAPABILITY_HASH_DOMAIN_V2;
12 use super::activation::{
13 CAPABILITY_HASH_DOMAIN_V1, PluginActivationCapability, PluginActivationPolicy,
14 };
15 use super::host_services::HostService;
16 use codewhale_mcp::config::{McpServerConfig, is_relative_stdio_path_arg};
17 use codewhale_util::path_identity::metadata_is_link_or_reparse;
18 #[cfg(windows)]
19 use codewhale_util::path_identity::windows_file_identity;
20
21 pub const CURRENT_SCHEMA_VERSION: u32 = 1;
22 pub const MAX_PLUGIN_NAME_CHARS: usize = 64;
23 const MAX_COMPONENT_PATHS: usize = 64;
24 const MAX_MANIFEST_BYTES: u64 = 1024 * 1024;
25 const MAX_HASHED_FILES: usize = 16_384;
26 const MAX_HASHED_BYTES: u64 = 256 * 1024 * 1024;
27 const MAX_MCP_ARGS: usize = 64;
28 const MAX_MCP_ENV: usize = 64;
29 const MAX_MCP_HEADERS: usize = 64;
30 const MAX_MCP_SCOPES: usize = 64;
31 const MAX_MCP_TOOL_FILTERS: usize = 256;
32 const MAX_MCP_TIMEOUT_SECS: u64 = 3_600;
33
34 #[derive(Debug, Clone, Deserialize, Serialize)]
35 #[serde(deny_unknown_fields)]
36 pub struct PluginManifest {
37 /// Missing means the legacy, pre-versioned Codewhale manifest. Legacy
38 /// manifests remain readable, but `/plugin validate` reports the migration.
39 #[serde(default)]
40 pub schema_version: u32,
41 pub plugin: PluginMeta,
42 #[serde(default)]
43 pub skills: Option<PluginPathSpec>,
44 #[serde(default)]
45 pub commands: Option<PluginPathSpec>,
46 #[serde(default, alias = "profiles")]
47 pub agents: Option<PluginPathSpec>,
48 #[serde(default)]
49 pub hooks: Option<PluginPathSpec>,
50 #[serde(default, alias = "lsp_servers")]
51 pub lsp: Option<PluginPathSpec>,
52 #[serde(default, alias = "native_extension")]
53 pub native: Option<PluginPathSpec>,
54 #[serde(default)]
55 pub mcp_servers: Option<HashMap<String, McpServerConfig>>,
56 #[serde(default)]
57 pub capabilities: PluginCapabilities,
58 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
59 pub providers: BTreeMap<String, super::providers::PluginProviderDeclaration>,
60 #[serde(default)]
61 pub when: Option<PluginWhen>,
62 }
63
64 #[derive(Debug, Clone, Deserialize, Serialize)]
65 #[serde(deny_unknown_fields)]
66 pub struct PluginMeta {
67 pub name: String,
68 #[serde(default)]
69 pub description: Option<String>,
70 #[serde(default)]
71 pub version: String,
72 #[serde(default)]
73 pub author: Option<String>,
74 /// Human-facing name preserved when the published `name` had to be
75 /// slugified to satisfy the Agent Plugins name rule.
76 #[serde(default)]
77 pub display_name: Option<String>,
78 /// Bounded inline PNG artwork. Never a remote fetch or executable SVG.
79 #[serde(default)]
80 pub icon: Option<String>,
81 #[serde(default)]
82 pub homepage: Option<String>,
83 #[serde(default)]
84 pub repository: Option<String>,
85 #[serde(default)]
86 pub license: Option<String>,
87 #[serde(default)]
88 pub keywords: Vec<String>,
89 }
90
91 /// A declarative component location. `path` preserves the original manifest
92 /// shape; `paths` lets a bundle split one component kind across directories.
93 #[derive(Debug, Clone, Default, Deserialize, Serialize)]
94 #[serde(deny_unknown_fields)]
95 pub struct PluginPathSpec {
96 #[serde(default, skip_serializing_if = "Option::is_none")]
97 pub path: Option<String>,
98 #[serde(default, skip_serializing_if = "Vec::is_empty")]
99 pub paths: Vec<String>,
100 }
101
102 impl PluginPathSpec {
103 pub(crate) fn declared_paths(&self, default: Option<&str>) -> Result<Vec<String>, String> {
104 let mut paths = Vec::new();
105 if let Some(path) = self.path.as_deref() {
106 paths.push(path.to_string());
107 }
108 paths.extend(self.paths.iter().cloned());
109 if paths.is_empty()
110 && let Some(default) = default
111 {
112 paths.push(default.to_string());
113 }
114 if paths.is_empty() {
115 return Err("component table must declare `path` or `paths`".to_string());
116 }
117 if paths.len() > MAX_COMPONENT_PATHS {
118 return Err(format!(
119 "component declares {} paths; maximum is {MAX_COMPONENT_PATHS}",
120 paths.len()
121 ));
122 }
123 let mut seen = BTreeSet::new();
124 for path in &paths {
125 if !seen.insert(path.clone()) {
126 return Err(format!(
127 "component path `{path}` is declared more than once"
128 ));
129 }
130 }
131 Ok(paths)
132 }
133 }
134
135 #[derive(Debug, Clone, Default, Deserialize, Serialize)]
136 #[serde(deny_unknown_fields)]
137 pub struct PluginCapabilities {
138 /// Requested filesystem roots are inventoried and stay inactive. They do
139 /// not block the bundle's supported declarative adapters from activating.
140 #[serde(default, skip_serializing_if = "Vec::is_empty")]
141 pub filesystem_roots: Vec<String>,
142 /// Requested hosts are inventory-only. MCP URL hosts are added to the
143 /// effective capability inventory automatically.
144 #[serde(default, skip_serializing_if = "Vec::is_empty")]
145 pub network_hosts: Vec<String>,
146 /// Lifecycle mutation is inventoried but unsupported. It does not block
147 /// the bundle's supported declarative adapters from activating.
148 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
149 pub lifecycle_mutation: bool,
150 #[serde(default, skip_serializing_if = "Vec::is_empty")]
151 pub host_services: Vec<HostService>,
152 }
153
154 #[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
155 #[serde(deny_unknown_fields)]
156 pub struct PluginWhen {
157 #[serde(default, skip_serializing_if = "Option::is_none")]
158 pub os: Option<Vec<String>>,
159 #[serde(default, skip_serializing_if = "Option::is_none")]
160 pub binaries: Option<Vec<String>>,
161 }
162
163 #[derive(Debug, Clone, Default, PartialEq, Eq)]
164 pub struct ResolvedPluginComponents {
165 pub skills: Vec<PathBuf>,
166 pub commands: Vec<PathBuf>,
167 pub agents: Vec<PathBuf>,
168 pub hooks: Vec<PathBuf>,
169 pub lsp: Vec<PathBuf>,
170 pub native: Vec<PathBuf>,
171 }
172
173 #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
174 #[serde(deny_unknown_fields)]
175 pub struct PluginInventory {
176 pub skills: usize,
177 pub mcp_servers: usize,
178 /// MCP servers that launch a child process under the Codewhale user's
179 /// host permissions. Kept separate from remote MCP so the review screen
180 /// cannot imply that an empty declared filesystem/network list is a
181 /// sandbox boundary.
182 #[serde(default)]
183 pub stdio_mcp_servers: usize,
184 /// MCP servers contacted over HTTP(S) without launching a local child.
185 #[serde(default)]
186 pub remote_mcp_servers: usize,
187 pub commands: usize,
188 pub agents: usize,
189 pub hooks: usize,
190 pub lsp: usize,
191 pub native: usize,
192 #[serde(default)]
193 pub providers: usize,
194 pub filesystem_roots: Vec<String>,
195 pub network_hosts: Vec<String>,
196 pub lifecycle_mutation: bool,
197 #[serde(default, skip_serializing_if = "Vec::is_empty")]
198 pub host_services: Vec<HostService>,
199 }
200
201 /// Host compatibility of a reviewed bundle. This is independent of trust,
202 /// enablement, and staging: it names whether Codewhale can activate the
203 /// declared surfaces, not whether the operator has turned the bundle on.
204 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
205 #[serde(rename_all = "snake_case")]
206 pub enum PluginCompatibility {
207 /// Every declared surface has an adapter, or the bundle is empty.
208 Full,
209 /// Supported adapters can activate; other declared surfaces stay inactive.
210 Partial,
211 /// The bundle only declares surfaces Codewhale cannot activate yet.
212 Unsupported,
213 }
214
215 impl PluginCompatibility {
216 #[must_use]
217 pub fn as_str(self) -> &'static str {
218 match self {
219 Self::Full => "full",
220 Self::Partial => "partial",
221 Self::Unsupported => "unsupported",
222 }
223 }
224 }
225
226 impl PluginInventory {
227 #[must_use]
228 pub fn declared_capabilities(&self) -> Vec<PluginActivationCapability> {
229 let mut capabilities = Vec::new();
230 if self.skills > 0 {
231 capabilities.push(PluginActivationCapability::Skills);
232 }
233 if self.stdio_mcp_servers > 0 {
234 capabilities.push(PluginActivationCapability::McpStdio);
235 }
236 if self.remote_mcp_servers > 0 {
237 capabilities.push(PluginActivationCapability::McpRemote);
238 }
239 if self.commands > 0 {
240 capabilities.push(PluginActivationCapability::Commands);
241 }
242 if self.agents > 0 {
243 capabilities.push(PluginActivationCapability::Agents);
244 }
245 if self.hooks > 0 {
246 capabilities.push(PluginActivationCapability::Hooks);
247 }
248 if self.lsp > 0 {
249 capabilities.push(PluginActivationCapability::Lsp);
250 }
251 if self.providers > 0 {
252 capabilities.push(PluginActivationCapability::Providers);
253 }
254 if self.native > 0 {
255 capabilities.push(PluginActivationCapability::Native);
256 }
257 if !self.filesystem_roots.is_empty() {
258 capabilities.push(PluginActivationCapability::FilesystemRoots);
259 }
260 if self.lifecycle_mutation {
261 capabilities.push(PluginActivationCapability::LifecycleMutation);
262 }
263 capabilities
264 }
265
266 #[must_use]
267 pub fn unsupported_labels(&self) -> Vec<&'static str> {
268 let policy = PluginActivationPolicy::current();
269 self.declared_capabilities()
270 .into_iter()
271 .filter(|capability| !policy.is_supported(*capability))
272 .map(PluginActivationCapability::as_str)
273 .collect()
274 }
275
276 #[must_use]
277 pub fn has_unsupported_capabilities(&self) -> bool {
278 !self.unsupported_labels().is_empty()
279 }
280
281 /// True when the bundle declares at least one adapter this build activates.
282 #[must_use]
283 pub fn has_supported_components(&self) -> bool {
284 let policy = PluginActivationPolicy::current();
285 self.declared_capabilities()
286 .into_iter()
287 .any(|capability| policy.is_supported(capability))
288 }
289
290 #[must_use]
291 pub fn supported_labels(&self) -> Vec<&'static str> {
292 let policy = PluginActivationPolicy::current();
293 let mut labels = Vec::new();
294 let mut saw_mcp = false;
295 for capability in self.declared_capabilities() {
296 if !policy.is_supported(capability) {
297 continue;
298 }
299 match capability {
300 PluginActivationCapability::McpStdio | PluginActivationCapability::McpRemote => {
301 if !saw_mcp {
302 labels.push("mcp");
303 saw_mcp = true;
304 }
305 }
306 other => labels.push(other.as_str()),
307 }
308 }
309 labels
310 }
311
312 #[must_use]
313 pub fn compatibility(&self) -> PluginCompatibility {
314 if !self.has_unsupported_capabilities() {
315 PluginCompatibility::Full
316 } else if self.has_supported_components() {
317 PluginCompatibility::Partial
318 } else {
319 PluginCompatibility::Unsupported
320 }
321 }
322
323 /// Empty or fully-supported bundles can activate; mixed bundles can
324 /// activate their supported adapters; all-unsupported bundles cannot.
325 #[must_use]
326 pub fn can_activate_supported_components(&self) -> bool {
327 !matches!(self.compatibility(), PluginCompatibility::Unsupported)
328 }
329
330 #[must_use]
331 pub fn summary(&self) -> String {
332 let mut summary = format!(
333 "skills={} mcp={} (stdio={} remote={}) commands={} agents={} hooks={} lsp={} native={} providers={}",
334 self.skills,
335 self.mcp_servers,
336 self.stdio_mcp_servers,
337 self.remote_mcp_servers,
338 self.commands,
339 self.agents,
340 self.hooks,
341 self.lsp,
342 self.native,
343 self.providers
344 );
345 if !self.host_services.is_empty() {
346 summary.push_str(" host_services=");
347 summary.push_str(&host_service_names(&self.host_services).join(","));
348 }
349 summary
350 }
351 }
352
353 #[derive(Debug, Clone)]
354 pub struct ValidatedManifest {
355 pub manifest: PluginManifest,
356 pub canonical_root: PathBuf,
357 pub components: ResolvedPluginComponents,
358 pub inventory: PluginInventory,
359 pub content_hash: String,
360 /// Digest of the exact bytes read for every regular bundle file, keyed by
361 /// its lossless relative OS path. Runtime adapters use this to bind parsed
362 /// representations to the same bytes that produced `content_hash`.
363 pub file_hashes: BTreeMap<PathBuf, String>,
364 /// Plain SHA256 for declared regular Native entry files, captured from
365 /// the same anchored, bounded read as the domain-separated bundle hashes.
366 /// EntryRef binds these digests; the bundle file inventory keeps its domain.
367 pub native_entry_hashes: BTreeMap<PathBuf, String>,
368 pub capability_hash: String,
369 pub applicable: bool,
370 pub warnings: Vec<String>,
371 }
372
373 /// On-disk manifest encoding, detected from the file name. `plugin.json`
374 /// (Agent Plugins v1.0.0) is the native format; `plugin.toml` stays readable
375 /// as the legacy Codewhale format. Both parse into the same
376 /// [`PluginManifest`], so nothing downstream of discovery changes.
377 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
378 enum ManifestFormat {
379 Json,
380 KimiJson,
381 ClaudeJson,
382 Toml,
383 }
384
385 impl ManifestFormat {
386 fn from_path(path: &Path) -> Result<Self, String> {
387 match path.file_name().and_then(|name| name.to_str()) {
388 Some(super::agent_plugin::PLUGIN_JSON_NAME)
389 if super::agent_plugin::plugin_root_for_manifest(path) != path.parent() =>
390 {
391 Ok(Self::ClaudeJson)
392 }
393 Some(super::agent_plugin::PLUGIN_JSON_NAME) => Ok(Self::Json),
394 Some(super::agent_plugin::KIMI_PLUGIN_JSON_NAME) => Ok(Self::KimiJson),
395 Some(super::agent_plugin::PLUGIN_TOML_NAME) => Ok(Self::Toml),
396 _ => Err(format!(
397 "plugin manifest must be named plugin.json, kimi.plugin.json, or plugin.toml: {}",
398 path.display()
399 )),
400 }
401 }
402
403 fn label(self) -> &'static str {
404 match self {
405 Self::Json => super::agent_plugin::PLUGIN_JSON_NAME,
406 Self::KimiJson => super::agent_plugin::KIMI_PLUGIN_JSON_NAME,
407 Self::ClaudeJson => ".claude-plugin/plugin.json",
408 Self::Toml => super::agent_plugin::PLUGIN_TOML_NAME,
409 }
410 }
411 }
412
413 /// Parse manifest text in either encoding. For `plugin.json` this also reads
414 /// the sibling `mcp.json` (whose bytes are returned so callers can re-read and
415 /// detect mid-validation drift); Codewhale-specific data arrives through
416 /// `extensions["net.codewhale"]` and unknown namespaces are ignored.
417 fn parse_manifest(
418 format: ManifestFormat,
419 text: &str,
420 root: &Path,
421 ) -> Result<(PluginManifest, Option<Vec<u8>>), String> {
422 match format {
423 ManifestFormat::Toml => {
424 validate_nested_mcp_schema(text)?;
425 let manifest = toml::from_str(text).map_err(|error| safe_toml_parse_error(&error))?;
426 Ok((manifest, None))
427 }
428 ManifestFormat::Json => {
429 let standard = super::agent_plugin::parse_plugin_json(text)?;
430 let mcp_bytes = read_sibling_mcp_json(root, super::agent_plugin::MCP_JSON_NAME)?;
431 let mcp_servers = match &mcp_bytes {
432 Some(bytes) => {
433 let text = std::str::from_utf8(bytes)
434 .map_err(|_| "mcp.json must be valid UTF-8".to_string())?;
435 Some(super::agent_plugin::parse_mcp_json(text)?)
436 }
437 None => None,
438 };
439 let manifest = super::agent_plugin::standard_to_manifest(standard, mcp_servers, root)?;
440 Ok((manifest, mcp_bytes))
441 }
442 ManifestFormat::ClaudeJson => {
443 let bytes = read_sibling_mcp_json(root, ".mcp.json")?;
444 let manifest =
445 super::agent_plugin::parse_claude_plugin_json(text, root, bytes.as_deref())?;
446 Ok((manifest, bytes))
447 }
448 ManifestFormat::KimiJson => Ok((
449 super::agent_plugin::parse_kimi_plugin_json(text, root)?,
450 None,
451 )),
452 }
453 }
454
455 /// Read a `plugin.json` bundle's sibling `mcp.json` under the same rules as
456 /// the manifest itself: a regular file, never a link, size-bounded.
457 fn read_sibling_mcp_json(root: &Path, name: &str) -> Result<Option<Vec<u8>>, String> {
458 let path = root.join(name);
459 let metadata = match fs::symlink_metadata(&path) {
460 Ok(metadata) => metadata,
461 Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
462 Err(error) => return Err(format!("failed to inspect mcp.json: {error}")),
463 };
464 if metadata_is_link_or_reparse(&metadata) || !metadata.is_file() {
465 return Err("mcp.json must be a regular file, not a symbolic link".to_string());
466 }
467 let file = codewhale_util::bundle_file::open_bundle_file(&path)
468 .map_err(|e| format!("failed to open mcp.json without following links: {e}"))?;
469 let mut bytes = Vec::new();
470 file.take(MAX_MANIFEST_BYTES + 1)
471 .read_to_end(&mut bytes)
472 .map_err(|e| format!("failed to read mcp.json: {e}"))?;
473 if bytes.len() as u64 > MAX_MANIFEST_BYTES {
474 return Err(format!(
475 "mcp.json exceeds the {MAX_MANIFEST_BYTES}-byte review limit"
476 ));
477 }
478 Ok(Some(bytes))
479 }
480
481 impl PluginManifest {
482 pub fn from_path(path: &Path) -> Result<Self, String> {
483 let format = ManifestFormat::from_path(path)?;
484 let label = format.label();
485 let metadata =
486 fs::symlink_metadata(path).map_err(|e| format!("failed to inspect {label}: {e}"))?;
487 if metadata_is_link_or_reparse(&metadata) {
488 return Err(format!("{label} may not be a symbolic link"));
489 }
490 let bytes = read_manifest_bytes(path, label)?;
491 let content =
492 std::str::from_utf8(&bytes).map_err(|_| format!("{label} must be valid UTF-8"))?;
493 let root = super::agent_plugin::plugin_root_for_manifest(path)
494 .ok_or_else(|| format!("{label} has no parent directory"))?;
495 Ok(parse_manifest(format, content, root)?.0)
496 }
497
498 pub fn validate_from_path(path: &Path) -> Result<ValidatedManifest, String> {
499 let format = ManifestFormat::from_path(path)?;
500 let label = format.label();
501 let manifest_metadata =
502 fs::symlink_metadata(path).map_err(|e| format!("failed to inspect {label}: {e}"))?;
503 if metadata_is_link_or_reparse(&manifest_metadata) || !manifest_metadata.is_file() {
504 return Err(format!(
505 "{label} must be a regular file, not a symbolic link"
506 ));
507 }
508 let root = super::agent_plugin::plugin_root_for_manifest(path)
509 .ok_or_else(|| format!("{label} has no parent directory"))?;
510 let root_metadata = fs::symlink_metadata(root)
511 .map_err(|e| format!("failed to inspect plugin root: {e}"))?;
512 if metadata_is_link_or_reparse(&root_metadata) || !root_metadata.is_dir() {
513 return Err("plugin root must be a directory, not a symbolic link".to_string());
514 }
515 let canonical_root = root
516 .canonicalize()
517 .map_err(|e| format!("failed to canonicalize plugin root: {e}"))?;
518 if !canonical_root.is_dir() {
519 return Err("plugin root is not a directory".to_string());
520 }
521
522 let manifest_bytes = read_manifest_bytes(path, label)?;
523 let manifest_text = std::str::from_utf8(&manifest_bytes)
524 .map_err(|_| format!("{label} must be valid UTF-8"))?;
525 let (mut manifest, mcp_bytes) = parse_manifest(format, manifest_text, &canonical_root)?;
526 let warnings = if manifest.schema_version == 0 && format == ManifestFormat::Toml {
527 let mut warnings = vec![format!(
528 "legacy manifest: add `schema_version = {CURRENT_SCHEMA_VERSION}`"
529 )];
530 if manifest.plugin.version.trim().is_empty() {
531 manifest.plugin.version = "0.0.0".to_string();
532 warnings.push(
533 "legacy manifest: add a semantic `[plugin].version`; displaying `0.0.0`"
534 .to_string(),
535 );
536 }
537 warnings
538 } else {
539 Vec::new()
540 };
541 manifest.validate_metadata(format)?;
542
543 let components = manifest.resolve_components(&canonical_root)?;
544 manifest.validate_mcp_servers(&canonical_root)?;
545 super::providers::validate_declarations(&manifest.providers)?;
546 let inventory = manifest.inventory(&components)?;
547 let (content_hash, bundle_hashes) =
548 hash_bundle(&canonical_root, &manifest_bytes, label, &components.native)?;
549 let capability_hash = hash_inventory(&inventory);
550 let applicable = manifest.check_when();
551 if read_manifest_bytes(path, label)? != manifest_bytes {
552 return Err(format!(
553 "{label} changed while it was being validated; retry discovery"
554 ));
555 }
556 let mcp_name = match format {
557 ManifestFormat::Json => Some(super::agent_plugin::MCP_JSON_NAME),
558 ManifestFormat::ClaudeJson => Some(".mcp.json"),
559 _ => None,
560 };
561 if let Some(name) = mcp_name
562 && read_sibling_mcp_json(&canonical_root, name)? != mcp_bytes
563 {
564 return Err(
565 "mcp.json changed while it was being validated; retry discovery".to_string(),
566 );
567 }
568
569 Ok(ValidatedManifest {
570 manifest,
571 canonical_root,
572 components,
573 inventory,
574 content_hash,
575 file_hashes: bundle_hashes.file_hashes,
576 native_entry_hashes: bundle_hashes.native_entry_hashes,
577 capability_hash,
578 applicable,
579 warnings,
580 })
581 }
582
583 fn validate_metadata(&self, format: ManifestFormat) -> Result<(), String> {
584 if self.schema_version > CURRENT_SCHEMA_VERSION {
585 return Err(format!(
586 "unsupported schema_version {}; maximum is {CURRENT_SCHEMA_VERSION}",
587 self.schema_version
588 ));
589 }
590 match format {
591 ManifestFormat::Json | ManifestFormat::ClaudeJson => {
592 if !super::agent_plugin::is_standard_plugin_name(&self.plugin.name) {
593 return Err(format!(
594 "plugin name `{}` violates the Agent Plugins name rule (1-{MAX_PLUGIN_NAME_CHARS} lowercase ASCII letters, digits, or internal single hyphens or dots; never `--` or `..`)",
595 self.plugin.name
596 ));
597 }
598 }
599 ManifestFormat::KimiJson => {
600 if !super::agent_plugin::is_kimi_plugin_name(&self.plugin.name) {
601 return Err(format!(
602 "plugin name `{}` violates the Kimi plugin name rule",
603 self.plugin.name
604 ));
605 }
606 }
607 ManifestFormat::Toml => validate_plugin_name(&self.plugin.name)?,
608 }
609 Version::parse(self.plugin.version.trim()).map_err(|e| {
610 format!(
611 "plugin version `{}` is not valid semantic versioning: {e}",
612 self.plugin.version
613 )
614 })?;
615 validate_optional_text("description", self.plugin.description.as_deref(), 1_024)?;
616 validate_optional_text("author", self.plugin.author.as_deref(), 256)?;
617 validate_optional_text("display name", self.plugin.display_name.as_deref(), 128)?;
618 if let Some(icon) = &self.plugin.icon {
619 validate_icon(icon)?;
620 }
621 validate_optional_text("homepage", self.plugin.homepage.as_deref(), 2_048)?;
622 validate_optional_text("repository", self.plugin.repository.as_deref(), 2_048)?;
623 validate_optional_text("license", self.plugin.license.as_deref(), 128)?;
624 validate_unique_texts("keyword", &self.plugin.keywords, 128)?;
625 validate_unique_texts("filesystem root", &self.capabilities.filesystem_roots, 512)?;
626 validate_unique_texts("network host", &self.capabilities.network_hosts, 253)?;
627 let mut asked = BTreeSet::new();
628 for service in &self.capabilities.host_services {
629 if !asked.insert(*service) {
630 return Err(format!("duplicate host service value `{}`", service.name()));
631 }
632 }
633 let declared_network_hosts = self
634 .capabilities
635 .network_hosts
636 .iter()
637 .map(|host| normalize_network_host(host))
638 .collect::<Result<BTreeSet<_>, _>>()?;
639 let remote_network_hosts = self
640 .mcp_servers
641 .as_ref()
642 .into_iter()
643 .flat_map(|servers| servers.values())
644 .filter_map(|server| server.url.as_deref())
645 .map(|url| {
646 reqwest::Url::parse(url)
647 .map_err(|_| "remote MCP URL is invalid".to_string())?
648 .host_str()
649 .map(str::to_string)
650 .ok_or_else(|| "remote MCP URL is missing a host".to_string())
651 })
652 .collect::<Result<BTreeSet<_>, _>>()?;
653 if declared_network_hosts != remote_network_hosts {
654 return Err(
655 "capabilities.network_hosts must exactly match the normalized host set of all remote MCP endpoints"
656 .to_string(),
657 );
658 }
659 if let Some(when) = &self.when {
660 if let Some(os_values) = &when.os {
661 validate_unique_texts("OS", os_values, 32)?;
662 const SUPPORTED: &[&str] = &[
663 "windows", "linux", "macos", "freebsd", "openbsd", "netbsd", "android", "ios",
664 ];
665 for os in os_values {
666 if !SUPPORTED.contains(&os.to_ascii_lowercase().as_str()) {
667 return Err(format!("unsupported OS selector `{os}`"));
668 }
669 }
670 }
671 if let Some(binaries) = &when.binaries {
672 validate_unique_texts("binary", binaries, 128)?;
673 for binary in binaries {
674 if binary.contains('/')
675 || binary.contains('\\')
676 || looks_windows_absolute(binary)
677 {
678 return Err(format!(
679 "binary condition `{binary}` must be a bare executable name"
680 ));
681 }
682 }
683 }
684 }
685 Ok(())
686 }
687
688 fn resolve_components(&self, root: &Path) -> Result<ResolvedPluginComponents, String> {
689 Ok(ResolvedPluginComponents {
690 skills: resolve_spec(root, "skills", self.skills.as_ref(), Some("skills"))?,
691 commands: resolve_spec(root, "commands", self.commands.as_ref(), None)?,
692 agents: resolve_spec(root, "agents", self.agents.as_ref(), None)?,
693 hooks: resolve_spec(root, "hooks", self.hooks.as_ref(), None)?,
694 lsp: resolve_spec(root, "lsp", self.lsp.as_ref(), None)?,
695 native: resolve_spec(root, "native", self.native.as_ref(), None)?,
696 })
697 }
698
699 pub fn validate_mcp_servers(&self, root: &Path) -> Result<(), String> {
700 let Some(servers) = &self.mcp_servers else {
701 return Ok(());
702 };
703 if servers.len() > MAX_COMPONENT_PATHS {
704 return Err(format!(
705 "manifest declares {} MCP servers; maximum is {MAX_COMPONENT_PATHS}",
706 servers.len()
707 ));
708 }
709 for (name, server) in servers {
710 validate_component_name("MCP server", name)?;
711 if server.args.len() > MAX_MCP_ARGS {
712 return Err(format!(
713 "MCP server `{name}` declares too many arguments; maximum is {MAX_MCP_ARGS}"
714 ));
715 }
716 if server.env.len() > MAX_MCP_ENV {
717 return Err(format!(
718 "MCP server `{name}` declares too many environment mappings; maximum is {MAX_MCP_ENV}"
719 ));
720 }
721 if server.env_headers.len() > MAX_MCP_HEADERS {
722 return Err(format!(
723 "MCP server `{name}` declares too many environment-backed headers; maximum is {MAX_MCP_HEADERS}"
724 ));
725 }
726 if server.scopes.len() > MAX_MCP_SCOPES {
727 return Err(format!(
728 "MCP server `{name}` declares too many OAuth scopes; maximum is {MAX_MCP_SCOPES}"
729 ));
730 }
731 if server.enabled_tools.len() > MAX_MCP_TOOL_FILTERS
732 || server.disabled_tools.len() > MAX_MCP_TOOL_FILTERS
733 {
734 return Err(format!(
735 "MCP server `{name}` declares too many tool filters; maximum is {MAX_MCP_TOOL_FILTERS} per list"
736 ));
737 }
738 for (label, timeout) in [
739 ("connect_timeout", server.connect_timeout),
740 ("execute_timeout", server.execute_timeout),
741 ("read_timeout", server.read_timeout),
742 ] {
743 if timeout.is_some_and(|seconds| !(1..=MAX_MCP_TIMEOUT_SECS).contains(&seconds)) {
744 return Err(format!(
745 "MCP server `{name}` {label} must be 1-{MAX_MCP_TIMEOUT_SECS} seconds"
746 ));
747 }
748 }
749 if server.required && !server.enabled {
750 return Err(format!(
751 "MCP server `{name}` cannot be required while disabled"
752 ));
753 }
754 for arg in &server.args {
755 validate_text("MCP argument", arg, 4_096)?;
756 }
757 validate_unique_texts("enabled MCP tool", &server.enabled_tools, 256)?;
758 validate_unique_texts("disabled MCP tool", &server.disabled_tools, 256)?;
759 if server.enabled_tools.iter().any(|tool| {
760 server
761 .disabled_tools
762 .iter()
763 .any(|disabled| disabled == tool)
764 }) {
765 return Err(format!(
766 "MCP server `{name}` declares a tool in both enabled_tools and disabled_tools"
767 ));
768 }
769 match (server.command.as_deref(), server.url.as_deref()) {
770 (Some(command), None) => {
771 validate_text("MCP command", command, 512)?;
772 if server.transport.is_some()
773 || !server.headers.is_empty()
774 || !server.env_headers.is_empty()
775 || server.bearer_token_env_var.is_some()
776 || !server.scopes.is_empty()
777 || server.oauth.is_some()
778 || server.oauth_resource.is_some()
779 {
780 return Err(format!(
781 "stdio MCP server `{name}` may not declare remote transport or authentication fields"
782 ));
783 }
784 if command.contains('/') || command.contains('\\') {
785 let resolved = resolve_contained_path(root, command, "MCP command")?;
786 if !resolved.is_file() {
787 return Err(format!(
788 "MCP server `{name}` command is not a regular file"
789 ));
790 }
791 } else {
792 validate_bare_executable(command)?;
793 }
794 if let Some(cwd) = server.cwd.as_deref() {
795 let raw = cwd.to_string_lossy();
796 let resolved = resolve_contained_path(root, &raw, "MCP cwd")?;
797 if !resolved.is_dir() {
798 return Err(format!(
799 "MCP server `{name}` cwd is not a directory: {}",
800 resolved.display()
801 ));
802 }
803 }
804 validate_mcp_argv_has_no_literal_credentials(name, &server.args)?;
805 for (index, arg) in server.args.iter().enumerate() {
806 if Path::new(arg).is_absolute() || looks_windows_absolute(arg) {
807 return Err(format!(
808 "MCP server `{name}` argument #{} must not use an absolute path",
809 index + 1
810 ));
811 }
812 if is_relative_stdio_path_arg(arg)
813 && Path::new(arg)
814 .components()
815 .any(|part| matches!(part, Component::ParentDir))
816 {
817 return Err(format!(
818 "MCP server `{name}` argument #{} escapes the plugin root",
819 index + 1
820 ));
821 }
822 }
823 for (destination, source) in &server.env {
824 validate_environment_name("MCP environment destination", destination)?;
825 let source = exact_environment_placeholder(source).ok_or_else(|| {
826 format!(
827 "MCP server `{name}` environment values must be exact `${{SOURCE_ENV}}` references"
828 )
829 })?;
830 validate_environment_name("MCP environment source", source)?;
831 }
832 }
833 (None, Some(url)) => {
834 if !server.scopes.is_empty()
835 || server.oauth.is_some()
836 || server.oauth_resource.is_some()
837 {
838 return Err(format!(
839 "remote MCP server `{name}` may not declare OAuth fields because plugin OAuth is disabled; use env_headers or bearer_token_env_var"
840 ));
841 }
842 let parsed = reqwest::Url::parse(url)
843 .map_err(|e| format!("MCP server `{name}` URL is invalid: {e}"))?;
844 if !matches!(parsed.scheme(), "http" | "https") || parsed.host_str().is_none() {
845 return Err(format!(
846 "MCP server `{name}` URL must use http or https and include a host"
847 ));
848 }
849 if parsed.scheme() == "http"
850 && !parsed.host_str().is_some_and(|host| {
851 host.eq_ignore_ascii_case("localhost")
852 || host
853 .parse::<std::net::IpAddr>()
854 .is_ok_and(|address| address.is_loopback())
855 })
856 {
857 return Err(format!(
858 "MCP server `{name}` URL must use HTTPS unless it targets loopback"
859 ));
860 }
861 if !parsed.username().is_empty() || parsed.password().is_some() {
862 return Err(format!(
863 "MCP server `{name}` URL must not embed credentials; use environment-backed authentication"
864 ));
865 }
866 if parsed.query().is_some() || parsed.fragment().is_some() {
867 return Err(format!(
868 "MCP server `{name}` URL may not contain a query or fragment"
869 ));
870 }
871 if server.cwd.is_some() || !server.args.is_empty() || !server.env.is_empty() {
872 return Err(format!(
873 "remote MCP server `{name}` may not declare stdio cwd, args, or env"
874 ));
875 }
876 if !server.headers.is_empty() {
877 return Err(format!(
878 "remote MCP server `{name}` may not contain literal headers; use env_headers or bearer_token_env_var"
879 ));
880 }
881 if let Some(transport) = server.transport.as_deref() {
882 validate_text("MCP transport", transport, 32)?;
883 if !transport.eq_ignore_ascii_case("sse") {
884 return Err(format!(
885 "MCP server `{name}` transport must be `sse` when explicitly set"
886 ));
887 }
888 }
889 for (header, env_var) in &server.env_headers {
890 validate_http_header_name(header)?;
891 validate_environment_name("MCP header environment source", env_var)?;
892 }
893 if let Some(env_var) = server.bearer_token_env_var.as_deref() {
894 validate_environment_name("MCP bearer environment source", env_var)?;
895 }
896 validate_unique_texts("OAuth scope", &server.scopes, 256)?;
897 if let Some(oauth) = &server.oauth
898 && let Some(client_id) = oauth.client_id.as_deref()
899 {
900 validate_text("OAuth client id", client_id, 512)?;
901 }
902 if let Some(resource) = server.oauth_resource.as_deref() {
903 validate_safe_oauth_resource(resource)?;
904 }
905 }
906 (Some(_), Some(_)) => {
907 return Err(format!(
908 "MCP server `{name}` must declare exactly one of command or url"
909 ));
910 }
911 (None, None) => {
912 return Err(format!(
913 "MCP server `{name}` must declare exactly one of command or url"
914 ));
915 }
916 }
917 }
918 Ok(())
919 }
920
921 fn inventory(&self, components: &ResolvedPluginComponents) -> Result<PluginInventory, String> {
922 let stdio_mcp_servers = self.mcp_servers.as_ref().map_or(0, |servers| {
923 servers
924 .values()
925 .filter(|server| server.command.is_some() && server.url.is_none())
926 .count()
927 });
928 let remote_mcp_servers = self.mcp_servers.as_ref().map_or(0, |servers| {
929 servers
930 .values()
931 .filter(|server| server.url.is_some() && server.command.is_none())
932 .count()
933 });
934 let mut network_hosts = self
935 .capabilities
936 .network_hosts
937 .iter()
938 .map(|host| host.to_ascii_lowercase())
939 .collect::<Vec<_>>();
940 if let Some(servers) = &self.mcp_servers {
941 for server in servers.values() {
942 if let Some(url) = server.url.as_deref()
943 && let Ok(url) = reqwest::Url::parse(url)
944 && let Some(host) = url.host_str()
945 {
946 network_hosts.push(host.to_ascii_lowercase());
947 }
948 }
949 }
950 for declaration in self.providers.values() {
951 for endpoint in declaration.endpoints() {
952 if let Ok(url) = reqwest::Url::parse(endpoint)
953 && let Some(host) = url.host_str()
954 {
955 network_hosts.push(host.to_ascii_lowercase());
956 }
957 }
958 }
959 network_hosts.sort();
960 network_hosts.dedup();
961
962 let mut filesystem_roots = self.capabilities.filesystem_roots.clone();
963 filesystem_roots.sort();
964 filesystem_roots.dedup();
965 let mut host_services = self.capabilities.host_services.clone();
966 host_services.sort();
967 host_services.dedup();
968
969 Ok(PluginInventory {
970 skills: components.skills.len(),
971 mcp_servers: self.mcp_servers.as_ref().map_or(0, HashMap::len),
972 stdio_mcp_servers,
973 remote_mcp_servers,
974 commands: components.commands.len(),
975 agents: components.agents.len(),
976 hooks: components.hooks.len(),
977 lsp: components.lsp.len(),
978 native: components.native.len(),
979 providers: self.providers.len(),
980 filesystem_roots,
981 network_hosts,
982 lifecycle_mutation: self.capabilities.lifecycle_mutation,
983 host_services,
984 })
985 }
986
987 #[must_use]
988 pub fn check_when(&self) -> bool {
989 let Some(when) = &self.when else {
990 return true;
991 };
992 if let Some(os_list) = &when.os {
993 let os = std::env::consts::OS;
994 if !os_list
995 .iter()
996 .any(|candidate| candidate.eq_ignore_ascii_case(os))
997 {
998 return false;
999 }
1000 }
1001 if let Some(binaries) = &when.binaries {
1002 for binary in binaries {
1003 if !Self::has_binary(binary) {
1004 return false;
1005 }
1006 }
1007 }
1008 true
1009 }
1010
1011 fn has_binary(name: &str) -> bool {
1012 let paths = std::env::var_os("PATH").unwrap_or_default();
1013 for path in std::env::split_paths(&paths) {
1014 let candidate = path.join(name);
1015 if candidate.is_file() {
1016 return true;
1017 }
1018 #[cfg(windows)]
1019 if candidate.with_extension("exe").is_file() {
1020 return true;
1021 }
1022 }
1023 false
1024 }
1025 }
1026
1027 fn safe_toml_parse_error(error: &toml::de::Error) -> String {
1028 // `Display` includes source excerpts and can echo a malformed literal
1029 // secret. Byte location is enough to repair the file without copying
1030 // manifest values into logs, diagnostics, or transcripts.
1031 error.span().map_or_else(
1032 || "failed to parse plugin.toml; check the v1 schema and field types".to_string(),
1033 |span| {
1034 format!(
1035 "failed to parse plugin.toml near bytes {}..{}; check the v1 schema and field types",
1036 span.start, span.end
1037 )
1038 },
1039 )
1040 }
1041
1042 fn read_manifest_bytes(path: &Path, label: &str) -> Result<Vec<u8>, String> {
1043 let file = codewhale_util::bundle_file::open_bundle_file(path)
1044 .map_err(|e| format!("failed to open {label} without following links: {e}"))?;
1045 let mut bytes = Vec::new();
1046 file.take(MAX_MANIFEST_BYTES + 1)
1047 .read_to_end(&mut bytes)
1048 .map_err(|e| format!("failed to read {label}: {e}"))?;
1049 if bytes.len() as u64 > MAX_MANIFEST_BYTES {
1050 return Err(format!(
1051 "{label} exceeds the {MAX_MANIFEST_BYTES}-byte review limit"
1052 ));
1053 }
1054 Ok(bytes)
1055 }
1056
1057 /// The historical Codewhale `plugin.toml` name rule: lowercase ASCII letters,
1058 /// digits, and internal hyphens (including `--` runs). Kept byte-for-byte for
1059 /// legacy manifests; `/plugin export` slugifies names that are invalid under
1060 /// the Agent Plugins standard. `plugin.json` manifests are held to the
1061 /// standard's rule instead ([`super::agent_plugin::is_standard_plugin_name`]):
1062 /// it also allows internal dots but bans `--` and `..`.
1063 pub fn validate_plugin_name(name: &str) -> Result<(), String> {
1064 let count = name.chars().count();
1065 let valid = count > 0
1066 && count <= MAX_PLUGIN_NAME_CHARS
1067 && name
1068 .chars()
1069 .all(|ch| ch.is_ascii_lowercase() || ch.is_ascii_digit() || ch == '-')
1070 && name
1071 .chars()
1072 .next()
1073 .is_some_and(|ch| ch.is_ascii_lowercase() || ch.is_ascii_digit())
1074 && name
1075 .chars()
1076 .last()
1077 .is_some_and(|ch| ch.is_ascii_lowercase() || ch.is_ascii_digit());
1078 if valid {
1079 Ok(())
1080 } else {
1081 Err(format!(
1082 "plugin name `{name}` must be 1-{MAX_PLUGIN_NAME_CHARS} lowercase ASCII letters, digits, or internal hyphens"
1083 ))
1084 }
1085 }
1086
1087 fn validate_component_name(kind: &str, name: &str) -> Result<(), String> {
1088 let count = name.chars().count();
1089 let valid = count > 0
1090 && count <= MAX_PLUGIN_NAME_CHARS
1091 && name
1092 .chars()
1093 .all(|ch| ch.is_ascii_alphanumeric() || matches!(ch, '-' | '_'))
1094 && !name.starts_with(['-', '_'])
1095 && !name.ends_with(['-', '_']);
1096 if valid {
1097 Ok(())
1098 } else {
1099 Err(format!("{kind} name `{name}` is invalid"))
1100 }
1101 }
1102
1103 fn validate_optional_text(
1104 field: &str,
1105 value: Option<&str>,
1106 max_chars: usize,
1107 ) -> Result<(), String> {
1108 if let Some(value) = value {
1109 validate_text(field, value, max_chars)?;
1110 }
1111 Ok(())
1112 }
1113
1114 fn validate_mcp_argv_has_no_literal_credentials(
1115 server_name: &str,
1116 arguments: &[String],
1117 ) -> Result<(), String> {
1118 for (index, argument) in arguments.iter().enumerate() {
1119 let (key, assigned_value) = argument
1120 .split_once('=')
1121 .map_or((argument.as_str(), None), |(key, value)| (key, Some(value)));
1122 if credential_argument_key(key)
1123 && (assigned_value.is_some_and(|value| !value.is_empty())
1124 || (assigned_value.is_none() && arguments.get(index + 1).is_some()))
1125 {
1126 return Err(format!(
1127 "MCP server `{server_name}` argument #{} embeds a credential-bearing value; pass credentials through a reviewed environment mapping instead",
1128 index + 1
1129 ));
1130 }
1131 if looks_like_literal_credential(argument) {
1132 return Err(format!(
1133 "MCP server `{server_name}` argument #{} looks like a literal credential; pass credentials through a reviewed environment mapping instead",
1134 index + 1
1135 ));
1136 }
1137 }
1138 Ok(())
1139 }
1140
1141 fn credential_argument_key(value: &str) -> bool {
1142 let key = value
1143 .trim_start_matches('-')
1144 .replace('_', "-")
1145 .to_ascii_lowercase();
1146 [
1147 "token",
1148 "api-key",
1149 "apikey",
1150 "password",
1151 "passwd",
1152 "secret",
1153 "client-secret",
1154 "authorization",
1155 "auth-token",
1156 "access-key",
1157 "private-key",
1158 "credential",
1159 "credentials",
1160 ]
1161 .iter()
1162 .any(|sensitive| key == *sensitive || key.ends_with(&format!("-{sensitive}")))
1163 }
1164
1165 fn looks_like_literal_credential(value: &str) -> bool {
1166 let trimmed = value.trim();
1167 trimmed.starts_with("sk-")
1168 || trimmed.starts_with("ghp_")
1169 || trimmed.starts_with("github_pat_")
1170 || trimmed.starts_with("xoxb-")
1171 || trimmed.starts_with("xoxp-")
1172 || (trimmed.starts_with("AKIA") && trimmed.len() >= 16)
1173 }
1174
1175 fn validate_text(field: &str, value: &str, max_chars: usize) -> Result<(), String> {
1176 let trimmed = value.trim();
1177 if trimmed.is_empty() || trimmed.chars().count() > max_chars {
1178 return Err(format!(
1179 "{field} must contain 1-{max_chars} non-whitespace characters"
1180 ));
1181 }
1182 if value.chars().any(char::is_control) {
1183 return Err(format!("{field} may not contain control characters"));
1184 }
1185 if value
1186 .chars()
1187 .any(codewhale_sanitize::sanitize::is_bidi_control)
1188 {
1189 return Err(format!(
1190 "{field} may not contain bidirectional formatting characters"
1191 ));
1192 }
1193 Ok(())
1194 }
1195
1196 fn validate_unique_texts(field: &str, values: &[String], max_chars: usize) -> Result<(), String> {
1197 if values.len() > MAX_COMPONENT_PATHS {
1198 return Err(format!(
1199 "too many {field} values; maximum is {MAX_COMPONENT_PATHS}"
1200 ));
1201 }
1202 let mut seen = BTreeSet::new();
1203 for value in values {
1204 validate_text(field, value, max_chars)?;
1205 let normalized = value.to_ascii_lowercase();
1206 if !seen.insert(normalized) {
1207 return Err(format!("duplicate {field} value `{value}`"));
1208 }
1209 }
1210 Ok(())
1211 }
1212
1213 fn normalize_network_host(host: &str) -> Result<String, String> {
1214 if host.contains("://") || host.contains('/') || host.contains('\\') {
1215 return Err(format!(
1216 "network host `{host}` must be a host name, not a URL or path"
1217 ));
1218 }
1219 let parsed = reqwest::Url::parse(&format!("https://{host}"))
1220 .map_err(|e| format!("network host `{host}` is invalid: {e}"))?;
1221 if parsed.port().is_some()
1222 || !parsed.username().is_empty()
1223 || parsed.password().is_some()
1224 || parsed.path() != "/"
1225 || parsed.query().is_some()
1226 || parsed.fragment().is_some()
1227 {
1228 return Err(format!(
1229 "network host `{host}` must contain only a normalized host name"
1230 ));
1231 }
1232 parsed
1233 .host_str()
1234 .map(|host| host.to_ascii_lowercase())
1235 .ok_or_else(|| format!("network host `{host}` is invalid"))
1236 }
1237
1238 fn validate_bare_executable(command: &str) -> Result<(), String> {
1239 if command.len() <= 128
1240 && command
1241 .chars()
1242 .all(|ch| ch.is_ascii_alphanumeric() || matches!(ch, '-' | '_' | '.' | '+'))
1243 && !matches!(command, "." | "..")
1244 {
1245 Ok(())
1246 } else {
1247 Err("MCP command must be a bare executable name or a contained plugin path".to_string())
1248 }
1249 }
1250
1251 fn validate_environment_name(field: &str, value: &str) -> Result<(), String> {
1252 validate_text(field, value, 128)?;
1253 if value
1254 .chars()
1255 .next()
1256 .is_some_and(|ch| ch.is_ascii_alphabetic() || ch == '_')
1257 && value
1258 .chars()
1259 .all(|ch| ch.is_ascii_alphanumeric() || ch == '_')
1260 {
1261 Ok(())
1262 } else {
1263 Err(format!(
1264 "{field} must be an ASCII environment variable name"
1265 ))
1266 }
1267 }
1268
1269 pub(super) fn exact_environment_placeholder(value: &str) -> Option<&str> {
1270 value.strip_prefix("${")?.strip_suffix('}')
1271 }
1272
1273 fn validate_http_header_name(name: &str) -> Result<(), String> {
1274 validate_text("MCP HTTP header name", name, 128)?;
1275 reqwest::header::HeaderName::from_bytes(name.as_bytes())
1276 .map(|_| ())
1277 .map_err(|_| "MCP HTTP header name is invalid".to_string())
1278 }
1279
1280 fn validate_safe_oauth_resource(resource: &str) -> Result<(), String> {
1281 validate_text("OAuth resource", resource, 2_048)?;
1282 let parsed = reqwest::Url::parse(resource)
1283 .map_err(|_| "OAuth resource must be an absolute HTTPS URL".to_string())?;
1284 if parsed.scheme() != "https"
1285 || parsed.host_str().is_none()
1286 || !parsed.username().is_empty()
1287 || parsed.password().is_some()
1288 || parsed.query().is_some()
1289 || parsed.fragment().is_some()
1290 {
1291 return Err(
1292 "OAuth resource must be an HTTPS URL without credentials, query, or fragment"
1293 .to_string(),
1294 );
1295 }
1296 Ok(())
1297 }
1298
1299 fn validate_nested_mcp_schema(content: &str) -> Result<(), String> {
1300 const SERVER_FIELDS: &[&str] = &[
1301 "command",
1302 "args",
1303 "env",
1304 "cwd",
1305 "url",
1306 "transport",
1307 "connect_timeout",
1308 "execute_timeout",
1309 "read_timeout",
1310 "enabled",
1311 "required",
1312 "enabled_tools",
1313 "disabled_tools",
1314 "headers",
1315 "env_headers",
1316 "env_http_headers",
1317 "bearer_token_env_var",
1318 "scopes",
1319 "oauth",
1320 "oauth_resource",
1321 ];
1322 let value: toml::Value =
1323 toml::from_str(content).map_err(|error| safe_toml_parse_error(&error))?;
1324 let Some(servers) = value.get("mcp_servers") else {
1325 return Ok(());
1326 };
1327 let servers = servers
1328 .as_table()
1329 .ok_or_else(|| "mcp_servers must be a table".to_string())?;
1330 for server in servers.values() {
1331 let server = server
1332 .as_table()
1333 .ok_or_else(|| "each MCP server must be a table".to_string())?;
1334 if server
1335 .keys()
1336 .any(|field| !SERVER_FIELDS.contains(&field.as_str()))
1337 {
1338 return Err("plugin MCP server contains an unsupported field".to_string());
1339 }
1340 if let Some(oauth) = server.get("oauth") {
1341 let oauth = oauth
1342 .as_table()
1343 .ok_or_else(|| "plugin MCP oauth must be a table".to_string())?;
1344 if oauth.keys().any(|field| field != "client_id") {
1345 return Err("plugin MCP oauth contains an unsupported field".to_string());
1346 }
1347 }
1348 }
1349 Ok(())
1350 }
1351
1352 fn resolve_spec(
1353 root: &Path,
1354 kind: &str,
1355 spec: Option<&PluginPathSpec>,
1356 default: Option<&str>,
1357 ) -> Result<Vec<PathBuf>, String> {
1358 let Some(spec) = spec else {
1359 return Ok(Vec::new());
1360 };
1361 spec.declared_paths(default)?
1362 .iter()
1363 .map(|path| resolve_contained_path(root, path, kind))
1364 .collect()
1365 }
1366
1367 fn resolve_contained_path(root: &Path, raw: &str, kind: &str) -> Result<PathBuf, String> {
1368 validate_text(&format!("{kind} path"), raw, 1_024)?;
1369 if Path::new(raw).is_absolute() || looks_windows_absolute(raw) {
1370 return Err(format!("{kind} path must be relative: `{raw}`"));
1371 }
1372 if Path::new(raw).components().any(|component| {
1373 matches!(
1374 component,
1375 Component::ParentDir | Component::RootDir | Component::Prefix(_)
1376 )
1377 }) {
1378 return Err(format!("{kind} path escapes the plugin root: `{raw}`"));
1379 }
1380 let joined = root.join(raw);
1381 reject_symlink_components(root, &joined, kind)?;
1382 let canonical = joined
1383 .canonicalize()
1384 .map_err(|e| format!("{kind} path `{raw}` cannot be resolved: {e}"))?;
1385 if !canonical.starts_with(root) {
1386 return Err(format!("{kind} path escapes the plugin root: `{raw}`"));
1387 }
1388 Ok(canonical)
1389 }
1390
1391 fn reject_symlink_components(root: &Path, target: &Path, kind: &str) -> Result<(), String> {
1392 let relative = target
1393 .strip_prefix(root)
1394 .map_err(|_| format!("{kind} path is outside the plugin root"))?;
1395 let mut cursor = root.to_path_buf();
1396 for component in relative.components() {
1397 cursor.push(component.as_os_str());
1398 let metadata = fs::symlink_metadata(&cursor)
1399 .map_err(|e| format!("failed to inspect {kind} path {}: {e}", cursor.display()))?;
1400 if metadata_is_link_or_reparse(&metadata) {
1401 return Err(format!(
1402 "{kind} path may not traverse symbolic link {}",
1403 cursor.display()
1404 ));
1405 }
1406 }
1407 Ok(())
1408 }
1409
1410 fn looks_windows_absolute(raw: &str) -> bool {
1411 let bytes = raw.as_bytes();
1412 bytes
1413 .first()
1414 .is_some_and(|byte| matches!(*byte, b'\\' | b'/'))
1415 || (bytes.len() >= 3
1416 && bytes[0].is_ascii_alphabetic()
1417 && bytes[1] == b':'
1418 && matches!(bytes[2], b'\\' | b'/'))
1419 }
1420
1421 fn hash_bundle(
1422 root: &Path,
1423 manifest_bytes: &[u8],
1424 manifest_label: &str,
1425 native_entries: &[PathBuf],
1426 ) -> Result<(String, HashBudget), String> {
1427 let mut hasher = Sha256::new();
1428 // v2 length-frames every variable-length field. The v1 delimiter-only
1429 // stream was structurally ambiguous across file-record boundaries.
1430 // Changing the domain invalidates every ambiguous v1 receipt.
1431 // The manifest file name is part of the domain: `plugin.toml` produces the
1432 // exact v2 byte stream existing receipts bind to, while `plugin.json`
1433 // starts a fresh receipt family.
1434 hasher.update(b"codewhale-plugin-content-v2\0");
1435 hasher.update(manifest_label.as_bytes());
1436 hasher.update(b"\0");
1437 hasher.update((manifest_bytes.len() as u64).to_le_bytes());
1438 hasher.update(manifest_bytes);
1439 let native_paths = native_entries
1440 .iter()
1441 .map(|entry| {
1442 entry
1443 .strip_prefix(root)
1444 .map(Path::to_path_buf)
1445 .map_err(|_| "Native entry escaped the reviewed bundle".to_string())
1446 })
1447 .collect::<Result<BTreeSet<_>, _>>()?;
1448 let mut budget = HashBudget {
1449 native_paths,
1450 ..Default::default()
1451 };
1452 // Hash the complete bundle, not only declared component roots. Local MCP
1453 // entrypoints and companion assets are security-relevant even when they do
1454 // not have a separate component table.
1455 hash_path(root, root, &mut hasher, &mut budget)?;
1456 Ok((hex_digest(hasher.finalize()), budget))
1457 }
1458
1459 #[derive(Default)]
1460 struct HashBudget {
1461 files: usize,
1462 bytes: u64,
1463 file_hashes: BTreeMap<PathBuf, String>,
1464 native_paths: BTreeSet<PathBuf>,
1465 native_entry_hashes: BTreeMap<PathBuf, String>,
1466 }
1467
1468 fn hash_path(
1469 root: &Path,
1470 path: &Path,
1471 hasher: &mut Sha256,
1472 budget: &mut HashBudget,
1473 ) -> Result<(), String> {
1474 let metadata = fs::symlink_metadata(path)
1475 .map_err(|e| format!("failed to inspect component {}: {e}", path.display()))?;
1476 if metadata_is_link_or_reparse(&metadata) {
1477 return Err(format!(
1478 "component trees may not contain symbolic link {}",
1479 path.display()
1480 ));
1481 }
1482 let relative = path
1483 .strip_prefix(root)
1484 .map_err(|_| format!("component {} is outside the plugin root", path.display()))?;
1485 hash_permissions(&metadata, hasher);
1486 if metadata.is_dir() {
1487 #[cfg(windows)]
1488 let directory_guard = codewhale_util::bundle_file::open_bundle_directory(path)
1489 .map_err(|e| format!("failed to open component directory safely: {e}"))?;
1490 #[cfg(windows)]
1491 ensure_windows_path_still_opened(path, &directory_guard)?;
1492 hasher.update(b"D\0");
1493 codewhale_util::path_identity::hash_os_path(hasher, b"bundle-relative-directory", relative);
1494 let mut entries = fs::read_dir(path)
1495 .map_err(|e| format!("failed to read component directory {}: {e}", path.display()))?
1496 .collect::<Result<Vec<_>, _>>()
1497 .map_err(|e| format!("failed to read component directory {}: {e}", path.display()))?;
1498 entries.sort_by_key(fs::DirEntry::file_name);
1499 for entry in entries {
1500 hash_path(root, &entry.path(), hasher, budget)?;
1501 }
1502 hasher.update(b"E\0");
1503 #[cfg(windows)]
1504 ensure_windows_path_still_opened(path, &directory_guard)?;
1505 } else if metadata.is_file() {
1506 budget.files += 1;
1507 if budget.files > MAX_HASHED_FILES {
1508 return Err(format!(
1509 "plugin bundle content exceeds the plugin review limit ({MAX_HASHED_FILES} files / {MAX_HASHED_BYTES} bytes)"
1510 ));
1511 }
1512 hasher.update(b"F\0");
1513 codewhale_util::path_identity::hash_os_path(hasher, b"bundle-relative-file", relative);
1514 let mut file = codewhale_util::bundle_file::open_bundle_file(path)
1515 .map_err(|e| format!("failed to read component file {}: {e}", path.display()))?;
1516 #[cfg(windows)]
1517 ensure_windows_path_still_opened(path, &file)?;
1518 let expected_len = file
1519 .metadata()
1520 .map_err(|e| format!("failed to inspect component file {}: {e}", path.display()))?
1521 .len();
1522 hasher.update(expected_len.to_le_bytes());
1523 let mut file_hasher = Sha256::new();
1524 file_hasher.update(b"codewhale-plugin-file-bytes-v1\0");
1525 let mut native_entry_hasher = budget.native_paths.contains(relative).then(Sha256::new);
1526 // Keep the read buffer off the stack. `hash_path` is recursive and the
1527 // fixed-size array inflated every directory frame, which could exhaust
1528 // a Tokio worker stack while revalidating a nested plugin bundle.
1529 let mut buffer = vec![0_u8; 64 * 1024];
1530 let mut actual_len = 0_u64;
1531 loop {
1532 let read = file
1533 .read(&mut buffer)
1534 .map_err(|e| format!("failed to read component file {}: {e}", path.display()))?;
1535 if read == 0 {
1536 break;
1537 }
1538 actual_len = actual_len.saturating_add(read as u64);
1539 budget.bytes = budget.bytes.saturating_add(read as u64);
1540 if budget.bytes > MAX_HASHED_BYTES {
1541 return Err(format!(
1542 "plugin bundle content exceeds the plugin review limit ({MAX_HASHED_FILES} files / {MAX_HASHED_BYTES} bytes)"
1543 ));
1544 }
1545 hasher.update(&buffer[..read]);
1546 file_hasher.update(&buffer[..read]);
1547 if let Some(entry_hasher) = &mut native_entry_hasher {
1548 entry_hasher.update(&buffer[..read]);
1549 }
1550 }
1551 if actual_len != expected_len {
1552 return Err(format!(
1553 "component file {} changed length while being reviewed",
1554 path.display()
1555 ));
1556 }
1557 budget
1558 .file_hashes
1559 .insert(relative.to_path_buf(), hex_digest(file_hasher.finalize()));
1560 if let Some(entry_hasher) = native_entry_hasher {
1561 budget
1562 .native_entry_hashes
1563 .insert(relative.to_path_buf(), hex_digest(entry_hasher.finalize()));
1564 }
1565 #[cfg(windows)]
1566 ensure_windows_path_still_opened(path, &file)?;
1567 } else {
1568 return Err(format!(
1569 "component {} is neither a regular file nor directory",
1570 path.display()
1571 ));
1572 }
1573 Ok(())
1574 }
1575
1576 #[cfg(unix)]
1577 fn hash_permissions(metadata: &fs::Metadata, hasher: &mut Sha256) {
1578 use std::os::unix::fs::PermissionsExt;
1579
1580 // Runtime snapshots deliberately remove group/other access and write bits.
1581 // Bind identity only to whether a regular file is executable, so the
1582 // owner-only staged representation has the same reviewed content hash.
1583 hasher.update(b"unix-executable\0");
1584 hasher.update([u8::from(
1585 metadata.is_file() && metadata.permissions().mode() & 0o111 != 0,
1586 )]);
1587 }
1588
1589 #[cfg(not(unix))]
1590 fn hash_permissions(metadata: &fs::Metadata, hasher: &mut Sha256) {
1591 let _ = metadata;
1592 // Windows staging marks files read-only as a defense-in-depth hardening
1593 // step; that representation change is not plugin content identity.
1594 hasher.update(b"portable-mode\0");
1595 }
1596
1597 #[cfg(windows)]
1598 fn ensure_windows_path_still_opened(path: &Path, opened: &fs::File) -> Result<(), String> {
1599 let after = fs::symlink_metadata(path)
1600 .map_err(|e| format!("failed to re-inspect plugin path after handle open: {e}"))?;
1601 if metadata_is_link_or_reparse(&after) {
1602 return Err("plugin path changed into a reparse point during validation".to_string());
1603 }
1604 let expect_directory = if after.is_dir() {
1605 true
1606 } else if after.is_file() {
1607 false
1608 } else {
1609 return Err("plugin path changed into an unsupported object during validation".to_string());
1610 };
1611 let current =
1612 codewhale_util::bundle_file::open_bundle_identity_probe(path, expect_directory)
1613 .map_err(|e| format!("failed to reopen plugin path for identity validation: {e}"))?;
1614 let opened = windows_file_identity(opened)
1615 .map_err(|e| format!("failed to identify retained plugin handle: {e}"))?;
1616 let current = windows_file_identity(&current)
1617 .map_err(|e| format!("failed to identify current plugin path: {e}"))?;
1618 if opened.volume != current.volume || opened.index != current.index {
1619 return Err("plugin path identity changed between handle open and validation".to_string());
1620 }
1621 Ok(())
1622 }
1623
1624 pub(super) fn hash_inventory(inventory: &PluginInventory) -> String {
1625 hash_inventory_with_policy(inventory, PluginActivationPolicy::current())
1626 }
1627
1628 fn host_service_names(services: &[HostService]) -> Vec<&'static str> {
1629 services.iter().map(|service| service.name()).collect()
1630 }
1631
1632 fn hash_inventory_counts(inventory: &PluginInventory) -> BTreeMap<&'static str, String> {
1633 let mut normalized = BTreeMap::new();
1634 normalized.insert("skills", inventory.skills.to_string());
1635 normalized.insert("mcp", inventory.mcp_servers.to_string());
1636 normalized.insert("mcp-stdio", inventory.stdio_mcp_servers.to_string());
1637 normalized.insert("mcp-remote", inventory.remote_mcp_servers.to_string());
1638 normalized.insert("commands", inventory.commands.to_string());
1639 normalized.insert("agents", inventory.agents.to_string());
1640 normalized.insert("hooks", inventory.hooks.to_string());
1641 normalized.insert("lsp", inventory.lsp.to_string());
1642 normalized.insert("native", inventory.native.to_string());
1643 normalized.insert("providers", inventory.providers.to_string());
1644 normalized.insert("filesystem", inventory.filesystem_roots.join("\n"));
1645 normalized.insert("network", inventory.network_hosts.join("\n"));
1646 normalized.insert("lifecycle", inventory.lifecycle_mutation.to_string());
1647 if !inventory.host_services.is_empty() {
1648 normalized.insert(
1649 "host-services",
1650 host_service_names(&inventory.host_services).join("\n"),
1651 );
1652 }
1653 normalized
1654 }
1655
1656 fn hash_inventory_with_policy(
1657 inventory: &PluginInventory,
1658 policy: PluginActivationPolicy,
1659 ) -> String {
1660 let mut hasher = Sha256::new();
1661 policy.write_hash_material(&mut hasher);
1662 for (key, value) in hash_inventory_counts(inventory) {
1663 hasher.update(key.as_bytes());
1664 hasher.update(b"\0");
1665 hasher.update(value.as_bytes());
1666 hasher.update(b"\0");
1667 }
1668 hex_digest(hasher.finalize())
1669 }
1670
1671 /// Pre-policy capability digest. Tests use this to prove that a v1 trust
1672 /// receipt cannot match the current capability hash.
1673 pub fn capability_hash_v1(inventory: &PluginInventory) -> String {
1674 let mut hasher = Sha256::new();
1675 hasher.update(CAPABILITY_HASH_DOMAIN_V1);
1676 for (key, value) in hash_inventory_counts(inventory) {
1677 hasher.update(key.as_bytes());
1678 hasher.update(b"\0");
1679 hasher.update(value.as_bytes());
1680 hasher.update(b"\0");
1681 }
1682 hex_digest(hasher.finalize())
1683 }
1684
1685 /// Historical v2 capability digest. Kept only to prove that receipts from the
1686 /// Skills/MCP-only activation policy fail closed when v3 enables additional
1687 /// declarative adapters.
1688 /// Catalog and manifest artwork follows one inert, bounded wire format.
1689 pub fn validate_icon(value: &str) -> Result<(), String> {
1690 use base64::Engine;
1691 if value.len() > 32_768 {
1692 return Err("plugin icon exceeds 32 KiB".into());
1693 }
1694 let encoded = value
1695 .strip_prefix("data:image/png;base64,")
1696 .ok_or("plugin icon must be an inline PNG")?;
1697 let bytes = base64::engine::general_purpose::STANDARD
1698 .decode(encoded)
1699 .map_err(|_| "plugin icon has invalid base64")?;
1700 if bytes.len() < 33 || &bytes[..8] != b"\x89PNG\r\n\x1a\n" || &bytes[12..16] != b"IHDR" {
1701 return Err("plugin icon has an invalid PNG header".into());
1702 }
1703 let width = u32::from_be_bytes(bytes[16..20].try_into().map_err(|_| "invalid PNG width")?);
1704 let height = u32::from_be_bytes(bytes[20..24].try_into().map_err(|_| "invalid PNG height")?);
1705 if width == 0 || height == 0 || width > 256 || height > 256 {
1706 return Err("plugin icon must fit within 256 by 256 pixels".into());
1707 }
1708 Ok(())
1709 }
1710
1711 #[cfg(any(test, feature = "test-support"))]
1712 pub fn capability_hash_v2(inventory: &PluginInventory) -> String {
1713 let mut hasher = Sha256::new();
1714 hasher.update(CAPABILITY_HASH_DOMAIN_V2);
1715 hasher.update(b"policy-version\0");
1716 hasher.update(b"2\0");
1717 for capability in [
1718 PluginActivationCapability::Skills,
1719 PluginActivationCapability::McpStdio,
1720 PluginActivationCapability::McpRemote,
1721 ] {
1722 hasher.update(b"supported\0");
1723 hasher.update(capability.as_str().as_bytes());
1724 hasher.update(b"\0");
1725 }
1726 for capability in [
1727 PluginActivationCapability::Commands,
1728 PluginActivationCapability::Agents,
1729 PluginActivationCapability::Hooks,
1730 PluginActivationCapability::Lsp,
1731 PluginActivationCapability::Native,
1732 PluginActivationCapability::FilesystemRoots,
1733 PluginActivationCapability::LifecycleMutation,
1734 ] {
1735 hasher.update(b"inactive\0");
1736 hasher.update(capability.as_str().as_bytes());
1737 hasher.update(b"\0");
1738 }
1739 for (key, value) in hash_inventory_counts(inventory) {
1740 hasher.update(key.as_bytes());
1741 hasher.update(b"\0");
1742 hasher.update(value.as_bytes());
1743 hasher.update(b"\0");
1744 }
1745 hex_digest(hasher.finalize())
1746 }
1747
1748 #[cfg(any(test, feature = "test-support"))]
1749 pub fn capability_hash_with_policy(
1750 inventory: &PluginInventory,
1751 policy: PluginActivationPolicy,
1752 ) -> String {
1753 hash_inventory_with_policy(inventory, policy)
1754 }
1755
1756 pub(super) fn hex_digest(bytes: impl AsRef<[u8]>) -> String {
1757 let bytes = bytes.as_ref();
1758 let mut output = String::with_capacity(bytes.len() * 2);
1759 for byte in bytes {
1760 use std::fmt::Write as _;
1761 let _ = write!(output, "{byte:02x}");
1762 }
1763 output
1764 }
1765
1766 #[cfg(test)]
1767 mod tests {
1768 use super::*;
1769
1770 fn write_manifest(root: &Path, extra: &str) -> PathBuf {
1771 fs::create_dir_all(root.join("skills/example")).unwrap();
1772 fs::write(
1773 root.join("skills/example/SKILL.md"),
1774 "---\nname: example\ndescription: example\n---\nbody\n",
1775 )
1776 .unwrap();
1777 let path = root.join("plugin.toml");
1778 fs::write(
1779 &path,
1780 format!(
1781 "schema_version = 1\n[plugin]\nname = \"example-plugin\"\nversion = \"1.2.3\"\n[skills]\npath = \"skills\"\n{extra}"
1782 ),
1783 )
1784 .unwrap();
1785 path
1786 }
1787
1788 #[test]
1789 fn validates_versioned_manifest_and_hashes_declared_content() {
1790 let tmp = tempfile::tempdir().unwrap();
1791 let path = write_manifest(tmp.path(), "");
1792 let first = PluginManifest::validate_from_path(&path).unwrap();
1793 assert_eq!(first.inventory.skills, 1);
1794 assert!(first.warnings.is_empty());
1795
1796 fs::write(
1797 tmp.path().join("skills/example/SKILL.md"),
1798 "---\nname: example\ndescription: changed\n---\nbody\n",
1799 )
1800 .unwrap();
1801 let second = PluginManifest::validate_from_path(&path).unwrap();
1802 assert_ne!(first.content_hash, second.content_hash);
1803 assert_eq!(first.capability_hash, second.capability_hash);
1804 }
1805
1806 #[test]
1807 fn native_entry_receipt_is_plain_same_read_digest_without_changing_bundle_hashes() {
1808 let tmp = tempfile::tempdir().unwrap();
1809 fs::create_dir_all(tmp.path().join("native")).unwrap();
1810 let entry_bytes = b"export function apply() {}\n";
1811 fs::write(tmp.path().join("native/index.mjs"), entry_bytes).unwrap();
1812 fs::write(
1813 tmp.path().join("native/undeclared.mjs"),
1814 b"export const sidecar = 1",
1815 )
1816 .unwrap();
1817 let manifest = write_manifest(tmp.path(), "[native]\npath = \"native/index.mjs\"\n");
1818 let first = PluginManifest::validate_from_path(&manifest).unwrap();
1819 let relative = PathBuf::from("native/index.mjs");
1820 let plain = hex_digest(Sha256::digest(entry_bytes));
1821 let mut domain = Sha256::new();
1822 domain.update(b"codewhale-plugin-file-bytes-v1\0");
1823 domain.update(entry_bytes);
1824 assert_eq!(first.native_entry_hashes.len(), 1);
1825 assert_eq!(first.native_entry_hashes[&relative], plain);
1826 assert_eq!(first.file_hashes[&relative], hex_digest(domain.finalize()));
1827 assert_ne!(
1828 first.file_hashes[&relative],
1829 first.native_entry_hashes[&relative]
1830 );
1831 assert!(
1832 !first
1833 .native_entry_hashes
1834 .contains_key(Path::new("native/undeclared.mjs"))
1835 );
1836
1837 // The purpose-specific capture adds no bytes to the established
1838 // bundle domain or its complete regular-file inventory.
1839 let manifest_bytes = fs::read(&manifest).unwrap();
1840 let (without_entries, without_entry_hashes) =
1841 hash_bundle(&first.canonical_root, &manifest_bytes, "plugin.toml", &[]).unwrap();
1842 assert_eq!(first.content_hash, without_entries);
1843 assert_eq!(first.file_hashes, without_entry_hashes.file_hashes);
1844 assert!(without_entry_hashes.native_entry_hashes.is_empty());
1845
1846 // Undeclared companions remain whole-bundle authority even though
1847 // they receive no Native EntryRef digest.
1848 fs::write(
1849 tmp.path().join("native/undeclared.mjs"),
1850 b"export const sidecar = 2",
1851 )
1852 .unwrap();
1853 let changed_sidecar = PluginManifest::validate_from_path(&manifest).unwrap();
1854 assert_ne!(first.content_hash, changed_sidecar.content_hash);
1855 assert_eq!(
1856 first.native_entry_hashes,
1857 changed_sidecar.native_entry_hashes
1858 );
1859 fs::write(
1860 tmp.path().join("native/index.mjs"),
1861 b"export function changed() {}\n",
1862 )
1863 .unwrap();
1864 let changed_entry = PluginManifest::validate_from_path(&manifest).unwrap();
1865 assert_ne!(changed_sidecar.content_hash, changed_entry.content_hash);
1866 assert_ne!(
1867 first.native_entry_hashes[&relative],
1868 changed_entry.native_entry_hashes[&relative]
1869 );
1870 }
1871
1872 #[test]
1873 fn ordinary_native_entry_receipt_keeps_bundle_limit_beyond_preset_metadata_cap() {
1874 let tmp = tempfile::tempdir().unwrap();
1875 fs::create_dir_all(tmp.path().join("native")).unwrap();
1876 let bytes = format!(
1877 "// {}\nexport function apply() {{}}\n",
1878 "x".repeat(32 * 1024)
1879 );
1880 fs::write(tmp.path().join("native/index.mjs"), &bytes).unwrap();
1881 let manifest = write_manifest(tmp.path(), "[native]\npath = \"native/index.mjs\"\n");
1882 let validated = PluginManifest::validate_from_path(&manifest).unwrap();
1883 assert_eq!(validated.inventory.native, 1);
1884 assert_eq!(
1885 validated.native_entry_hashes[Path::new("native/index.mjs")],
1886 hex_digest(Sha256::digest(bytes.as_bytes()))
1887 );
1888 }
1889
1890 #[test]
1891 fn validates_deep_bundle_on_small_stack() {
1892 let tmp = tempfile::tempdir().unwrap();
1893 let manifest = write_manifest(tmp.path(), "");
1894 let mut nested = tmp.path().join("nested");
1895 for level in 0..8 {
1896 nested = nested.join(format!("level-{level}"));
1897 }
1898 fs::create_dir_all(&nested).unwrap();
1899 fs::write(nested.join("payload.txt"), "nested bundle payload").unwrap();
1900
1901 let worker = std::thread::Builder::new()
1902 .name("plugin-small-stack-validation".to_string())
1903 .stack_size(512 * 1024)
1904 .spawn(move || PluginManifest::validate_from_path(&manifest))
1905 .unwrap();
1906 let validated = worker
1907 .join()
1908 .expect("nested plugin validation must not overflow a small stack")
1909 .expect("nested plugin bundle must validate");
1910 assert_eq!(validated.inventory.skills, 1);
1911 }
1912
1913 #[test]
1914 fn bundle_hash_is_deterministic_and_covers_undeclared_companion_files() {
1915 let left = tempfile::tempdir().unwrap();
1916 let right = tempfile::tempdir().unwrap();
1917 let left_manifest = write_manifest(left.path(), "");
1918 let right_manifest = write_manifest(right.path(), "");
1919 fs::write(left.path().join("z.txt"), "z").unwrap();
1920 fs::write(left.path().join("a.txt"), "a").unwrap();
1921 fs::write(right.path().join("a.txt"), "a").unwrap();
1922 fs::write(right.path().join("z.txt"), "z").unwrap();
1923
1924 let left_hash = PluginManifest::validate_from_path(&left_manifest).unwrap();
1925 let right_hash = PluginManifest::validate_from_path(&right_manifest).unwrap();
1926 assert_eq!(left_hash.content_hash, right_hash.content_hash);
1927 assert_eq!(left_hash.capability_hash, right_hash.capability_hash);
1928
1929 fs::write(right.path().join("z.txt"), "changed").unwrap();
1930 let changed = PluginManifest::validate_from_path(&right_manifest).unwrap();
1931 assert_ne!(right_hash.content_hash, changed.content_hash);
1932 assert_eq!(right_hash.capability_hash, changed.capability_hash);
1933 }
1934
1935 #[cfg(unix)]
1936 #[test]
1937 fn bundle_hash_frames_adversarial_binary_records() {
1938 let left = tempfile::tempdir().unwrap();
1939 let right = tempfile::tempdir().unwrap();
1940 let manifest = b"schema_version = 1\n[plugin]\nname = \"framing\"\nversion = \"1.0.0\"\n";
1941 for root in [left.path(), right.path()] {
1942 fs::write(root.join("plugin.toml"), manifest).unwrap();
1943 }
1944
1945 fs::write(left.path().join("a.bin"), b"alpha").unwrap();
1946 fs::write(left.path().join("b.bin"), b"omega").unwrap();
1947
1948 let mut adversarial = b"alpha\0unix-executable\0\0F\0codewhale-os-path-v1\0".to_vec();
1949 adversarial.extend_from_slice(&(b"bundle-relative-file".len() as u64).to_le_bytes());
1950 adversarial.extend_from_slice(b"bundle-relative-file");
1951 adversarial.extend_from_slice(b"unix-bytes\0");
1952 adversarial.extend_from_slice(&(b"b.bin".len() as u64).to_le_bytes());
1953 adversarial.extend_from_slice(b"b.bin");
1954 adversarial.extend_from_slice(b"omega");
1955 fs::write(right.path().join("a.bin"), adversarial).unwrap();
1956
1957 let left = PluginManifest::validate_from_path(&left.path().join("plugin.toml")).unwrap();
1958 let right = PluginManifest::validate_from_path(&right.path().join("plugin.toml")).unwrap();
1959 assert_ne!(left.content_hash, right.content_hash);
1960 assert_eq!(left.capability_hash, right.capability_hash);
1961 }
1962
1963 // Darwin rejects these malformed bytes at the filesystem boundary. The
1964 // platform-independent native-path framing is covered in path_identity;
1965 // run this full bundle-walk regression where Unix permits the entries.
1966 #[cfg(all(unix, not(target_os = "macos")))]
1967 #[test]
1968 fn bundle_hash_distinguishes_lossy_colliding_native_file_names() {
1969 use std::ffi::OsString;
1970 use std::os::unix::ffi::OsStringExt as _;
1971
1972 let left = tempfile::tempdir().unwrap();
1973 let right = tempfile::tempdir().unwrap();
1974 let left_manifest = write_manifest(left.path(), "");
1975 let right_manifest = write_manifest(right.path(), "");
1976 let left_name = OsString::from_vec(vec![b'a', 0xff]);
1977 let right_name = OsString::from_vec(vec![b'a', 0xfe]);
1978 assert_eq!(left_name.to_string_lossy(), right_name.to_string_lossy());
1979 fs::write(left.path().join(left_name), "same bytes").unwrap();
1980 fs::write(right.path().join(right_name), "same bytes").unwrap();
1981
1982 let left = PluginManifest::validate_from_path(&left_manifest).unwrap();
1983 let right = PluginManifest::validate_from_path(&right_manifest).unwrap();
1984 assert_ne!(left.content_hash, right.content_hash);
1985 }
1986
1987 #[test]
1988 fn legacy_manifest_is_accepted_with_migration_warning() {
1989 let tmp = tempfile::tempdir().unwrap();
1990 fs::write(
1991 tmp.path().join("plugin.toml"),
1992 "[plugin]\nname = \"legacy\"\n",
1993 )
1994 .unwrap();
1995 let validated =
1996 PluginManifest::validate_from_path(&tmp.path().join("plugin.toml")).unwrap();
1997 assert_eq!(validated.manifest.schema_version, 0);
1998 assert_eq!(validated.manifest.plugin.version, "0.0.0");
1999 assert_eq!(validated.warnings.len(), 2);
2000 }
2001
2002 #[test]
2003 fn rejects_unknown_fields_invalid_names_and_versions() {
2004 let invalid = [
2005 "schema_version = 1\nunknown = true\n[plugin]\nname = \"ok\"\nversion = \"1.0.0\"\n",
2006 "schema_version = 1\n[plugin]\nname = \"Bad_Name\"\nversion = \"1.0.0\"\n",
2007 "schema_version = 1\n[plugin]\nname = \"ok\"\nversion = \"latest\"\n",
2008 "schema_version = 1\n[plugin]\nname = \"ok\"\n",
2009 ];
2010 for source in invalid {
2011 let tmp = tempfile::tempdir().unwrap();
2012 let path = tmp.path().join("plugin.toml");
2013 fs::write(&path, source).unwrap();
2014 assert!(PluginManifest::validate_from_path(&path).is_err());
2015 }
2016 }
2017
2018 #[test]
2019 fn parse_diagnostics_do_not_echo_manifest_values() {
2020 let tmp = tempfile::tempdir().unwrap();
2021 let path = tmp.path().join("plugin.toml");
2022 fs::write(
2023 &path,
2024 "schema_version = 1\n[plugin]\nname = \"safe\"\nversion = \"1.0.0\"\ndescription = [\"sk-sensitive-value\"]\n",
2025 )
2026 .unwrap();
2027 let error = PluginManifest::validate_from_path(&path).unwrap_err();
2028 assert!(!error.contains("sk-sensitive-value"));
2029 }
2030
2031 #[test]
2032 fn rejects_parent_absolute_and_windows_absolute_component_paths() {
2033 for bad in [
2034 "../escape",
2035 "/tmp/escape",
2036 r"C:\\escape",
2037 r"\\\\server\\share",
2038 ] {
2039 let tmp = tempfile::tempdir().unwrap();
2040 let path = write_manifest(tmp.path(), &format!("\n[commands]\npath = {bad:?}\n"));
2041 assert!(
2042 PluginManifest::validate_from_path(&path).is_err(),
2043 "accepted {bad}"
2044 );
2045 }
2046 }
2047
2048 #[cfg(unix)]
2049 #[test]
2050 fn rejects_symlinked_component_and_nested_symlink() {
2051 use std::os::unix::fs::symlink;
2052
2053 let outside = tempfile::tempdir().unwrap();
2054 fs::write(outside.path().join("SKILL.md"), "# outside").unwrap();
2055
2056 let tmp = tempfile::tempdir().unwrap();
2057 let path = write_manifest(tmp.path(), "");
2058 fs::remove_dir_all(tmp.path().join("skills")).unwrap();
2059 symlink(outside.path(), tmp.path().join("skills")).unwrap();
2060 assert!(PluginManifest::validate_from_path(&path).is_err());
2061
2062 fs::remove_file(tmp.path().join("skills")).unwrap();
2063 fs::create_dir_all(tmp.path().join("skills/example")).unwrap();
2064 fs::write(tmp.path().join("skills/example/SKILL.md"), "# safe").unwrap();
2065 symlink(
2066 outside.path().join("SKILL.md"),
2067 tmp.path().join("skills/example/linked.md"),
2068 )
2069 .unwrap();
2070 assert!(PluginManifest::validate_from_path(&path).is_err());
2071 }
2072
2073 #[cfg(unix)]
2074 #[test]
2075 fn rejects_symlinked_manifest() {
2076 use std::os::unix::fs::symlink;
2077
2078 let tmp = tempfile::tempdir().unwrap();
2079 let real = tmp.path().join("real.toml");
2080 fs::write(
2081 &real,
2082 "schema_version = 1\n[plugin]\nname = \"linked\"\nversion = \"1.0.0\"\n",
2083 )
2084 .unwrap();
2085 let linked = tmp.path().join("plugin.toml");
2086 symlink(&real, &linked).unwrap();
2087
2088 assert!(PluginManifest::validate_from_path(&linked).is_err());
2089 }
2090
2091 #[cfg(unix)]
2092 #[test]
2093 fn rejects_symlinked_bundle_root() {
2094 use std::os::unix::fs::symlink;
2095
2096 let tmp = tempfile::tempdir().unwrap();
2097 let real_root = tmp.path().join("real");
2098 fs::create_dir(&real_root).unwrap();
2099 fs::write(
2100 real_root.join("plugin.toml"),
2101 "schema_version = 1\n[plugin]\nname = \"linked-root\"\nversion = \"1.0.0\"\n",
2102 )
2103 .unwrap();
2104 let linked_root = tmp.path().join("linked");
2105 symlink(&real_root, &linked_root).unwrap();
2106
2107 assert!(PluginManifest::validate_from_path(&linked_root.join("plugin.toml")).is_err());
2108 }
2109
2110 #[test]
2111 fn rejects_absolute_mcp_arguments_and_embedded_url_credentials() {
2112 let absolute = tempfile::tempdir().unwrap();
2113 let absolute_path = write_manifest(
2114 absolute.path(),
2115 "\n[mcp_servers.local]\ncommand = \"node\"\nargs = [\"/tmp/server.js\"]\n",
2116 );
2117 assert!(PluginManifest::validate_from_path(&absolute_path).is_err());
2118
2119 let credentialed = tempfile::tempdir().unwrap();
2120 let credentialed_path = write_manifest(
2121 credentialed.path(),
2122 "\n[mcp_servers.remote]\nurl = \"https://user:secret@example.invalid/mcp\"\n",
2123 );
2124 assert!(PluginManifest::validate_from_path(&credentialed_path).is_err());
2125 }
2126
2127 #[test]
2128 fn windows_rooted_path_detection_is_host_independent() {
2129 assert!(looks_windows_absolute(r"C:\plugins\server.js"));
2130 assert!(looks_windows_absolute(r"C:/plugins/server.js"));
2131 assert!(looks_windows_absolute(r"\plugins\server.js"));
2132 assert!(looks_windows_absolute("/plugins/server.js"));
2133 assert!(!looks_windows_absolute("plugins/server.js"));
2134 assert!(!looks_windows_absolute("server.js"));
2135 }
2136
2137 #[cfg(windows)]
2138 #[test]
2139 fn retained_bundle_handle_allows_identity_revalidation_but_denies_writes() {
2140 use std::os::windows::fs::OpenOptionsExt as _;
2141
2142 let directory = tempfile::tempdir().unwrap();
2143 let path = directory.path().join("reviewed.bin");
2144 fs::write(&path, b"reviewed").unwrap();
2145 let retained = codewhale_util::bundle_file::open_bundle_file(&path).unwrap();
2146
2147 ensure_windows_path_still_opened(&path, &retained).unwrap();
2148 let denied = fs::OpenOptions::new()
2149 .write(true)
2150 .share_mode(0x0000_0007)
2151 .open(&path);
2152 assert!(denied.is_err(), "retained authority must deny mutation");
2153
2154 drop(retained);
2155 fs::OpenOptions::new().write(true).open(&path).unwrap();
2156 }
2157
2158 #[test]
2159 fn unsupported_capabilities_are_inventoried() {
2160 let tmp = tempfile::tempdir().unwrap();
2161 fs::create_dir_all(tmp.path().join("hooks")).unwrap();
2162 let path = write_manifest(
2163 tmp.path(),
2164 "\n[hooks]\npath = \"hooks\"\n[capabilities]\nfilesystem_roots = [\"workspace\"]\nlifecycle_mutation = true\n",
2165 );
2166 let validated = PluginManifest::validate_from_path(&path).unwrap();
2167 assert!(validated.inventory.has_unsupported_capabilities());
2168 assert!(validated.inventory.supported_labels().contains(&"hooks"));
2169 assert!(
2170 validated
2171 .inventory
2172 .unsupported_labels()
2173 .contains(&"filesystem-roots")
2174 );
2175 assert_eq!(
2176 validated.inventory.compatibility(),
2177 PluginCompatibility::Partial,
2178 "Skills and Hooks activate while explicit filesystem/lifecycle capabilities stay inactive"
2179 );
2180 assert!(validated.inventory.can_activate_supported_components());
2181 }
2182
2183 #[test]
2184 fn mixed_supported_and_unsupported_components_are_partial() {
2185 let tmp = tempfile::tempdir().unwrap();
2186 fs::create_dir_all(tmp.path().join("commands")).unwrap();
2187 fs::create_dir_all(tmp.path().join("lsp")).unwrap();
2188 let path = write_manifest(
2189 tmp.path(),
2190 "\n[commands]\npath = \"commands\"\n[lsp]\npath = \"lsp\"\n",
2191 );
2192 let validated = PluginManifest::validate_from_path(&path).unwrap();
2193 assert!(validated.inventory.has_supported_components());
2194 assert!(validated.inventory.has_unsupported_capabilities());
2195 assert_eq!(
2196 validated.inventory.supported_labels(),
2197 vec!["skills", "commands"]
2198 );
2199 assert_eq!(validated.inventory.unsupported_labels(), vec!["lsp"]);
2200 assert_eq!(
2201 validated.inventory.compatibility(),
2202 PluginCompatibility::Partial
2203 );
2204 assert!(validated.inventory.can_activate_supported_components());
2205 }
2206
2207 #[test]
2208 fn asked_host_services_move_the_capability_hash_and_none_keeps_it() {
2209 let tmp = tempfile::tempdir().unwrap();
2210 let plain = PluginManifest::validate_from_path(&write_manifest(tmp.path(), "")).unwrap();
2211 assert!(plain.inventory.host_services.is_empty());
2212 let mut before = Sha256::new();
2213 PluginActivationPolicy::current().write_hash_material(&mut before);
2214 let inventory = &plain.inventory;
2215 for (key, value) in [
2216 ("agents", inventory.agents.to_string()),
2217 ("commands", inventory.commands.to_string()),
2218 ("filesystem", inventory.filesystem_roots.join("\n")),
2219 ("hooks", inventory.hooks.to_string()),
2220 ("lifecycle", inventory.lifecycle_mutation.to_string()),
2221 ("lsp", inventory.lsp.to_string()),
2222 ("mcp", inventory.mcp_servers.to_string()),
2223 ("mcp-remote", inventory.remote_mcp_servers.to_string()),
2224 ("mcp-stdio", inventory.stdio_mcp_servers.to_string()),
2225 ("native", inventory.native.to_string()),
2226 ("network", inventory.network_hosts.join("\n")),
2227 ("providers", inventory.providers.to_string()),
2228 ("skills", inventory.skills.to_string()),
2229 ] {
2230 before.update(key.as_bytes());
2231 before.update(b"\0");
2232 before.update(value.as_bytes());
2233 before.update(b"\0");
2234 }
2235 assert_eq!(
2236 plain.capability_hash,
2237 hex_digest(before.finalize()),
2238 "a bundle that asks for nothing hashes exactly as it did before"
2239 );
2240 assert!(!plain.inventory.summary().contains("host_services"));
2241 assert!(
2242 !serde_json::to_string(&plain.inventory)
2243 .unwrap()
2244 .contains("host_services")
2245 );
2246
2247 let asked = |list: &str| {
2248 PluginManifest::validate_from_path(&write_manifest(
2249 tmp.path(),
2250 &format!("[capabilities]\nhost_services = [{list}]\n"),
2251 ))
2252 };
2253 let network = asked("\"network\"").unwrap();
2254 assert_eq!(network.inventory.host_services, vec![HostService::Network]);
2255 assert_ne!(network.capability_hash, plain.capability_hash);
2256 assert!(
2257 network
2258 .inventory
2259 .summary()
2260 .ends_with(" host_services=network")
2261 );
2262 let both = asked("\"network\", \"llm\"").unwrap();
2263 assert_eq!(
2264 both.inventory.host_services,
2265 vec![HostService::Llm, HostService::Network]
2266 );
2267 assert_ne!(both.capability_hash, network.capability_hash);
2268 assert_eq!(
2269 both.capability_hash,
2270 asked("\"llm\", \"network\"").unwrap().capability_hash
2271 );
2272 let reread: PluginInventory =
2273 serde_json::from_str(&serde_json::to_string(&both.inventory).unwrap()).unwrap();
2274 assert_eq!(reread, both.inventory);
2275 assert!(asked("\"everything\"").is_err());
2276 assert!(
2277 asked("\"llm\", \"llm\"")
2278 .unwrap_err()
2279 .contains("duplicate host service")
2280 );
2281 }
2282
2283 #[test]
2284 fn activation_policy_change_changes_the_capability_hash() {
2285 let inventory = PluginInventory {
2286 skills: 1,
2287 ..PluginInventory::default()
2288 };
2289 let current_policy = PluginActivationPolicy::current();
2290 let current = capability_hash_with_policy(&inventory, current_policy);
2291 let hooks_inactive = PluginActivationPolicy {
2292 version: current_policy.version,
2293 dsh_compatibility: current_policy.dsh_compatibility,
2294 supported: &[
2295 PluginActivationCapability::Skills,
2296 PluginActivationCapability::McpStdio,
2297 PluginActivationCapability::McpRemote,
2298 PluginActivationCapability::Commands,
2299 PluginActivationCapability::Agents,
2300 ],
2301 inactive: &[
2302 PluginActivationCapability::Hooks,
2303 PluginActivationCapability::Lsp,
2304 PluginActivationCapability::Native,
2305 PluginActivationCapability::FilesystemRoots,
2306 PluginActivationCapability::LifecycleMutation,
2307 ],
2308 };
2309 assert_ne!(
2310 current,
2311 capability_hash_with_policy(&inventory, hooks_inactive),
2312 "changing the executable adapter set must move the capability hash"
2313 );
2314 let bumped = PluginActivationPolicy {
2315 version: current_policy.version + 1,
2316 supported: current_policy.supported,
2317 inactive: current_policy.inactive,
2318 dsh_compatibility: current_policy.dsh_compatibility,
2319 };
2320 assert_ne!(
2321 current,
2322 capability_hash_with_policy(&inventory, bumped),
2323 "a policy version bump must move the capability hash"
2324 );
2325 assert_eq!(
2326 current,
2327 capability_hash_with_policy(&inventory, current_policy)
2328 );
2329 assert_ne!(current, capability_hash_v1(&inventory));
2330 }
2331
2332 #[test]
2333 fn all_unsupported_inventory_cannot_activate() {
2334 let tmp = tempfile::tempdir().unwrap();
2335 fs::create_dir_all(tmp.path().join("lsp")).unwrap();
2336 let path = tmp.path().join("plugin.toml");
2337 fs::write(
2338 &path,
2339 "schema_version = 1\n[plugin]\nname = \"lsp-only\"\nversion = \"1.0.0\"\n[lsp]\npath = \"lsp\"\n",
2340 )
2341 .unwrap();
2342 let validated = PluginManifest::validate_from_path(&path).unwrap();
2343 assert!(!validated.inventory.has_supported_components());
2344 assert_eq!(validated.inventory.unsupported_labels(), vec!["lsp"]);
2345 assert_eq!(
2346 validated.inventory.compatibility(),
2347 PluginCompatibility::Unsupported
2348 );
2349 assert!(!validated.inventory.can_activate_supported_components());
2350 }
2351
2352 #[test]
2353 fn plugin_mcp_schema_and_transport_combinations_fail_closed() {
2354 let invalid = [
2355 "\n[mcp_servers.remote]\nurl = \"https://example.invalid/mcp\"\nunknown_nested = true\n[capabilities]\nnetwork_hosts = [\"example.invalid\"]\n",
2356 "\n[mcp_servers.remote]\nurl = \"https://example.invalid/mcp\"\nargs = [\"secret\"]\n[capabilities]\nnetwork_hosts = [\"example.invalid\"]\n",
2357 "\n[mcp_servers.remote]\nurl = \"https://example.invalid/mcp?token=secret\"\n[capabilities]\nnetwork_hosts = [\"example.invalid\"]\n",
2358 "\n[mcp_servers.remote]\nurl = \"http://example.invalid/mcp\"\n[capabilities]\nnetwork_hosts = [\"example.invalid\"]\n",
2359 "\n[mcp_servers.remote]\nurl = \"https://example.invalid/mcp\"\n[capabilities]\nnetwork_hosts = [\"other.invalid\"]\n",
2360 "\n[mcp_servers.local]\ncommand = \"node\"\ntransport = \"sse\"\n",
2361 "\n[mcp_servers.local]\ncommand = \"node\"\nconnect_timeout = 0\n",
2362 "\n[mcp_servers.local]\ncommand = \"node\"\nenabled_tools = [\"same\"]\ndisabled_tools = [\"same\"]\n",
2363 "\n[mcp_servers.local]\ncommand = \"node\"\n[mcp_servers.local.env]\nTOKEN = \"literal-secret\"\n",
2364 "\n[mcp_servers.remote]\nurl = \"https://example.invalid/mcp\"\n[mcp_servers.remote.headers]\nAuthorization = \"literal-secret\"\n[capabilities]\nnetwork_hosts = [\"example.invalid\"]\n",
2365 "\n[mcp_servers.remote]\nurl = \"https://example.invalid/mcp\"\n[mcp_servers.remote.oauth]\nclient_id = \"public\"\nsecret = \"must-not-parse\"\n[capabilities]\nnetwork_hosts = [\"example.invalid\"]\n",
2366 ];
2367 for extra in invalid {
2368 let tmp = tempfile::tempdir().unwrap();
2369 let path = write_manifest(tmp.path(), extra);
2370 assert!(
2371 PluginManifest::validate_from_path(&path).is_err(),
2372 "accepted invalid plugin MCP manifest: {extra}"
2373 );
2374 }
2375 }
2376
2377 #[test]
2378 fn plugin_mcp_remote_allowlist_and_env_provenance_are_exact() {
2379 let tmp = tempfile::tempdir().unwrap();
2380 let path = write_manifest(
2381 tmp.path(),
2382 r#"
2383 [mcp_servers.remote]
2384 url = "https://Example.Invalid:8443/mcp/v1"
2385 transport = "sse"
2386 connect_timeout = 30
2387 execute_timeout = 120
2388 read_timeout = 180
2389 required = true
2390 enabled_tools = ["read"]
2391 disabled_tools = ["write"]
2392 bearer_token_env_var = "PLUGIN_BEARER"
2393
2394 [mcp_servers.remote.env_headers]
2395 X_Api_Key = "PLUGIN_API_KEY"
2396
2397 [capabilities]
2398 network_hosts = ["example.invalid"]
2399 "#,
2400 );
2401 let validated = PluginManifest::validate_from_path(&path).unwrap();
2402 assert_eq!(
2403 validated.inventory.network_hosts,
2404 vec!["example.invalid".to_string()]
2405 );
2406 assert_eq!(validated.inventory.remote_mcp_servers, 1);
2407 }
2408
2409 #[test]
2410 fn plugin_mcp_oauth_fields_are_rejected_for_v091() {
2411 for oauth_fields in [
2412 "scopes = [\"tools.read\"]\n",
2413 "oauth_resource = \"https://resource.invalid/mcp\"\n",
2414 "[mcp_servers.remote.oauth]\nclient_id = \"public-client-id\"\n",
2415 ] {
2416 let tmp = tempfile::tempdir().unwrap();
2417 let path = write_manifest(
2418 tmp.path(),
2419 &format!(
2420 "\n[mcp_servers.remote]\nurl = \"https://example.invalid/mcp\"\n{oauth_fields}[capabilities]\nnetwork_hosts = [\"example.invalid\"]\n"
2421 ),
2422 );
2423 let error = PluginManifest::validate_from_path(&path)
2424 .expect_err("plugin OAuth authority must remain disabled");
2425 assert!(error.contains("plugin OAuth is disabled"));
2426 }
2427 }
2428
2429 #[test]
2430 fn reviewed_stdio_argv_rejects_literal_credentials_but_accepts_exact_safe_values() {
2431 for args in [
2432 r#"["server.js", "--token", "literal-secret"]"#,
2433 r#"["server.js", "--api-key=literal-secret"]"#,
2434 r#"["server.js", "sk-live-literal"]"#,
2435 ] {
2436 let tmp = tempfile::tempdir().unwrap();
2437 fs::write(tmp.path().join("server.js"), "// entrypoint\n").unwrap();
2438 let path = write_manifest(
2439 tmp.path(),
2440 &format!("\n[mcp_servers.local]\ncommand = \"node\"\nargs = {args}\n"),
2441 );
2442 let error = PluginManifest::validate_from_path(&path)
2443 .expect_err("credential-bearing argv must fail closed");
2444 assert!(error.contains("credential"), "{error}");
2445 }
2446
2447 let safe = tempfile::tempdir().unwrap();
2448 fs::write(safe.path().join("server.js"), "// entrypoint\n").unwrap();
2449 let path = write_manifest(
2450 safe.path(),
2451 r#"
2452 [mcp_servers.local]
2453 command = "node"
2454 args = ["server.js", "--mode=worker", "-e", "console.log('ready')"]
2455 "#,
2456 );
2457 PluginManifest::validate_from_path(&path)
2458 .expect("safe interpreter argv should remain reviewable exactly");
2459 }
2460
2461 #[test]
2462 fn manifest_text_rejects_controls_and_bidirectional_spoofing() {
2463 for unsafe_text in ["line\nbreak", "safe\u{202e}lmot.nigulp"] {
2464 let tmp = tempfile::tempdir().unwrap();
2465 let path = tmp.path().join("plugin.toml");
2466 fs::write(
2467 &path,
2468 format!(
2469 "schema_version = 1\n[plugin]\nname = \"safe\"\nversion = \"1.0.0\"\nauthor = {unsafe_text:?}\n"
2470 ),
2471 )
2472 .unwrap();
2473 assert!(PluginManifest::validate_from_path(&path).is_err());
2474 }
2475 }
2476 }
2477
2478 #[cfg(test)]
2479 mod icon_tests {
2480 use super::validate_icon;
2481 use base64::Engine;
2482
2483 #[test]
2484 fn artwork_is_inline_bounded_png_only() {
2485 let catalog: serde_json::Value =
2486 serde_json::from_str(include_str!("../assets/first-party-marketplace.json")).unwrap();
2487 let icon = catalog["catalog"]["plugins"]
2488 .as_array()
2489 .unwrap()
2490 .iter()
2491 .find(|entry| entry["name"] == "computer-use")
2492 .unwrap()["icon"]
2493 .as_str()
2494 .unwrap();
2495 assert!(validate_icon(icon).is_ok());
2496 for invalid in [
2497 "https://publisher.example/tracker.png",
2498 "data:image/svg+xml,<svg/>",
2499 "data:image/png;base64,invalid",
2500 ] {
2501 assert!(validate_icon(invalid).is_err());
2502 }
2503 let mut png = base64::engine::general_purpose::STANDARD
2504 .decode(icon.strip_prefix("data:image/png;base64,").unwrap())
2505 .unwrap();
2506 png[16..20].copy_from_slice(&100_000_u32.to_be_bytes());
2507 assert!(
2508 validate_icon(&format!(
2509 "data:image/png;base64,{}",
2510 base64::engine::general_purpose::STANDARD.encode(png)
2511 ))
2512 .is_err()
2513 );
2514 assert!(validate_icon(&"x".repeat(32_769)).is_err());
2515 }
2516 }
2517
2517 lines RUST