返回 CodeWhale
document.rs
根目录 / crates / plugins / src / marketplace / document.rs
1 //! Local catalog document loading shared by the `/plugin marketplace add`
2 //! command and the Runtime API marketplace endpoints (#5311 surface).
3 //!
4 //! One loader so both entry points apply the same rules: LOCAL file only
5 //! (never network), bounded size, no symlink documents, strict per-format
6 //! parsing, and refusal to persist a document that parsed to nothing but
7 //! errors. Candidate→install-spec resolution also lives here so the TUI
8 //! command and the HTTP API can never disagree about what would be fetched.
9
10 use std::io::Read;
11 use std::path::{Component, Path, PathBuf};
12
13 use super::parsers::{self, MarketplaceDocument};
14 use super::store::StoredMarketplaceCatalog;
15 use super::types::{
16 MarketplaceCandidate, MarketplaceCatalogId, MarketplaceFormat, MarketplaceInstallPlan,
17 MarketplaceSourceSpec,
18 };
19
20 /// Catalog documents are JSON text; four megabytes is far beyond any real
21 /// published catalog and caps the parse cost of a user-supplied file.
22 const MAX_CATALOG_BYTES: u64 = 4 * 1024 * 1024;
23
24 /// A parsed catalog ready to store, plus the counts callers render back.
25 #[derive(Debug)]
26 pub struct LoadedCatalogDocument {
27 pub entry: StoredMarketplaceCatalog,
28 pub candidate_count: usize,
29 pub warning_count: usize,
30 }
31
32 /// Conservative catalog name: it becomes a key, appears in candidate IDs,
33 /// and is rendered back to the operator.
34 #[must_use]
35 pub fn valid_marketplace_name(name: &str) -> bool {
36 !name.is_empty()
37 && name.len() <= 64
38 && name
39 .chars()
40 .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_' || c == '.')
41 }
42
43 /// Read and parse a LOCAL catalog document. Relative paths resolve against
44 /// `workspace`. No network is touched, here or anywhere in this module.
45 pub fn load_catalog_document(
46 name: &str,
47 workspace: &Path,
48 raw_path: &str,
49 ) -> Result<LoadedCatalogDocument, String> {
50 if !valid_marketplace_name(name) {
51 return Err(
52 "Marketplace name must be 1-64 characters of letters, digits, `-`, `_`, or `.`"
53 .to_string(),
54 );
55 }
56 let path = PathBuf::from(raw_path.trim());
57 let path = if path.is_absolute() {
58 path
59 } else {
60 workspace.join(path)
61 };
62 let path = canonical_document(&path)?;
63 let body = read_bounded(&path)?;
64 let root = serde_json::from_str::<serde_json::Value>(&body)
65 .map_err(|error| format!("Catalog at {} is not valid JSON: {error}", path.display()))?;
66
67 let document = MarketplaceDocument {
68 catalog_id: MarketplaceCatalogId::new(name),
69 format: if path.ends_with(".github/plugin/marketplace.json")
70 || path.ends_with(".plugin/marketplace.json")
71 {
72 MarketplaceFormat::Claude
73 } else {
74 MarketplaceFormat::Auto
75 },
76 root,
77 base: Some(path.display().to_string()),
78 };
79 let catalog = parsers::parse_catalog(document);
80
81 // A document-level error (unknown/ambiguous format, not-an-object) means
82 // nothing useful was parsed; do not persist it.
83 if catalog.candidates.is_empty() && catalog.error_count() > 0 {
84 return Err(format!(
85 "Catalog `{name}` could not be parsed as any known marketplace format (kimi, claude, codex, dsh, codewhale):\n{}",
86 render_diagnostics_inline(&catalog.diagnostics)
87 ));
88 }
89
90 let entry = StoredMarketplaceCatalog {
91 added_at: chrono::Utc::now().to_rfc3339(),
92 source_path: path.display().to_string(),
93 catalog,
94 };
95 Ok(LoadedCatalogDocument {
96 candidate_count: entry.catalog.total_candidates(),
97 warning_count: entry.catalog.warning_count(),
98 entry,
99 })
100 }
101
102 /// What installing a stored candidate would do, resolved once for every
103 /// caller. `Supported.spec` is exactly what the reviewed installer accepts.
104 pub enum CatalogInstallResolution<'a> {
105 Supported {
106 spec: String,
107 source_kind: String,
108 },
109 /// A matching name is occupied; catalog metadata does not prove identity.
110 AlreadyPresent {
111 plugin: &'a crate::types::LoadedPlugin,
112 reason: String,
113 },
114 Unsupported {
115 reason: String,
116 },
117 HasErrors {
118 diagnostics: String,
119 },
120 }
121
122 /// Resolve a stored catalog candidate to its install spec. Relative local
123 /// paths resolve against the catalog document's own directory, not the
124 /// caller's working directory.
125 pub fn resolve_candidate_install<'a>(
126 entry: &StoredMarketplaceCatalog,
127 candidate: &MarketplaceCandidate,
128 registry: &'a crate::PluginRegistry,
129 ) -> CatalogInstallResolution<'a> {
130 if candidate.has_errors() {
131 return CatalogInstallResolution::HasErrors {
132 diagnostics: render_diagnostics_inline(&candidate.diagnostics),
133 };
134 }
135 if let Some(plugin) = registry.get(&candidate.name) {
136 if plugin.scope == crate::types::PluginScope::Builtin {
137 // A shipped bundle (Computer Use): the published "install"
138 // command must say so, not read as a failure (B5). The catalog
139 // entry still never replaces it.
140 return CatalogInstallResolution::AlreadyPresent {
141 plugin,
142 reason: format!(
143 "'{}' is built into Codewhale, so there is nothing to install; this catalog entry does not replace it. Review it with /plugin show {}.",
144 plugin.name(),
145 plugin.id.as_str()
146 ),
147 };
148 }
149 return CatalogInstallResolution::AlreadyPresent {
150 plugin,
151 reason: format!(
152 "A {} plugin named '{}' already exists. Review the existing bundle with /plugin show {}. Catalog metadata does not establish that it is the same bundle.",
153 plugin.scope.as_str(),
154 plugin.name(),
155 plugin.id.as_str()
156 ),
157 };
158 }
159 match &candidate.install_plan {
160 MarketplaceInstallPlan::Supported { spec, source_kind } => match resolve_spec(
161 &entry.source_path,
162 entry.catalog.format,
163 &candidate.source,
164 spec,
165 ) {
166 Ok(spec) => CatalogInstallResolution::Supported {
167 spec,
168 source_kind: source_kind.clone(),
169 },
170 Err(reason) => CatalogInstallResolution::Unsupported { reason },
171 },
172 MarketplaceInstallPlan::Unsupported { reason, .. } => {
173 CatalogInstallResolution::Unsupported {
174 reason: reason.clone(),
175 }
176 }
177 }
178 }
179
180 /// A catalog's local source must name a directory inside the catalog's own
181 /// tree. An absolute path, a root or drive prefix, or any `..` component would
182 /// let catalog metadata point the installer at an arbitrary directory on this
183 /// machine, so such an entry is not installable from the catalog; installing a
184 /// directory outside it stays an explicit `/plugin install path:...`.
185 fn resolve_spec(
186 source_path: &str,
187 format: MarketplaceFormat,
188 source: &MarketplaceSourceSpec,
189 spec: &str,
190 ) -> Result<String, String> {
191 if let MarketplaceSourceSpec::LocalPath { path } = source
192 && !path
193 .components()
194 .all(|part| matches!(part, Component::Normal(_) | Component::CurDir))
195 {
196 return Err(format!(
197 "Local catalog source `{}` leaves the catalog directory; only paths inside it (no absolute paths or `..`) are installable from a catalog",
198 path.display()
199 ));
200 }
201 if let MarketplaceSourceSpec::LocalPath { path } = source
202 && let Some(dir) = Path::new(source_path).parent()
203 {
204 let metadata = match format {
205 MarketplaceFormat::Claude if dir.ends_with(".github/plugin") => Some(".github/plugin"),
206 MarketplaceFormat::Claude if dir.ends_with(".claude-plugin") => Some(".claude-plugin"),
207 MarketplaceFormat::Claude if dir.ends_with(".plugin") => Some(".plugin"),
208 MarketplaceFormat::Codex if dir.ends_with(".agents/plugins") => Some(".agents/plugins"),
209 _ => None,
210 };
211 let dir = metadata
212 .and_then(|suffix| dir.ancestors().nth(Path::new(suffix).components().count()))
213 .unwrap_or(dir);
214 let mut target = dir.to_path_buf();
215 for part in path.components() {
216 target.push(part);
217 match std::fs::symlink_metadata(&target) {
218 Ok(metadata)
219 if codewhale_util::path_identity::metadata_is_link_or_reparse(&metadata) =>
220 {
221 return Err(format!(
222 "Catalog path {} contains a symbolic link",
223 target.display()
224 ));
225 }
226 Err(error) if error.kind() != std::io::ErrorKind::NotFound => {
227 return Err(error.to_string());
228 }
229 _ => {}
230 }
231 }
232 return Ok(format!("path:{}", target.display()));
233 }
234 // Every other source kind (GitHub, archive/tarball URL) is remote. The
235 // installer parses the spec again, and any value it does not recognise
236 // as remote is a local directory there — so an archive `url` of `/etc`
237 // or `../..` would bypass the containment check above. Only a spec the
238 // installer's own parser reads as remote is installable from a catalog.
239 match crate::install::PluginInstallSource::parse(spec) {
240 Ok(crate::install::PluginInstallSource::Remote(_)) => Ok(spec.to_string()),
241 _ => Err(format!(
242 "Catalog source `{spec}` is not a remote (github: or http(s)://) source; a catalog may name a local directory only as a path inside the catalog"
243 )),
244 }
245 }
246
247 /// Resolve a user-supplied document path to an existing regular file without
248 /// following a final symlink (the document is untrusted input).
249 fn canonical_document(path: &Path) -> Result<PathBuf, String> {
250 let metadata = std::fs::symlink_metadata(path)
251 .map_err(|e| format!("Cannot read catalog at {}: {e}", path.display()))?;
252 if metadata.is_symlink() {
253 return Err(format!(
254 "Catalog path {} is a symlink; marketplace documents must be regular files",
255 path.display()
256 ));
257 }
258 if !metadata.is_file() {
259 return Err(format!(
260 "Catalog path {} is not a regular file",
261 path.display()
262 ));
263 }
264 Ok(path.to_path_buf())
265 }
266
267 fn read_bounded(path: &Path) -> Result<String, String> {
268 // Validate the opened handle, not just the path checked before opening.
269 let file = crate::registry::open_existing_regular_file(path, false)?
270 .ok_or_else(|| format!("Cannot read catalog at {}: file is missing", path.display()))?;
271 let mut text = String::new();
272 let mut limited = file.take(MAX_CATALOG_BYTES + 1);
273 limited
274 .read_to_string(&mut text)
275 .map_err(|e| format!("Cannot read catalog at {}: {e}", path.display()))?;
276 // Check bytes actually read: the file can grow after its metadata is read.
277 if text.len() as u64 > MAX_CATALOG_BYTES {
278 return Err(format!(
279 "Catalog at {} exceeds the {} byte limit",
280 path.display(),
281 MAX_CATALOG_BYTES
282 ));
283 }
284 Ok(text)
285 }
286
287 fn render_diagnostics_inline(diagnostics: &[super::types::MarketplaceDiagnostic]) -> String {
288 use crate::types::PluginDiagnosticLevel;
289 diagnostics
290 .iter()
291 .map(|d| {
292 format!(
293 "{} {}: {}",
294 match d.level {
295 PluginDiagnosticLevel::Error => "error",
296 PluginDiagnosticLevel::Warning => "warning",
297 },
298 d.code,
299 d.message
300 )
301 })
302 .collect::<Vec<_>>()
303 .join("; ")
304 }
305
306 #[cfg(test)]
307 mod tests {
308 use super::*;
309
310 #[test]
311 fn marketplace_names_are_conservative() {
312 assert!(valid_marketplace_name("official"));
313 assert!(valid_marketplace_name("My-Catalog_2.beta"));
314 assert!(!valid_marketplace_name(""));
315 assert!(!valid_marketplace_name("has space"));
316 assert!(!valid_marketplace_name("a".repeat(65).as_str()));
317 }
318
319 #[test]
320 fn catalog_read_enforces_actual_byte_limit() {
321 use std::io::Write as _;
322 let dir = tempfile::tempdir().unwrap();
323 let path = dir.path().join("catalog.json");
324 let body = " ".repeat(MAX_CATALOG_BYTES as usize);
325 std::fs::write(&path, &body).unwrap();
326 assert_eq!(read_bounded(&path).unwrap(), body);
327 let checked = canonical_document(&path).unwrap();
328 let mut file = std::fs::OpenOptions::new()
329 .append(true)
330 .open(&path)
331 .unwrap();
332 file.write_all(b" ").unwrap();
333 assert!(read_bounded(&checked).unwrap_err().contains("byte limit"));
334 }
335
336 #[cfg(unix)]
337 #[test]
338 fn catalog_read_refuses_symlink_substituted_after_path_check() {
339 let dir = tempfile::tempdir().unwrap();
340 let path = dir.path().join("catalog.json");
341 let other = dir.path().join("other.json");
342 std::fs::write(&path, "{}").unwrap();
343 std::fs::write(&other, "synthetic unrelated content").unwrap();
344 let checked = canonical_document(&path).unwrap();
345 std::fs::rename(&path, dir.path().join("original.json")).unwrap();
346 std::os::unix::fs::symlink(&other, &path).unwrap();
347 assert!(read_bounded(&checked).is_err());
348 assert_eq!(
349 std::fs::read_to_string(&other).unwrap(),
350 "synthetic unrelated content"
351 );
352 }
353
354 #[cfg(unix)]
355 #[test]
356 fn catalog_read_refuses_fifo_without_waiting_for_a_writer() {
357 const CHILD_PATH: &str = "CODEWHALE_TEST_CATALOG_FIFO";
358 if let Some(path) = std::env::var_os(CHILD_PATH) {
359 assert!(read_bounded(Path::new(&path)).is_err());
360 return;
361 }
362 // Isolate a regressed blocking open so the test can stop it safely.
363 let dir = tempfile::tempdir().unwrap();
364 let path = dir.path().join("catalog.json");
365 std::fs::write(&path, "{}").unwrap();
366 let checked = canonical_document(&path).unwrap();
367 std::fs::rename(&path, dir.path().join("original.json")).unwrap();
368 assert!(
369 std::process::Command::new("mkfifo")
370 .arg(&path)
371 .status()
372 .unwrap()
373 .success()
374 );
375 let mut child = std::process::Command::new(std::env::current_exe().unwrap())
376 .args(["--exact", "plugins::marketplace::document::tests::catalog_read_refuses_fifo_without_waiting_for_a_writer"])
377 .env(CHILD_PATH, checked)
378 .stdout(std::process::Stdio::null())
379 .stderr(std::process::Stdio::null())
380 .spawn().unwrap();
381 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
382 loop {
383 if let Some(status) = child.try_wait().unwrap() {
384 assert!(status.success());
385 break;
386 }
387 if std::time::Instant::now() >= deadline {
388 let _ = child.kill();
389 let _ = child.wait();
390 panic!("catalog read waited for a FIFO writer");
391 }
392 std::thread::sleep(std::time::Duration::from_millis(10));
393 }
394 }
395
396 #[cfg(unix)]
397 #[test]
398 fn load_refuses_symlink_documents() {
399 let dir = tempfile::tempdir().unwrap();
400 let real = dir.path().join("real.json");
401 std::fs::write(&real, "{}").unwrap();
402 let link = dir.path().join("link.json");
403 std::os::unix::fs::symlink(&real, &link).unwrap();
404
405 let error = load_catalog_document("test", dir.path(), link.to_str().unwrap())
406 .expect_err("symlink document must be refused");
407 assert!(error.contains("symlink"), "{error}");
408 }
409
410 #[test]
411 fn load_refuses_unknown_format_documents() {
412 let dir = tempfile::tempdir().unwrap();
413 let doc = dir.path().join("catalog.json");
414 std::fs::write(&doc, r#"{"totally":"unknown"}"#).unwrap();
415
416 let error = load_catalog_document("test", dir.path(), doc.to_str().unwrap())
417 .expect_err("unknown format must be refused");
418 assert!(error.contains("could not be parsed"), "{error}");
419 }
420 }
421
421 lines RUST