返回 CodeWhale
install.rs
根目录 / crates / skill-install / src / install.rs
1 //! Community-skill installer (#140).
2 //!
3 //! Pulls user-authored skills from GitHub or direct tarball URLs, validates them
4 //! against a path-traversal- and size-bounded extractor, and writes them into
5 //! `<skills_dir>/<name>/`. No backend service, no auto-execution: every install
6 //! is gated by the per-domain [`codewhale_net::network_policy::NetworkPolicy`] and
7 //! validation rejects any tarball entry that escapes the destination directory.
8 //!
9 //! Public surface:
10 //!
11 //! * [`InstallSource`] — `github:owner/repo`, raw URL, or curated registry
12 //! name. Parsed from a single string with [`InstallSource::parse`].
13 //! * [`install`] / [`update`] / [`uninstall`] — async install, atomic update,
14 //! and clean uninstall. All three preserve a `.installed-from` marker so the
15 //! bundled `skill-creator` (which lacks the marker) is never touched.
16 //! * [`InstallOutcome`] — `Installed` / `NeedsApproval(host)` /
17 //! `NetworkDenied(host)`. The `NeedsApproval` variant is returned without
18 //! side effects so the caller (slash-command, runtime API, etc.) can route
19 //! through its own approval flow.
20 //!
21 //! # Hard rules
22 //!
23 //! * Validation extracts to a temp directory first. The destination path is
24 //! only created (via atomic rename) once the tarball clears every check.
25 //! Half-installed skills can never appear on disk.
26 //! * Path traversal rejection covers both `..` segments and absolute paths.
27 //! Symlinks inside the selected skill subtree are rejected — there's no use
28 //! case for them in a SKILL.md bundle and they're a notorious foothold for
29 //! escape. Multi-skill repository archives may contain unrelated symlinks
30 //! outside that selected subtree; those entries are ignored and never
31 //! extracted.
32 //! * Archive executable intent is preserved for the owner only; extraction
33 //! never runs files or accepts an archive's trust/installation markers.
34 //! `/skill trust <name>` writes the local `.trusted` receipt separately.
35 //! * Claude Code plugin archives that contain multiple skills are rejected with
36 //! an explicit migration message. Codewhale can install individual
37 //! `SKILL.md` bundles, including `.claude/skills/<name>/SKILL.md`, but it
38 //! does not execute `plugin.json` plugin runtimes or custom command bundles.
39
40 use std::fs;
41 use std::io::Write;
42 use std::path::{Component, Path, PathBuf};
43
44 use crate::bounded_tar::{
45 MAX_ENTRY_NAME_BYTES, entry_names_within_bound, map_stream_limit, open_bounded_tarball,
46 read_body_within, stream_cap,
47 };
48 use anyhow::{Context, Result, bail};
49 use futures_util::stream::{self, StreamExt};
50 use serde::{Deserialize, Serialize};
51 use sha2::{Digest, Sha256};
52 use thiserror::Error;
53
54 use codewhale_net::guard::{GuardedGet, PrivateTargets};
55 use codewhale_net::network_policy::{Decision, NetworkPolicy, host_from_url};
56
57 const MAX_INSTALL_REDIRECTS: usize = 5;
58
59 /// Connect and total budgets for install and registry-sync HTTP requests.
60 fn install_http_timeouts() -> (std::time::Duration, std::time::Duration) {
61 if cfg!(any(test, feature = "test-support")) {
62 // Short enough that the stalled-server regression test finishes
63 // quickly, long enough that happy-path tests never approach it.
64 (
65 std::time::Duration::from_millis(250),
66 std::time::Duration::from_secs(2),
67 )
68 } else {
69 (
70 std::time::Duration::from_secs(10),
71 std::time::Duration::from_secs(600),
72 )
73 }
74 }
75
76 async fn guarded_get(
77 url: &str,
78 network: &NetworkPolicy,
79 if_none_match: Option<&str>,
80 ) -> Result<reqwest::Response> {
81 let (connect_timeout, total_timeout) = install_http_timeouts();
82 let request = GuardedGet::new(url, network, "skill_install", PrivateTargets::Refuse)
83 .if_none_match(if_none_match)
84 .timeouts(connect_timeout, total_timeout)
85 .max_redirects(MAX_INSTALL_REDIRECTS);
86 #[cfg(any(test, feature = "test-support"))]
87 let request =
88 if reqwest::Url::parse(url).is_ok_and(|parsed| parsed.host_str() == Some("127.0.0.1")) {
89 request.trust_first_hop()
90 } else {
91 request
92 };
93 request.send().await
94 }
95
96 /// Cache directory for registry-synced skills.
97 ///
98 /// Lives at `~/.codewhale/cache/skills/` so it's separate from user-installed
99 /// skills and can be blown away without losing anything irreplaceable.
100 /// A missing home has no cache destination; callers must refuse the sync.
101 pub fn default_cache_skills_dir() -> Option<PathBuf> {
102 codewhale_paths::user_home().map(|home| home.join(".codewhale").join("cache").join("skills"))
103 }
104
105 /// Default registry. Falls back to a community-curated `index.json` hosted on
106 /// GitHub raw; users can override via `[skills] registry_url` in config.toml.
107 pub const DEFAULT_REGISTRY_URL: &str =
108 "https://raw.githubusercontent.com/Hmbown/deepseek-skills/main/index.json";
109
110 /// Default per-skill size cap (5 MiB). Honored at unpack time so a malicious
111 /// gzip bomb can't blow up RAM.
112 pub const DEFAULT_MAX_SIZE_BYTES: u64 = 5 * 1024 * 1024;
113 const SYNC_REGISTRY_CONCURRENCY: usize = 8;
114 /// Upper bound on a registry index document.
115 const MAX_REGISTRY_BYTES: usize = 4 * 1024 * 1024;
116
117 /// File written under each installed skill so [`update`] / [`uninstall`] can
118 /// recover the original [`InstallSource`] without re-parsing user input.
119 pub const INSTALLED_FROM_MARKER: &str = ".installed-from";
120
121 /// File written under each trusted skill. Currently advisory (the install path
122 /// never auto-runs anything) — the runtime tool-invocation gate consults this
123 /// marker before executing scripts that ship with the skill.
124 pub const TRUSTED_MARKER: &str = ".trusted";
125 const RESERVED_ROOT_METADATA: [&str; 3] = [
126 INSTALLED_FROM_MARKER,
127 TRUSTED_MARKER,
128 ".system-installed-version",
129 ];
130
131 /// Installer-owned root metadata must never arrive from a remote package.
132 /// Descendants of a reserved root directory are excluded too.
133 pub(super) fn is_reserved_root_metadata(relative: &Path) -> bool {
134 let first = relative
135 .components()
136 .find(|component| !matches!(component, Component::CurDir));
137 matches!(first, Some(Component::Normal(name)) if name.to_str().is_some_and(|name|
138 RESERVED_ROOT_METADATA.iter().any(|reserved| name.eq_ignore_ascii_case(reserved))))
139 }
140
141 // ─────────────────────────────────────────────────────────────────────────────
142 // Source parsing
143 // ─────────────────────────────────────────────────────────────────────────────
144
145 /// Where a skill is being installed from. See [`InstallSource::parse`] for the
146 /// accepted spec syntax.
147 #[derive(Debug, Clone, PartialEq, Eq)]
148 pub enum InstallSource {
149 /// `github:owner/repo`. Resolved to
150 /// `https://github.com/<owner>/<repo>/archive/refs/heads/main.tar.gz`
151 /// with a `master.tar.gz` fallback on 404.
152 GitHubRepo(String),
153 /// Raw `http(s)://…` tarball URL. Used as-is.
154 DirectUrl(String),
155 /// Curated registry lookup key. Looked up via the configured `registry_url`.
156 Registry(String),
157 }
158
159 impl InstallSource {
160 /// Parse a user-supplied spec. Empty / whitespace-only input is rejected.
161 ///
162 /// * `github:owner/repo` → [`InstallSource::GitHubRepo`]
163 /// * `https://github.com/owner/repo[.git]` (no path past the repo) →
164 /// [`InstallSource::GitHubRepo`]
165 /// * any other `http://` or `https://` prefix → [`InstallSource::DirectUrl`]
166 /// * anything else → [`InstallSource::Registry`]
167 pub fn parse(spec: &str) -> Result<Self> {
168 let trimmed = spec.trim();
169 if trimmed.is_empty() {
170 bail!("install source must not be empty");
171 }
172 if let Some(rest) = trimmed.strip_prefix("github:") {
173 let rest = rest.trim();
174 // Reject obviously bogus values up front. We intentionally accept
175 // case-insensitive owner/repo so `github:Hmbown/Foo` works.
176 let (owner, repo) = rest.split_once('/').with_context(|| {
177 format!("github source must be 'github:owner/repo' (got {spec})")
178 })?;
179 let owner = owner.trim();
180 let repo = repo.trim().trim_end_matches('/');
181 if owner.is_empty() || repo.is_empty() {
182 bail!("github source must be 'github:owner/repo' (got {spec})");
183 }
184 if owner.contains('/') || repo.contains('/') {
185 bail!("github source must be 'github:owner/repo' (got {spec})");
186 }
187 return Ok(Self::GitHubRepo(format!("{owner}/{repo}")));
188 }
189 if trimmed.starts_with("https://") || trimmed.starts_with("http://") {
190 if let Some(repo) = parse_github_browser_url(trimmed) {
191 return Ok(Self::GitHubRepo(repo));
192 }
193 return Ok(Self::DirectUrl(trimmed.to_string()));
194 }
195 Ok(Self::Registry(trimmed.to_string()))
196 }
197 }
198
199 /// Detect bare `https://github.com/<owner>/<repo>` URLs (with or without a
200 /// trailing `.git`) and return `owner/repo`. Returns `None` for any URL that
201 /// already points at a specific archive / blob / tree path — those are real
202 /// direct URLs and the caller fetches them as-is.
203 fn parse_github_browser_url(url: &str) -> Option<String> {
204 let after_scheme = url
205 .strip_prefix("https://")
206 .or_else(|| url.strip_prefix("http://"))?;
207 let (host, rest) = after_scheme.split_once('/')?;
208 if !host.eq_ignore_ascii_case("github.com") && !host.eq_ignore_ascii_case("www.github.com") {
209 return None;
210 }
211 let trimmed = rest.trim_end_matches('/');
212 let mut parts = trimmed.splitn(3, '/');
213 let owner = parts.next()?.trim();
214 let repo = parts.next()?.trim().trim_end_matches(".git");
215 if owner.is_empty() || repo.is_empty() {
216 return None;
217 }
218 // If there is a third segment, the URL points at a sub-resource
219 // (`/archive/...`, `/blob/...`, `/tree/...`). Treat that as a real direct
220 // URL — the user explicitly wants whatever lives at that path.
221 if parts.next().is_some() {
222 return None;
223 }
224 Some(format!("{owner}/{repo}"))
225 }
226
227 // ─────────────────────────────────────────────────────────────────────────────
228 // Outcome / result types
229 // ─────────────────────────────────────────────────────────────────────────────
230
231 /// Outcome of an install attempt.
232 #[derive(Debug)]
233 pub enum InstallOutcome {
234 /// The skill was installed (or already present and idempotent).
235 Installed(InstalledSkill),
236 /// The host requires user approval before the install can proceed. The
237 /// caller should surface this through whatever approval pathway it has and
238 /// retry once approved (typically by adding the host to the policy's
239 /// allow list).
240 NeedsApproval(String),
241 /// The host is denied by network policy. The install is aborted.
242 NetworkDenied(String),
243 }
244
245 /// Metadata for a successfully installed skill.
246 #[derive(Debug, Clone)]
247 pub struct InstalledSkill {
248 /// Skill name (taken from SKILL.md frontmatter).
249 pub name: String,
250 /// Final on-disk path: `<skills_dir>/<name>/`.
251 pub path: PathBuf,
252 /// SHA-256 over the downloaded tarball bytes. Used by [`update`] to detect
253 /// upstream changes without re-extracting; also surfaced for telemetry /
254 /// future signature-verification work.
255 pub source_checksum: String,
256 }
257
258 /// Result of an [`update`] call.
259 #[derive(Debug)]
260 pub enum UpdateResult {
261 /// Upstream tarball is byte-identical to the on-disk checksum; no action.
262 NoChange,
263 /// Upstream changed and the on-disk install was atomically replaced.
264 Updated(InstalledSkill),
265 /// Network policy short-circuited the update. Same semantics as
266 /// [`InstallOutcome::NeedsApproval`].
267 NeedsApproval(String),
268 /// Network policy denied the update.
269 NetworkDenied(String),
270 }
271
272 /// Errors that can happen during install. Most variants are flattened into
273 /// `anyhow::Error` at the public boundary; this enum is used internally so
274 /// tests can pattern-match without parsing strings.
275 #[derive(Debug, Error)]
276 pub enum InstallError {
277 #[error("entry escapes destination directory: {0}")]
278 PathTraversal(String),
279 #[error("entry is too large; uncompressed total would exceed {limit} bytes")]
280 OversizedTarball { limit: u64 },
281 #[error("archive entry name is longer than {limit} bytes")]
282 EntryNameTooLong { limit: usize },
283 #[error("missing SKILL.md in archive")]
284 MissingSkillMd,
285 #[error("symlinks are not allowed in skill tarballs")]
286 SymlinkRejected,
287 #[error(
288 "Claude Code plugin archive contains multiple SKILL.md entries; Codewhale installs one SKILL.md bundle at a time and does not run plugin.json/custom-command runtimes. Install or migrate an individual skills/<name> directory instead"
289 )]
290 ClaudePluginBundle,
291 #[error("skill '{0}' is already installed; use update or remove it first")]
292 AlreadyInstalled(String),
293 #[error("skill '{0}' was not installed via /skill install (no .installed-from marker)")]
294 NotInstalledHere(String),
295 }
296
297 // ─────────────────────────────────────────────────────────────────────────────
298 // Public API
299 // ─────────────────────────────────────────────────────────────────────────────
300
301 /// Install a community skill into `skills_dir`.
302 ///
303 /// Steps:
304 ///
305 /// 1. Resolve `source` to one or more candidate URLs (GitHub adds a
306 /// `master` fallback after `main`).
307 /// 2. Consult `network` for the host. `Allow` proceeds; `Deny` returns
308 /// [`InstallOutcome::NetworkDenied`]; `Prompt` returns
309 /// [`InstallOutcome::NeedsApproval`] without touching disk.
310 /// 3. Stream the tarball into a tempfile (capped at `max_size`).
311 /// 4. Validate the archive (path-traversal, size, no symlinks in the selected
312 /// skill subtree, SKILL.md present with required frontmatter fields) into a
313 /// fresh hidden sibling staging directory.
314 /// 5. Atomic-rename the staging directory → `<name>/`.
315 /// 6. Write `.installed-from` and return [`InstalledSkill`].
316 ///
317 /// `update = false` rejects an existing destination. Pass `update = true`
318 /// from [`update`] to allow replacement.
319 ///
320 /// Convenience wrapper over [`install_with_registry`] that uses the bundled
321 /// [`DEFAULT_REGISTRY_URL`]. Public for downstream consumers (tests, runtime
322 /// API) even though the slash-command path always goes through
323 /// [`install_with_registry`] so the user's configured registry wins.
324 pub async fn install(
325 source: InstallSource,
326 skills_dir: &Path,
327 max_size: u64,
328 network: &NetworkPolicy,
329 update: bool,
330 ) -> Result<InstallOutcome> {
331 install_with_registry(
332 source,
333 skills_dir,
334 max_size,
335 network,
336 update,
337 DEFAULT_REGISTRY_URL,
338 )
339 .await
340 }
341
342 /// Same as [`install`] but lets the caller override the registry URL. Useful
343 /// for tests; the slash-command path always uses the configured registry.
344 pub async fn install_with_registry(
345 source: InstallSource,
346 skills_dir: &Path,
347 max_size: u64,
348 network: &NetworkPolicy,
349 update: bool,
350 registry_url: &str,
351 ) -> Result<InstallOutcome> {
352 let urls = candidate_urls(&source, network, registry_url).await?;
353 let urls = match urls {
354 UrlResolution::Resolved(urls) => urls,
355 UrlResolution::NeedsApproval(host) => return Ok(InstallOutcome::NeedsApproval(host)),
356 UrlResolution::Denied(host) => return Ok(InstallOutcome::NetworkDenied(host)),
357 };
358
359 // Try each URL in order — GitHub returns 404 for `main` on master-only
360 // repos, and we don't want to fail the install on that.
361 let (bytes, source_url) = match download_first_success(&urls, network, max_size).await? {
362 DownloadOutcome::Bytes { bytes, url } => (bytes, url),
363 DownloadOutcome::NeedsApproval(host) => return Ok(InstallOutcome::NeedsApproval(host)),
364 DownloadOutcome::Denied(host) => return Ok(InstallOutcome::NetworkDenied(host)),
365 };
366
367 // Compute a checksum before unpacking so [`update`] can detect upstream
368 // no-op changes without redoing the extract.
369 let checksum = sha256_hex(&bytes);
370
371 let staged = {
372 let skills_dir = skills_dir.to_path_buf();
373 tokio::task::spawn_blocking(move || stage_tarball(&bytes, &skills_dir, max_size))
374 .await
375 .context("skill staging task failed")??
376 };
377
378 // Move the staged dir into its final location. If `update` is set and the
379 // destination exists, replace it; otherwise reject.
380 // Keep any backup until content digest + marker write succeed so a failed
381 // finalize can restore the previous install.
382 let final_path = skills_dir.join(&staged.skill_name);
383 let mut backup_path: Option<PathBuf> = None;
384 if tokio::fs::try_exists(&final_path).await.unwrap_or(false) {
385 if !update {
386 // Clean up the staging dir before returning the error.
387 let _ = tokio::fs::remove_dir_all(&staged.staged_path).await;
388 return Err(InstallError::AlreadyInstalled(staged.skill_name).into());
389 }
390 // Same ownership gate as plugins/install/place.rs: an update may only
391 // replace a tree this installer created. The tarball's top-level name
392 // is not proof of ownership — without the marker we would delete a
393 // user-authored or system skill that happened to share the name.
394 if let Err(err) = reject_unmarked_update(&final_path, &staged.skill_name) {
395 let _ = tokio::fs::remove_dir_all(&staged.staged_path).await;
396 return Err(err.into());
397 }
398 let backup = skills_dir.join(format!("{}.bak", staged.skill_name));
399 if tokio::fs::try_exists(&backup).await.unwrap_or(false) {
400 tokio::fs::remove_dir_all(&backup).await.ok();
401 }
402 tokio::fs::rename(&final_path, &backup)
403 .await
404 .with_context(|| {
405 format!(
406 "failed to backup existing skill at {}",
407 final_path.display()
408 )
409 })?;
410 if let Err(err) = tokio::fs::rename(&staged.staged_path, &final_path).await {
411 tokio::fs::rename(&backup, &final_path).await.ok();
412 return Err(err).context("failed to install staged skill");
413 }
414 backup_path = Some(backup);
415 } else {
416 if let Some(parent) = final_path.parent() {
417 tokio::fs::create_dir_all(parent).await.with_context(|| {
418 format!("failed to create skills directory {}", parent.display())
419 })?;
420 }
421 tokio::fs::rename(&staged.staged_path, &final_path)
422 .await
423 .context("failed to install staged skill")?;
424 }
425
426 // Write the marker last so a partial install never leaves a stale
427 // .installed-from on disk. Prefer v2 with package content digest.
428 let spec = source_spec_string(&source);
429 {
430 let final_path = final_path.clone();
431 let source_url = source_url.clone();
432 let checksum = checksum.clone();
433 let skill_name = staged.skill_name.clone();
434 tokio::task::spawn_blocking(move || {
435 let finalized = crate::package_digest::compute_package_digest(&final_path)
436 .map_err(|err| {
437 anyhow::anyhow!("installed package failed content digest validation: {err}")
438 })
439 .and_then(|content_digest| {
440 write_installed_from_v2(
441 &final_path,
442 &spec,
443 Some(&source_url),
444 &checksum,
445 &content_digest,
446 &skill_name,
447 )
448 });
449 if finalized.is_err() {
450 let _ = fs::remove_dir_all(&final_path);
451 if let Some(backup) = &backup_path {
452 let _ = fs::rename(backup, &final_path);
453 }
454 } else if let Some(backup) = &backup_path {
455 let _ = fs::remove_dir_all(backup);
456 }
457 finalized
458 })
459 .await
460 .context("skill finalize task failed")??;
461 }
462
463 Ok(InstallOutcome::Installed(InstalledSkill {
464 name: staged.skill_name,
465 path: final_path,
466 source_checksum: checksum,
467 }))
468 }
469
470 /// Re-fetch a previously installed skill and replace it on disk if the
471 /// upstream tarball changed.
472 ///
473 /// Reads `.installed-from` to recover the original [`InstallSource`], so
474 /// a skill installed via `/skill install github:foo/bar` can be updated via
475 /// `/skill update bar` without the user re-typing the spec.
476 ///
477 /// Convenience wrapper over [`update_with_registry`].
478 pub async fn update(
479 name: &str,
480 skills_dir: &Path,
481 max_size: u64,
482 network: &NetworkPolicy,
483 ) -> Result<UpdateResult> {
484 update_with_registry(name, skills_dir, max_size, network, DEFAULT_REGISTRY_URL).await
485 }
486
487 /// Same as [`update`] but lets the caller override the registry URL.
488 pub async fn update_with_registry(
489 name: &str,
490 skills_dir: &Path,
491 max_size: u64,
492 network: &NetworkPolicy,
493 registry_url: &str,
494 ) -> Result<UpdateResult> {
495 let target = skill_target_path(name, skills_dir)?;
496 if tokio::fs::try_exists(&target).await.unwrap_or(false) {
497 ensure_target_within_skills_dir(&target, skills_dir)?;
498 }
499 let marker_path = target.join(INSTALLED_FROM_MARKER);
500 if !tokio::fs::try_exists(&marker_path).await.unwrap_or(false) {
501 return Err(InstallError::NotInstalledHere(name.to_string()).into());
502 }
503 let marker_body = tokio::fs::read_to_string(&marker_path)
504 .await
505 .with_context(|| format!("failed to read {}", marker_path.display()))?;
506 let marker: InstalledFromMarker = serde_json::from_str(&marker_body)
507 .with_context(|| format!("malformed {INSTALLED_FROM_MARKER} for {name}"))?;
508 if !is_registry_updatable_spec(&marker.spec) {
509 bail!(
510 "skill '{name}' was imported locally (spec '{}') and cannot be updated from a registry; \
511 re-import or remove it first",
512 marker.spec
513 );
514 }
515
516 // Re-resolve the URL, taking the existing checksum as a short-circuit hint:
517 // we still hit the network so the user gets a useful "no upstream change"
518 // signal, but we skip the unpack step if the bytes match.
519 let source = InstallSource::parse(&marker.spec)?;
520 let urls = match candidate_urls(&source, network, registry_url).await? {
521 UrlResolution::Resolved(urls) => urls,
522 UrlResolution::NeedsApproval(host) => return Ok(UpdateResult::NeedsApproval(host)),
523 UrlResolution::Denied(host) => return Ok(UpdateResult::NetworkDenied(host)),
524 };
525 let (bytes, _url) = match download_first_success(&urls, network, max_size).await? {
526 DownloadOutcome::Bytes { bytes, url } => (bytes, url),
527 DownloadOutcome::NeedsApproval(host) => return Ok(UpdateResult::NeedsApproval(host)),
528 DownloadOutcome::Denied(host) => return Ok(UpdateResult::NetworkDenied(host)),
529 };
530
531 let checksum = sha256_hex(&bytes);
532 if checksum == marker.source_checksum() {
533 return Ok(UpdateResult::NoChange);
534 }
535
536 // Bytes changed — fall back to the regular install path with `update = true`
537 // so we get the same atomic-replace semantics. Content updates must not
538 // inherit a previous trust marker. The shared extractor excludes archive
539 // markers on every install, including an update of an untrusted package.
540 let outcome =
541 install_with_registry(source, skills_dir, max_size, network, true, registry_url).await?;
542 match outcome {
543 InstallOutcome::Installed(installed) => Ok(UpdateResult::Updated(installed)),
544 InstallOutcome::NeedsApproval(host) => Ok(UpdateResult::NeedsApproval(host)),
545 InstallOutcome::NetworkDenied(host) => Ok(UpdateResult::NetworkDenied(host)),
546 }
547 }
548
549 /// Remove a community-installed skill.
550 ///
551 /// Refuses to touch any directory that doesn't carry the `.installed-from`
552 /// marker — that's our cue that it's user-owned and not a system skill.
553 pub fn uninstall(name: &str, skills_dir: &Path) -> Result<()> {
554 let target = skill_target_path(name, skills_dir)?;
555 if !target.exists() {
556 bail!("skill '{name}' is not installed at {}", target.display());
557 }
558 ensure_target_within_skills_dir(&target, skills_dir)?;
559 if !target.join(INSTALLED_FROM_MARKER).exists() {
560 return Err(InstallError::NotInstalledHere(name.to_string()).into());
561 }
562 fs::remove_dir_all(&target)
563 .with_context(|| format!("failed to remove {}", target.display()))?;
564 Ok(())
565 }
566
567 /// Mark a community-installed skill as trusted, binding the marker to the
568 /// current package content digest (schema v2).
569 ///
570 /// Refuses to mark system skills (no `.installed-from`) so the bundled
571 /// `skill-creator` doesn't accidentally inherit elevated tool privileges.
572 #[cfg(any(test, feature = "test-support"))]
573 pub fn trust(name: &str, skills_dir: &Path) -> Result<()> {
574 let target = skill_target_path(name, skills_dir)?;
575 if !target.exists() {
576 bail!("skill '{name}' is not installed at {}", target.display());
577 }
578 ensure_target_within_skills_dir(&target, skills_dir)?;
579 if !target.join(INSTALLED_FROM_MARKER).exists() {
580 return Err(InstallError::NotInstalledHere(name.to_string()).into());
581 }
582 let content_digest = crate::package_digest::compute_package_digest(&target)
583 .with_context(|| format!("cannot compute content digest for {}", target.display()))?;
584 write_trust_v2(&target, &content_digest)?;
585 Ok(())
586 }
587
588 /// Fetch the curated registry and return the parsed entries.
589 ///
590 /// Honours `network` (skipping the call entirely on Deny / Prompt).
591 pub async fn fetch_registry(
592 network: &NetworkPolicy,
593 registry_url: &str,
594 ) -> Result<RegistryFetchResult> {
595 let host = match host_from_url(registry_url) {
596 Some(host) => host,
597 None => bail!("invalid registry url: {registry_url}"),
598 };
599 match network.decide(&host) {
600 Decision::Allow => {}
601 Decision::Deny => return Ok(RegistryFetchResult::Denied(host)),
602 Decision::Prompt => return Ok(RegistryFetchResult::NeedsApproval(host)),
603 }
604 let response = guarded_get(registry_url, network, None)
605 .await
606 .with_context(|| format!("failed to fetch registry {registry_url}"))?
607 .error_for_status()
608 .with_context(|| format!("registry {registry_url} returned an error status"))?;
609 let body = codewhale_util::utils::read_response_body_capped(response, MAX_REGISTRY_BYTES)
610 .await
611 .with_context(|| format!("failed to read registry body from {registry_url}"))?;
612 let parsed: RegistryDocument = serde_json::from_slice(&body)
613 .with_context(|| format!("failed to parse registry json from {registry_url}"))?;
614 Ok(RegistryFetchResult::Loaded(parsed))
615 }
616
617 // ─────────────────────────────────────────────────────────────────────────────
618 // Registry sync (issue #433)
619 // ─────────────────────────────────────────────────────────────────────────────
620
621 /// Outcome of a single skill entry during [`sync_registry`].
622 #[derive(Debug, Clone)]
623 pub enum SkillSyncOutcome {
624 /// Skill downloaded and written to the cache directory.
625 Downloaded { name: String, path: PathBuf },
626 /// Cached bytes match the upstream ETag / SHA-256; nothing written.
627 Fresh { name: String },
628 /// Skill download failed; the error is non-fatal so the sync continues.
629 Failed { name: String, reason: String },
630 /// Network policy blocked the download host.
631 Denied { name: String, host: String },
632 /// Network policy requires user approval for the download host.
633 NeedsApproval { name: String, host: String },
634 }
635
636 /// Overall result of [`sync_registry`].
637 #[derive(Debug)]
638 pub enum SyncResult {
639 /// Sync completed. `outcomes` contains one entry per skill in the index.
640 Done { outcomes: Vec<SkillSyncOutcome> },
641 /// The registry fetch was blocked by network policy.
642 RegistryDenied(String),
643 /// The registry fetch requires user approval.
644 RegistryNeedsApproval(String),
645 }
646
647 /// Freshness metadata written alongside each cached skill so subsequent syncs
648 /// can skip unchanged content.
649 #[derive(Debug, Serialize, Deserialize)]
650 struct CacheMeta {
651 /// ETag returned by the server for the primary asset, if any.
652 #[serde(default)]
653 etag: Option<String>,
654 /// SHA-256 hex digest of the downloaded bytes.
655 sha256: String,
656 /// Source URL the asset was fetched from.
657 url: String,
658 }
659
660 /// Sync the remote registry to the local cache.
661 ///
662 /// For every skill listed in `index.json` this function:
663 ///
664 /// 1. Resolves the download URL (same logic as `install`).
665 /// 2. Checks the cached `CacheMeta` (etag + sha256) for freshness; skips
666 /// the download if unchanged.
667 /// 3. Downloads SKILL.md (and any companion files if the source is a tarball)
668 /// into `<cache_dir>/<name>/`.
669 /// 4. Writes updated `CacheMeta` so the next sync is fast.
670 ///
671 /// Failures per-skill are non-fatal: [`SkillSyncOutcome::Failed`] is recorded
672 /// and the sync continues. The caller decides how to surface per-skill errors.
673 pub async fn sync_registry(
674 network: &NetworkPolicy,
675 registry_url: &str,
676 cache_dir: &Path,
677 max_size: u64,
678 ) -> Result<SyncResult> {
679 let doc = match fetch_registry(network, registry_url).await? {
680 RegistryFetchResult::Loaded(doc) => doc,
681 RegistryFetchResult::Denied(host) => return Ok(SyncResult::RegistryDenied(host)),
682 RegistryFetchResult::NeedsApproval(host) => {
683 return Ok(SyncResult::RegistryNeedsApproval(host));
684 }
685 };
686
687 let outcomes = stream::iter(doc.skills.iter())
688 .map(|(name, entry)| sync_one_skill(name, entry, network, cache_dir, max_size))
689 .buffered(SYNC_REGISTRY_CONCURRENCY)
690 .collect()
691 .await;
692
693 Ok(SyncResult::Done { outcomes })
694 }
695
696 /// Sync a single skill entry from the registry into the cache directory.
697 async fn sync_one_skill(
698 name: &str,
699 entry: &RegistryEntry,
700 network: &NetworkPolicy,
701 cache_dir: &Path,
702 max_size: u64,
703 ) -> SkillSyncOutcome {
704 // The registry key names the cache directory joined below; it gets the
705 // same single-segment check as an installed skill name.
706 if let Err(err) = validate_skill_name_segment(name) {
707 return SkillSyncOutcome::Failed {
708 name: name.to_string(),
709 reason: format!("{err:#}"),
710 };
711 }
712 // Resolve the source to a concrete URL list.
713 let source = match InstallSource::parse(&entry.source) {
714 Ok(s) => s,
715 Err(err) => {
716 return SkillSyncOutcome::Failed {
717 name: name.to_string(),
718 reason: format!("invalid source spec '{}': {err:#}", entry.source),
719 };
720 }
721 };
722
723 // Registry sources in index.json must not point back at another registry.
724 if matches!(source, InstallSource::Registry(_)) {
725 return SkillSyncOutcome::Failed {
726 name: name.to_string(),
727 reason: format!("registry entry for '{name}' must not point to another registry entry"),
728 };
729 }
730
731 let urls = match &source {
732 InstallSource::GitHubRepo(repo) => vec![
733 format!("https://github.com/{repo}/archive/refs/heads/main.tar.gz"),
734 format!("https://github.com/{repo}/archive/refs/heads/master.tar.gz"),
735 ],
736 InstallSource::DirectUrl(url) => vec![url.clone()],
737 InstallSource::Registry(_) => unreachable!("guarded above"),
738 };
739
740 // Check the first downloadable URL against any cached meta.
741 let skill_cache_dir = cache_dir.join(name);
742 let meta_path = skill_cache_dir.join(".cache-meta.json");
743
744 // Try each candidate URL in order.
745 for url in &urls {
746 let host = match host_from_url(url) {
747 Some(h) => h,
748 None => continue,
749 };
750 match network.decide(&host) {
751 Decision::Allow => {}
752 Decision::Deny => {
753 return SkillSyncOutcome::Denied {
754 name: name.to_string(),
755 host,
756 };
757 }
758 Decision::Prompt => {
759 return SkillSyncOutcome::NeedsApproval {
760 name: name.to_string(),
761 host,
762 };
763 }
764 }
765
766 // Perform a HEAD request (or conditional GET) for freshness. We use a
767 // simple GET with If-None-Match when we have an ETag, falling back to
768 // an unconditional GET for servers that don't support ETags.
769 let existing_meta: Option<CacheMeta> = tokio::fs::read_to_string(&meta_path)
770 .await
771 .ok()
772 .and_then(|s| serde_json::from_str(&s).ok());
773
774 // Build the request — add If-None-Match if we have a cached ETag.
775 let cached_etag = existing_meta.as_ref().and_then(|meta| meta.etag.as_deref());
776
777 let resp = match guarded_get(url, network, cached_etag).await {
778 Ok(r) => r,
779 Err(err) => {
780 // Network error — try the next candidate URL.
781 let _ = err;
782 continue;
783 }
784 };
785
786 let status = resp.status();
787
788 // 304 Not Modified: cached copy is still fresh.
789 if status == reqwest::StatusCode::NOT_MODIFIED {
790 return SkillSyncOutcome::Fresh {
791 name: name.to_string(),
792 };
793 }
794
795 if status == reqwest::StatusCode::NOT_FOUND {
796 // Try next URL (main → master fallback).
797 continue;
798 }
799
800 if !status.is_success() {
801 return SkillSyncOutcome::Failed {
802 name: name.to_string(),
803 reason: format!("GET {url} returned HTTP {status}"),
804 };
805 }
806
807 // Capture ETag before consuming the response body.
808 let etag = resp
809 .headers()
810 .get(reqwest::header::ETAG)
811 .and_then(|v| v.to_str().ok())
812 .map(|s| s.to_string());
813
814 let compressed_cap = compressed_download_cap(max_size);
815 let bytes = match codewhale_util::utils::read_response_body_capped(resp, compressed_cap)
816 .await
817 {
818 Ok(b) => b,
819 Err(err) => {
820 return SkillSyncOutcome::Failed {
821 name: name.to_string(),
822 reason: format!(
823 "failed to read body from {url} (compressed size cap {compressed_cap} bytes): {err:#}"
824 ),
825 };
826 }
827 };
828
829 // Compute SHA-256 of the downloaded bytes.
830 let sha256 = sha256_hex(&bytes);
831
832 // Short-circuit: if the hash matches the cached one, we're fresh even
833 // without a 304 (some CDNs strip ETags on redirects).
834 if let Some(ref meta) = existing_meta
835 && meta.sha256 == sha256
836 && meta.url == *url
837 {
838 return SkillSyncOutcome::Fresh {
839 name: name.to_string(),
840 };
841 }
842
843 // Determine whether this is a tarball or a plain SKILL.md.
844 // Heuristic: the URL ends with `.tar.gz` or `.tgz`, or the content
845 // starts with the gzip magic bytes (0x1f 0x8b).
846 let is_tarball =
847 url.ends_with(".tar.gz") || url.ends_with(".tgz") || bytes.starts_with(&[0x1f, 0x8b]);
848
849 let final_path: PathBuf = if is_tarball {
850 // Extract into a temp staging dir, then rename atomically.
851 let staging = {
852 let (bytes, cache_dir) = (bytes.clone(), cache_dir.to_path_buf());
853 tokio::task::spawn_blocking(move || stage_tarball(&bytes, &cache_dir, max_size))
854 .await
855 .unwrap_or_else(|err| Err(anyhow::anyhow!("skill staging task failed: {err}")))
856 };
857 let staged = match staging {
858 Ok(s) => s,
859 Err(err) => {
860 return SkillSyncOutcome::Failed {
861 name: name.to_string(),
862 reason: format!("tarball extraction failed: {err:#}"),
863 };
864 }
865 };
866 // Move staged dir into its final location, replacing any prior cache.
867 let dest = cache_dir.join(name);
868 if tokio::fs::try_exists(&dest).await.unwrap_or(false) {
869 let _ = tokio::fs::remove_dir_all(&dest).await;
870 }
871 if let Err(err) = tokio::fs::rename(&staged.staged_path, &dest).await {
872 let _ = tokio::fs::remove_dir_all(&staged.staged_path).await;
873 return SkillSyncOutcome::Failed {
874 name: name.to_string(),
875 reason: format!("failed to move staged skill into cache: {err:#}"),
876 };
877 }
878 dest
879 } else {
880 // Plain SKILL.md (or other companion text file). Write directly.
881 if let Err(err) = tokio::fs::create_dir_all(&skill_cache_dir).await {
882 return SkillSyncOutcome::Failed {
883 name: name.to_string(),
884 reason: format!("failed to create cache dir: {err:#}"),
885 };
886 }
887 let skill_md_path = skill_cache_dir.join("SKILL.md");
888 if let Err(err) = tokio::fs::write(&skill_md_path, &bytes).await {
889 return SkillSyncOutcome::Failed {
890 name: name.to_string(),
891 reason: format!("failed to write SKILL.md to cache: {err:#}"),
892 };
893 }
894 skill_cache_dir.clone()
895 };
896
897 // Write the updated freshness metadata.
898 let meta = CacheMeta {
899 etag,
900 sha256,
901 url: url.clone(),
902 };
903 let meta_json = match serde_json::to_string(&meta) {
904 Ok(json) => json,
905 Err(err) => {
906 return SkillSyncOutcome::Failed {
907 name: name.to_string(),
908 reason: format!("failed to serialize cache metadata: {err:#}"),
909 };
910 }
911 };
912 if let Err(err) = tokio::fs::write(final_path.join(".cache-meta.json"), meta_json).await {
913 return SkillSyncOutcome::Failed {
914 name: name.to_string(),
915 reason: format!("failed to write cache metadata: {err:#}"),
916 };
917 }
918
919 return SkillSyncOutcome::Downloaded {
920 name: name.to_string(),
921 path: final_path,
922 };
923 }
924
925 // All candidate URLs exhausted without a successful response.
926 SkillSyncOutcome::Failed {
927 name: name.to_string(),
928 reason: format!(
929 "all candidate URLs for '{}' failed or were not found",
930 entry.source
931 ),
932 }
933 }
934
935 // ─────────────────────────────────────────────────────────────────────────────
936 // Internal helpers
937 // ─────────────────────────────────────────────────────────────────────────────
938
939 #[derive(Debug, Deserialize)]
940 pub struct InstalledFromMarker {
941 pub spec: String,
942 /// v1 download checksum field.
943 #[serde(default)]
944 checksum: String,
945 #[serde(default)]
946 source_checksum: Option<String>,
947 #[serde(default)]
948 install_nonce: Option<String>,
949 }
950
951 impl InstalledFromMarker {
952 pub fn source_checksum(&self) -> &str {
953 self.source_checksum
954 .as_deref()
955 .filter(|s| !s.is_empty())
956 .unwrap_or(self.checksum.as_str())
957 }
958
959 pub fn install_nonce(&self) -> Option<&str> {
960 self.install_nonce.as_deref().filter(|s| !s.is_empty())
961 }
962 }
963
964 /// Remote/registry update is only valid for install specs that are not local imports.
965 #[must_use]
966 pub fn is_registry_updatable_spec(spec: &str) -> bool {
967 let spec = spec.trim();
968 !spec.is_empty() && !spec.starts_with("import:")
969 }
970
971 /// Write schema-v2 `.installed-from` metadata (last step of a successful install).
972 pub fn write_installed_from_v2(
973 skill_dir: &Path,
974 spec: &str,
975 url: Option<&str>,
976 source_checksum: &str,
977 content_digest: &str,
978 installed_name: &str,
979 ) -> Result<()> {
980 write_installed_from_marker_v2(
981 skill_dir,
982 spec,
983 url,
984 source_checksum,
985 content_digest,
986 installed_name,
987 None,
988 )
989 }
990
991 pub fn write_installed_from_v2_with_nonce(
992 skill_dir: &Path,
993 spec: &str,
994 url: Option<&str>,
995 source_checksum: &str,
996 content_digest: &str,
997 installed_name: &str,
998 install_nonce: &str,
999 ) -> Result<()> {
1000 write_installed_from_marker_v2(
1001 skill_dir,
1002 spec,
1003 url,
1004 source_checksum,
1005 content_digest,
1006 installed_name,
1007 Some(install_nonce),
1008 )
1009 }
1010
1011 fn write_installed_from_marker_v2(
1012 skill_dir: &Path,
1013 spec: &str,
1014 url: Option<&str>,
1015 source_checksum: &str,
1016 content_digest: &str,
1017 installed_name: &str,
1018 install_nonce: Option<&str>,
1019 ) -> Result<()> {
1020 let mut body = serde_json::json!({
1021 "schema_version": 2,
1022 "spec": spec,
1023 "url": url,
1024 "source_checksum": source_checksum,
1025 "content_digest": content_digest,
1026 "installed_name": installed_name,
1027 "registry_version": null,
1028 });
1029 if let (Some(nonce), Some(object)) = (install_nonce, body.as_object_mut()) {
1030 object.insert(
1031 "install_nonce".to_string(),
1032 serde_json::Value::String(nonce.to_string()),
1033 );
1034 }
1035 codewhale_util::utils::write_atomic(
1036 &skill_dir.join(INSTALLED_FROM_MARKER),
1037 body.to_string().as_bytes(),
1038 )
1039 .with_context(|| {
1040 format!(
1041 "failed to write {} for {}",
1042 INSTALLED_FROM_MARKER,
1043 skill_dir.display()
1044 )
1045 })?;
1046 Ok(())
1047 }
1048
1049 /// Write schema-v2 `.trusted` bound to a package content digest.
1050 pub fn write_trust_v2(skill_dir: &Path, content_digest: &str) -> Result<()> {
1051 let body = serde_json::json!({
1052 "schema_version": 2,
1053 "content_digest": content_digest,
1054 });
1055 codewhale_util::utils::write_atomic(
1056 &skill_dir.join(TRUSTED_MARKER),
1057 body.to_string().as_bytes(),
1058 )
1059 .with_context(|| {
1060 format!(
1061 "failed to write {} for {}",
1062 TRUSTED_MARKER,
1063 skill_dir.display()
1064 )
1065 })?;
1066 Ok(())
1067 }
1068
1069 /// Curated-registry document. The shape is intentionally minimal so adding
1070 /// optional metadata later (homepage, version, signature) is forward-compatible.
1071 #[derive(Debug, Clone, Deserialize)]
1072 pub struct RegistryDocument {
1073 /// Map of skill name → entry.
1074 #[serde(default)]
1075 pub skills: std::collections::BTreeMap<String, RegistryEntry>,
1076 }
1077
1078 /// One row in the curated registry. Descriptive matching metadata is optional
1079 /// so old indices keep parsing and new registries can publish it gradually.
1080 #[derive(Debug, Clone, Deserialize)]
1081 pub struct RegistryEntry {
1082 /// Source spec (e.g. `github:owner/repo`).
1083 pub source: String,
1084 /// Optional human-readable description.
1085 #[serde(default)]
1086 pub description: Option<String>,
1087 /// Task phrases that should rank this skill above description fallbacks.
1088 #[serde(default)]
1089 pub keywords: Vec<String>,
1090 /// Relevant web domains, optionally written as full URLs by the registry.
1091 #[serde(default)]
1092 pub domains: Vec<String>,
1093 }
1094
1095 /// Successful registry fetch result. Same shape as [`InstallOutcome`] for the
1096 /// network-policy outcomes so the caller can drop directly into approval flow.
1097 #[derive(Debug)]
1098 pub enum RegistryFetchResult {
1099 Loaded(RegistryDocument),
1100 NeedsApproval(String),
1101 Denied(String),
1102 }
1103
1104 enum UrlResolution {
1105 Resolved(Vec<String>),
1106 NeedsApproval(String),
1107 Denied(String),
1108 }
1109
1110 enum DownloadOutcome {
1111 Bytes { bytes: Vec<u8>, url: String },
1112 NeedsApproval(String),
1113 Denied(String),
1114 }
1115
1116 /// Outcome of [`fetch_tarball`], shared with the plugin installer (#5182) so
1117 /// both route `Prompt`/`Deny` hosts through their own approval flows instead
1118 /// of growing a second download path.
1119 #[derive(Debug)]
1120 pub enum FetchOutcome {
1121 Bytes { bytes: Vec<u8>, url: String },
1122 NeedsApproval(String),
1123 Denied(String),
1124 }
1125
1126 /// Resolve a *remote* [`InstallSource`] (GitHub repo or direct tarball URL)
1127 /// and download the first reachable candidate under the network policy.
1128 /// Registry sources are rejected: skill registry resolution stays inside
1129 /// `candidate_urls`, and the plugin install on-ramp has no registry index.
1130 pub async fn fetch_tarball(
1131 source: &InstallSource,
1132 network: &NetworkPolicy,
1133 max_size: u64,
1134 ) -> Result<FetchOutcome> {
1135 let urls = match source {
1136 InstallSource::GitHubRepo(repo) => vec![
1137 format!("https://github.com/{repo}/archive/refs/heads/main.tar.gz"),
1138 format!("https://github.com/{repo}/archive/refs/heads/master.tar.gz"),
1139 ],
1140 InstallSource::DirectUrl(url) => vec![url.clone()],
1141 InstallSource::Registry(name) => {
1142 bail!("registry source '{name}' cannot be fetched as a plain tarball")
1143 }
1144 };
1145 Ok(
1146 match download_first_success(&urls, network, max_size).await? {
1147 DownloadOutcome::Bytes { bytes, url } => FetchOutcome::Bytes { bytes, url },
1148 DownloadOutcome::NeedsApproval(host) => FetchOutcome::NeedsApproval(host),
1149 DownloadOutcome::Denied(host) => FetchOutcome::Denied(host),
1150 },
1151 )
1152 }
1153
1154 /// Resolve the source spec into one or more candidate URLs to try in order.
1155 async fn candidate_urls(
1156 source: &InstallSource,
1157 network: &NetworkPolicy,
1158 registry_url: &str,
1159 ) -> Result<UrlResolution> {
1160 match source {
1161 InstallSource::GitHubRepo(repo) => {
1162 // GitHub's archive endpoint lives on `codeload.github.com` after
1163 // the redirect, but the public URL we hit is `github.com`. Every
1164 // hop is checked, so a deny-default allow list needs both hosts.
1165 Ok(UrlResolution::Resolved(vec![
1166 format!("https://github.com/{repo}/archive/refs/heads/main.tar.gz"),
1167 format!("https://github.com/{repo}/archive/refs/heads/master.tar.gz"),
1168 ]))
1169 }
1170 InstallSource::DirectUrl(url) => Ok(UrlResolution::Resolved(vec![url.clone()])),
1171 InstallSource::Registry(name) => {
1172 match fetch_registry(network, registry_url).await? {
1173 RegistryFetchResult::Loaded(doc) => {
1174 let entry = doc
1175 .skills
1176 .get(name)
1177 .with_context(|| format!("skill '{name}' not found in registry"))?
1178 .clone();
1179 let inner = InstallSource::parse(&entry.source).with_context(|| {
1180 format!(
1181 "registry entry for '{name}' has invalid source: {}",
1182 entry.source
1183 )
1184 })?;
1185 // Recurse only one level — registry pointing at registry is
1186 // disallowed to avoid cycles.
1187 if matches!(inner, InstallSource::Registry(_)) {
1188 bail!("registry entry for '{name}' must not point to another registry");
1189 }
1190 // Reuse this function for the inner source so GitHub fallback
1191 // still applies.
1192 Box::pin(candidate_urls(&inner, network, registry_url)).await
1193 }
1194 RegistryFetchResult::NeedsApproval(host) => Ok(UrlResolution::NeedsApproval(host)),
1195 RegistryFetchResult::Denied(host) => Ok(UrlResolution::Denied(host)),
1196 }
1197 }
1198 }
1199 }
1200
1201 /// Download the first URL whose host the policy allows and which returns 2xx.
1202 /// Returns `NeedsApproval` if every candidate hit `Prompt`, or `Denied` if every
1203 /// candidate was denied.
1204 async fn download_first_success(
1205 urls: &[String],
1206 network: &NetworkPolicy,
1207 max_size: u64,
1208 ) -> Result<DownloadOutcome> {
1209 let mut last_status: Option<reqwest::StatusCode> = None;
1210 let mut prompt_host: Option<String> = None;
1211 let mut denied_host: Option<String> = None;
1212 for url in urls {
1213 let host = match host_from_url(url) {
1214 Some(h) => h,
1215 None => bail!("invalid download url: {url}"),
1216 };
1217 match network.decide(&host) {
1218 Decision::Allow => {}
1219 Decision::Deny => {
1220 denied_host.get_or_insert(host);
1221 continue;
1222 }
1223 Decision::Prompt => {
1224 prompt_host.get_or_insert(host);
1225 continue;
1226 }
1227 }
1228 match download_with_cap(url, network, max_size).await? {
1229 DownloadAttempt::Bytes(bytes) => {
1230 return Ok(DownloadOutcome::Bytes {
1231 bytes,
1232 url: url.clone(),
1233 });
1234 }
1235 DownloadAttempt::NotFound(status) => {
1236 last_status = Some(status);
1237 continue;
1238 }
1239 }
1240 }
1241 if let Some(host) = denied_host {
1242 return Ok(DownloadOutcome::Denied(host));
1243 }
1244 if let Some(host) = prompt_host {
1245 return Ok(DownloadOutcome::NeedsApproval(host));
1246 }
1247 bail!(
1248 "failed to download skill (last status: {})",
1249 last_status
1250 .map(|s| s.to_string())
1251 .unwrap_or_else(|| "unknown".to_string())
1252 );
1253 }
1254
1255 enum DownloadAttempt {
1256 Bytes(Vec<u8>),
1257 NotFound(reqwest::StatusCode),
1258 }
1259
1260 /// Stream a URL into memory with a size cap. Aborts on the first read that
1261 /// would push the buffer over `(max_size * 4).min(4 GiB)` (accounting for
1262 /// compression while capping compressed downloads at 4 GiB; the unpack step
1263 /// still enforces `max_size` on the *uncompressed* bytes).
1264 async fn download_with_cap(
1265 url: &str,
1266 network: &NetworkPolicy,
1267 max_size: u64,
1268 ) -> Result<DownloadAttempt> {
1269 let resp = guarded_get(url, network, None).await?;
1270 let status = resp.status();
1271 if !status.is_success() {
1272 if status == reqwest::StatusCode::NOT_FOUND {
1273 return Ok(DownloadAttempt::NotFound(status));
1274 }
1275 bail!("download {url} returned {status}");
1276 }
1277 let compressed_cap = compressed_download_cap(max_size);
1278 let bytes = codewhale_util::utils::read_response_body_capped(resp, compressed_cap)
1279 .await
1280 .with_context(|| {
1281 format!("failed to read body of {url} (compressed size cap {compressed_cap} bytes)")
1282 })?;
1283 Ok(DownloadAttempt::Bytes(bytes))
1284 }
1285
1286 /// Soft cap on the *compressed* download — well above `max_size` to allow for
1287 /// highly compressible payloads but still bounded.
1288 fn compressed_download_cap(max_size: u64) -> usize {
1289 usize::try_from(stream_cap(max_size)).unwrap_or(usize::MAX)
1290 }
1291
1292 struct StagedSkill {
1293 skill_name: String,
1294 staged_path: PathBuf,
1295 }
1296
1297 /// Validate a tarball and extract it into a fresh hidden staging dir under `skills_dir`.
1298 fn stage_tarball(bytes: &[u8], skills_dir: &Path, max_size: u64) -> Result<StagedSkill> {
1299 fs::create_dir_all(skills_dir)
1300 .with_context(|| format!("failed to create skills directory {}", skills_dir.display()))?;
1301
1302 // Two passes: first determine the skill name (and therefore the staged
1303 // dir) by finding the SKILL.md, then extract under that staged dir.
1304 // Both passes share the same archive bytes; we reset by wrapping fresh
1305 // decoders.
1306
1307 let scan = scan_tarball(bytes, max_size)?;
1308
1309 let staged_path = tempfile::Builder::new()
1310 .prefix(".staging-")
1311 .tempdir_in(skills_dir)
1312 .with_context(|| format!("failed to create staging dir in {}", skills_dir.display()))?
1313 .keep();
1314
1315 // Second pass — extract.
1316 let result = extract_into(&scan, bytes, &staged_path, max_size);
1317 if let Err(err) = result {
1318 // Cleanup on failure so a half-staged directory doesn't survive.
1319 let _ = fs::remove_dir_all(&staged_path);
1320 return Err(err);
1321 }
1322
1323 Ok(StagedSkill {
1324 skill_name: scan.skill_name,
1325 staged_path,
1326 })
1327 }
1328
1329 struct TarballScan {
1330 /// Skill name from SKILL.md frontmatter.
1331 skill_name: String,
1332 /// Archive prefix to strip from each entry (e.g. `repo-main/`). May be empty.
1333 prefix: String,
1334 /// Sub-directory inside `prefix` that the SKILL.md lives in (`""` if root,
1335 /// or `skills/<name>` for repos that bundle multiple skills).
1336 skill_root: String,
1337 }
1338
1339 /// First pass: locate SKILL.md, validate frontmatter, compute total size,
1340 /// reject path-traversal entries and symlinks inside the selected install
1341 /// subtree. We do not write anything in this pass; that's the second pass's job.
1342 fn scan_tarball(bytes: &[u8], max_size: u64) -> Result<TarballScan> {
1343 scan_tarball_entries(bytes, max_size).map_err(|err| oversized_if_stream_limit(err, max_size))
1344 }
1345
1346 fn oversized_if_stream_limit(err: anyhow::Error, max_size: u64) -> anyhow::Error {
1347 map_stream_limit(err, || {
1348 InstallError::OversizedTarball { limit: max_size }.into()
1349 })
1350 }
1351
1352 fn scan_tarball_entries(bytes: &[u8], max_size: u64) -> Result<TarballScan> {
1353 let mut archive = open_bounded_tarball(bytes, max_size);
1354
1355 let mut total_size: u64 = 0;
1356 let mut prefix: Option<(String, bool)> = None;
1357 let mut skill_md_files: Vec<(String, Vec<u8>)> = Vec::new();
1358 let mut skill_md_relative: Option<(SkillMdCandidate, Vec<u8>)> = None;
1359 let mut skill_md_candidate_count: usize = 0;
1360 let mut has_claude_plugin_manifest = false;
1361 let mut link_paths: Vec<String> = Vec::new();
1362
1363 for entry in archive
1364 .entries()
1365 .context("failed to read tar entries (corrupt archive?)")?
1366 {
1367 let mut entry = entry.context("failed to read tar entry")?;
1368 if !entry_names_within_bound(&entry) {
1369 return Err(InstallError::EntryNameTooLong {
1370 limit: MAX_ENTRY_NAME_BYTES,
1371 }
1372 .into());
1373 }
1374 let header = entry.header().clone();
1375 let entry_type = header.entry_type();
1376 let path = entry
1377 .path()
1378 .context("tar entry has invalid path")?
1379 .to_path_buf();
1380 let path_str = path.to_string_lossy().into_owned();
1381 if !is_safe_path(&path) {
1382 return Err(InstallError::PathTraversal(path_str).into());
1383 }
1384 if is_claude_plugin_manifest_path(&path) {
1385 has_claude_plugin_manifest = true;
1386 }
1387
1388 total_size = total_size.saturating_add(entry.size());
1389 if total_size > max_size {
1390 return Err(InstallError::OversizedTarball { limit: max_size }.into());
1391 }
1392
1393 if entry_type == tar::EntryType::XGlobalHeader {
1394 continue;
1395 }
1396 let mut components = path.components();
1397 let first = match components.next() {
1398 Some(Component::Normal(first)) => Some(first.to_string_lossy().into_owned()),
1399 _ => None,
1400 };
1401 let wraps = entry_type.is_dir() || components.next().is_some();
1402 prefix = match (prefix, first) {
1403 (None, Some(first)) => Some((first, wraps)),
1404 (Some((current, nested)), Some(first)) if current == first => {
1405 Some((current, nested && wraps))
1406 }
1407 _ => Some((String::new(), false)),
1408 };
1409
1410 if entry_type.is_symlink() || entry_type.is_hard_link() {
1411 link_paths.push(path_str);
1412 continue;
1413 }
1414
1415 // SKILL.md detection. Match the same workflow layouts that runtime
1416 // discovery understands:
1417 // * `<prefix>/SKILL.md`
1418 // * `<prefix>/*/skills/<name>/SKILL.md`
1419 // * `<prefix>/<name>/SKILL.md`
1420 if entry_type.is_file()
1421 && path
1422 .file_name()
1423 .is_some_and(|name| name.eq_ignore_ascii_case("SKILL.md"))
1424 {
1425 let buf = read_body_within(&mut entry, max_size)
1426 .context("failed to read SKILL.md from archive")?
1427 .ok_or(InstallError::OversizedTarball { limit: max_size })?;
1428 skill_md_files.push((path_str, buf));
1429 }
1430 }
1431
1432 let prefix = match prefix {
1433 Some((prefix, true)) => prefix,
1434 _ => String::new(),
1435 };
1436 for (path, buf) in skill_md_files {
1437 if let Some(candidate) = skill_md_candidate(&strip_prefix(&path, &prefix)) {
1438 skill_md_candidate_count += 1;
1439 // Prefer the most explicit match: repo-root SKILL.md first,
1440 // then known skill-directory layouts, then a single nested
1441 // `<name>/SKILL.md` repository.
1442 let replace = skill_md_relative
1443 .as_ref()
1444 .is_none_or(|(current, _)| candidate.rank < current.rank);
1445 if replace {
1446 skill_md_relative = Some((candidate, buf));
1447 }
1448 }
1449 }
1450 if has_claude_plugin_manifest && skill_md_candidate_count > 1 {
1451 return Err(InstallError::ClaudePluginBundle.into());
1452 }
1453 let (skill_md, skill_md_bytes) = skill_md_relative
1454 .ok_or(InstallError::MissingSkillMd)
1455 .map_err(anyhow::Error::from)?;
1456
1457 for link_path in link_paths {
1458 if is_within_selected_root(&link_path, &prefix, &skill_md.skill_root) {
1459 return Err(InstallError::SymlinkRejected.into());
1460 }
1461 }
1462
1463 // Install and discovery share the same frontmatter reader; install adds
1464 // the required description and path-safe destination-name checks.
1465 let name = parse_frontmatter_name(&skill_md_bytes)?;
1466
1467 Ok(TarballScan {
1468 skill_name: name,
1469 prefix,
1470 skill_root: skill_md.skill_root,
1471 })
1472 }
1473
1474 struct SkillMdCandidate {
1475 rank: u8,
1476 skill_root: String,
1477 }
1478
1479 fn skill_md_candidate(stripped_path: &str) -> Option<SkillMdCandidate> {
1480 if stripped_path.eq_ignore_ascii_case("SKILL.md") {
1481 return Some(SkillMdCandidate {
1482 rank: 0,
1483 skill_root: String::new(),
1484 });
1485 }
1486
1487 let parts: Vec<&str> = stripped_path.split('/').collect();
1488 if parts
1489 .last()
1490 .is_none_or(|last| !last.eq_ignore_ascii_case("SKILL.md"))
1491 {
1492 return None;
1493 }
1494
1495 // Common workflow-pack layouts:
1496 // `skills/<name>/SKILL.md`, `.agents/skills/<name>/SKILL.md`,
1497 // `.claude/skills/<name>/SKILL.md`, and nested package layouts such as
1498 // `packages/foo/skills/<name>/SKILL.md`.
1499 if parts.len() >= 3 {
1500 let container = parts[parts.len() - 3];
1501 let name = parts[parts.len() - 2];
1502 if container.eq_ignore_ascii_case("skills") && !name.is_empty() {
1503 return Some(SkillMdCandidate {
1504 rank: 1,
1505 skill_root: parts[..parts.len() - 1].join("/"),
1506 });
1507 }
1508 }
1509
1510 // Single-skill repos sometimes keep their root tidy with
1511 // `<skill-name>/SKILL.md` plus sibling docs at repo root.
1512 if parts.len() == 2 && !parts[0].is_empty() {
1513 return Some(SkillMdCandidate {
1514 rank: 2,
1515 skill_root: parts[0].to_string(),
1516 });
1517 }
1518
1519 None
1520 }
1521
1522 fn is_claude_plugin_manifest_path(path: &Path) -> bool {
1523 let parts: Vec<String> = path
1524 .components()
1525 .filter_map(|component| match component {
1526 Component::Normal(part) => Some(part.to_string_lossy().to_string()),
1527 _ => None,
1528 })
1529 .collect();
1530
1531 parts.windows(2).any(|window| {
1532 window[0].eq_ignore_ascii_case(".claude-plugin")
1533 && window[1].eq_ignore_ascii_case("plugin.json")
1534 })
1535 }
1536
1537 fn extract_into(scan: &TarballScan, bytes: &[u8], dest: &Path, max_size: u64) -> Result<()> {
1538 extract_entries(scan, bytes, dest, max_size)
1539 .map_err(|err| oversized_if_stream_limit(err, max_size))
1540 }
1541
1542 fn extract_entries(scan: &TarballScan, bytes: &[u8], dest: &Path, max_size: u64) -> Result<()> {
1543 let mut archive = open_bounded_tarball(bytes, max_size);
1544
1545 let mut total_size: u64 = 0;
1546 let prefix_with_root = if scan.skill_root.is_empty() {
1547 scan.prefix.clone()
1548 } else if scan.prefix.is_empty() {
1549 scan.skill_root.clone()
1550 } else {
1551 format!("{}/{}", scan.prefix, scan.skill_root)
1552 };
1553
1554 for entry in archive
1555 .entries()
1556 .context("failed to read tar entries (corrupt archive?)")?
1557 {
1558 let mut entry = entry.context("failed to read tar entry")?;
1559 if !entry_names_within_bound(&entry) {
1560 return Err(InstallError::EntryNameTooLong {
1561 limit: MAX_ENTRY_NAME_BYTES,
1562 }
1563 .into());
1564 }
1565 let header = entry.header().clone();
1566 let entry_type = header.entry_type();
1567 let path = entry
1568 .path()
1569 .context("tar entry has invalid path")?
1570 .to_path_buf();
1571 let path_str = path.to_string_lossy().into_owned();
1572 if !is_safe_path(&path) {
1573 return Err(InstallError::PathTraversal(path_str).into());
1574 }
1575
1576 // Only extract entries that live under our skill root. For simple
1577 // tarballs (`SKILL.md` at root) that's everything; for multi-skill
1578 // repos it's the `skills/<name>/` slice.
1579 let stripped = strip_prefix(&path_str, &prefix_with_root).into_owned();
1580 if stripped.is_empty() && entry_type.is_dir() {
1581 // The root directory itself — already created.
1582 continue;
1583 }
1584 if stripped == path_str && !prefix_with_root.is_empty() {
1585 // Nothing to strip => entry is outside our subtree, skip.
1586 continue;
1587 }
1588 // Defense-in-depth: re-validate the stripped path.
1589 let stripped_path = Path::new(&stripped);
1590 if !is_safe_path(stripped_path) {
1591 return Err(InstallError::PathTraversal(stripped).into());
1592 }
1593 if entry_type.is_symlink() || entry_type.is_hard_link() {
1594 return Err(InstallError::SymlinkRejected.into());
1595 }
1596 if is_reserved_root_metadata(stripped_path) {
1597 continue;
1598 }
1599
1600 let target = dest.join(stripped_path);
1601 // Final paranoia check: ensure the resolved target stays under dest.
1602 // We can't canonicalize (target doesn't exist yet), so we walk
1603 // components one more time after composing.
1604 let target_components: Vec<_> = target.components().collect();
1605 let dest_components: Vec<_> = dest.components().collect();
1606 if !target_components.starts_with(dest_components.as_slice()) {
1607 return Err(InstallError::PathTraversal(stripped).into());
1608 }
1609
1610 if entry_type.is_dir() {
1611 fs::create_dir_all(&target)
1612 .with_context(|| format!("failed to create dir {}", target.display()))?;
1613 continue;
1614 }
1615 if entry_type.is_file() {
1616 if let Some(parent) = target.parent() {
1617 fs::create_dir_all(parent)
1618 .with_context(|| format!("failed to create dir {}", parent.display()))?;
1619 }
1620 // Read into a buffer so we can enforce `max_size`. Files inside
1621 // a SKILL bundle are small; copying through a buffer is fine.
1622 let buf = read_body_within(&mut entry, max_size.saturating_sub(total_size))
1623 .with_context(|| format!("failed to read {}", path.display()))?
1624 .ok_or(InstallError::OversizedTarball { limit: max_size })?;
1625 total_size = total_size.saturating_add(buf.len() as u64);
1626 let mut options = fs::OpenOptions::new();
1627 options.create_new(true).write(true);
1628 #[cfg(unix)]
1629 {
1630 use std::os::unix::fs::OpenOptionsExt as _;
1631 options.mode(0o600);
1632 }
1633 let mut out = options
1634 .open(&target)
1635 .with_context(|| format!("failed to create {}", target.display()))?;
1636 out.write_all(&buf)
1637 .with_context(|| format!("failed to write {}", target.display()))?;
1638 #[cfg(unix)]
1639 {
1640 use std::os::unix::fs::PermissionsExt as _;
1641 let executable = header.mode().context("invalid archive file mode")? & 0o111 != 0;
1642 let mode = if executable { 0o700 } else { 0o600 };
1643 out.set_permissions(fs::Permissions::from_mode(mode))
1644 .with_context(|| format!("failed to set mode for {}", target.display()))?;
1645 }
1646 }
1647 }
1648 // Let the host filesystem resolve any platform-specific aliases (for
1649 // example a trailing dot on Windows) before this staged tree is published.
1650 // Remote content can never supply the local install or trust receipt.
1651 for marker in RESERVED_ROOT_METADATA {
1652 match fs::remove_file(dest.join(marker)) {
1653 Ok(()) => {}
1654 Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
1655 Err(error) => return Err(error).context("failed to discard archive metadata"),
1656 }
1657 }
1658 Ok(())
1659 }
1660
1661 fn selected_root(prefix: &str, skill_root: &str) -> String {
1662 if skill_root.is_empty() {
1663 prefix.to_string()
1664 } else if prefix.is_empty() {
1665 skill_root.to_string()
1666 } else {
1667 format!("{prefix}/{skill_root}")
1668 }
1669 }
1670
1671 fn is_within_selected_root(path: &str, prefix: &str, skill_root: &str) -> bool {
1672 let root = selected_root(prefix, skill_root);
1673 if root.is_empty() {
1674 return true;
1675 }
1676 path == root || path.starts_with(&format!("{root}/"))
1677 }
1678
1679 /// Ensure a tar path has no `..` segments and is not absolute.
1680 pub fn is_safe_path(path: &Path) -> bool {
1681 if path.is_absolute() {
1682 return false;
1683 }
1684 for component in path.components() {
1685 match component {
1686 Component::ParentDir => return false,
1687 Component::Prefix(_) | Component::RootDir => return false,
1688 _ => {}
1689 }
1690 }
1691 true
1692 }
1693
1694 fn skill_target_path(name: &str, skills_dir: &Path) -> Result<PathBuf> {
1695 let name = validate_skill_name_segment(name)?;
1696 Ok(skills_dir.join(name))
1697 }
1698
1699 pub fn validate_skill_name_segment(name: &str) -> Result<&str> {
1700 if !crate::frontmatter::is_path_safe_skill_name(name) {
1701 bail!("skill name must be a single path-safe segment (got '{name}')");
1702 }
1703 Ok(name)
1704 }
1705
1706 fn ensure_target_within_skills_dir(target: &Path, skills_dir: &Path) -> Result<()> {
1707 let skills_dir = fs::canonicalize(skills_dir)
1708 .with_context(|| format!("failed to resolve {}", skills_dir.display()))?;
1709 let target = fs::canonicalize(target)
1710 .with_context(|| format!("failed to resolve {}", target.display()))?;
1711 if !target.starts_with(&skills_dir) {
1712 bail!(
1713 "skill path {} escapes skills directory {}",
1714 target.display(),
1715 skills_dir.display()
1716 );
1717 }
1718 Ok(())
1719 }
1720
1721 /// Strip a leading directory prefix (e.g. `repo-main/`) from a tarball path.
1722 fn strip_prefix<'a>(path: &'a str, prefix: &str) -> std::borrow::Cow<'a, str> {
1723 if prefix.is_empty() {
1724 return std::borrow::Cow::Borrowed(path);
1725 }
1726 let with_slash = format!("{prefix}/");
1727 if let Some(rest) = path.strip_prefix(&with_slash) {
1728 std::borrow::Cow::Owned(rest.to_string())
1729 } else if path == prefix {
1730 std::borrow::Cow::Borrowed("")
1731 } else {
1732 std::borrow::Cow::Borrowed(path)
1733 }
1734 }
1735
1736 /// Extract `name:` and ensure `description:` exist in the SKILL.md frontmatter.
1737 /// Also verifies the leading `---` fence so we reject malformed files early.
1738 fn parse_frontmatter_name(bytes: &[u8]) -> Result<String> {
1739 let content = std::str::from_utf8(bytes).context("SKILL.md is not valid UTF-8")?;
1740 let parsed = crate::frontmatter::parse_frontmatter(content).map_err(anyhow::Error::msg)?;
1741 crate::frontmatter::validate_skill_frontmatter(
1742 parsed.as_ref().map(|(metadata, _)| metadata),
1743 None,
1744 crate::frontmatter::SkillValidationMode::Strict,
1745 )
1746 .map_err(anyhow::Error::msg)?;
1747 let (metadata, _) = parsed.expect("strict validation requires frontmatter");
1748 let name = metadata["name"].clone();
1749 Ok(name)
1750 }
1751
1752 fn reject_unmarked_update(final_path: &Path, name: &str) -> std::result::Result<(), InstallError> {
1753 if final_path.join(INSTALLED_FROM_MARKER).exists() {
1754 Ok(())
1755 } else {
1756 Err(InstallError::NotInstalledHere(name.to_string()))
1757 }
1758 }
1759
1760 pub fn source_spec_string(source: &InstallSource) -> String {
1761 match source {
1762 InstallSource::GitHubRepo(repo) => format!("github:{repo}"),
1763 InstallSource::DirectUrl(url) => url.clone(),
1764 InstallSource::Registry(name) => name.clone(),
1765 }
1766 }
1767
1768 pub fn sha256_hex(bytes: &[u8]) -> String {
1769 hex_bytes(Sha256::digest(bytes))
1770 }
1771
1772 fn hex_bytes(bytes: impl AsRef<[u8]>) -> String {
1773 let bytes = bytes.as_ref();
1774 let mut out = String::with_capacity(bytes.len() * 2);
1775 for byte in bytes {
1776 use std::fmt::Write as _;
1777 let _ = write!(&mut out, "{byte:02x}");
1778 }
1779 out
1780 }
1781
1782 // ─────────────────────────────────────────────────────────────────────────────
1783 // Tests
1784 // ─────────────────────────────────────────────────────────────────────────────
1785
1786 #[cfg(test)]
1787 mod tests {
1788 use super::*;
1789 use crate::bounded_tar::test_archives;
1790
1791 fn skill_tarball(entries: &[(&str, &[u8], u32)]) -> Vec<u8> {
1792 let encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::fast());
1793 let mut builder = tar::Builder::new(encoder);
1794 for (path, body, mode) in entries {
1795 let mut header = tar::Header::new_gnu();
1796 header.set_size(body.len() as u64);
1797 header.set_mode(*mode);
1798 header.set_cksum();
1799 builder.append_data(&mut header, path, *body).unwrap();
1800 }
1801 builder.into_inner().unwrap().finish().unwrap()
1802 }
1803
1804 const SKILL_MD: &[u8] = b"---\nname: demo\ndescription: test\n---\nbody";
1805 const SMALL_CAP: u64 = 64 * 1024;
1806 const HUGE_BODY: u64 = 16 * 1024 * 1024;
1807
1808 fn assert_oversized(err: &anyhow::Error) {
1809 assert!(
1810 matches!(
1811 err.downcast_ref::<InstallError>(),
1812 Some(InstallError::OversizedTarball { .. })
1813 ),
1814 "got: {err:#}"
1815 );
1816 }
1817
1818 #[test]
1819 fn scan_counts_the_size_a_pax_record_gives_an_entry() {
1820 let bytes = test_archives::pax_size_record_archive(("SKILL.md", SKILL_MD), HUGE_BODY);
1821 assert_oversized(&scan_tarball(&bytes, SMALL_CAP).err().unwrap());
1822 let tmp = tempfile::tempdir().unwrap();
1823 assert_oversized(
1824 &stage_tarball(&bytes, tmp.path(), SMALL_CAP)
1825 .map(|staged| staged.skill_name)
1826 .unwrap_err(),
1827 );
1828 }
1829
1830 #[test]
1831 fn scan_and_extract_bound_the_decoded_stream_for_extension_entries() {
1832 let benign = skill_tarball(&[("SKILL.md", SKILL_MD, 0o644)]);
1833 let benign_scan = scan_tarball(&benign, SMALL_CAP).unwrap();
1834 for kind in [tar::EntryType::GNULongName, tar::EntryType::XHeader] {
1835 let bytes =
1836 test_archives::extension_body_archive(("SKILL.md", SKILL_MD), kind, HUGE_BODY);
1837 assert_oversized(&scan_tarball(&bytes, SMALL_CAP).err().unwrap());
1838 let tmp = tempfile::tempdir().unwrap();
1839 assert_oversized(
1840 &extract_into(&benign_scan, &bytes, tmp.path(), SMALL_CAP).unwrap_err(),
1841 );
1842 }
1843 }
1844
1845 fn assert_name_too_long(err: &anyhow::Error) {
1846 assert!(
1847 matches!(
1848 err.downcast_ref::<InstallError>(),
1849 Some(InstallError::EntryNameTooLong { .. })
1850 ),
1851 "got: {err:#}"
1852 );
1853 }
1854
1855 #[test]
1856 fn entry_names_longer_than_the_bound_are_rejected_before_any_copy() {
1857 let benign = skill_tarball(&[("SKILL.md", SKILL_MD, 0o644)]);
1858 let benign_scan = scan_tarball(&benign, SMALL_CAP).unwrap();
1859 let archives = [
1860 test_archives::long_name_archive(("SKILL.md", SKILL_MD), MAX_ENTRY_NAME_BYTES + 1),
1861 test_archives::long_name_archive(("SKILL.md", SKILL_MD), 100 * 1024),
1862 test_archives::long_link_target_archive(
1863 ("SKILL.md", SKILL_MD),
1864 MAX_ENTRY_NAME_BYTES + 1,
1865 ),
1866 ];
1867 for bytes in &archives {
1868 assert_name_too_long(&scan_tarball(bytes, SMALL_CAP).err().unwrap());
1869 let tmp = tempfile::tempdir().unwrap();
1870 assert_name_too_long(
1871 &extract_into(&benign_scan, bytes, tmp.path(), SMALL_CAP).unwrap_err(),
1872 );
1873 }
1874 let at_bound =
1875 test_archives::long_name_archive(("SKILL.md", SKILL_MD), MAX_ENTRY_NAME_BYTES);
1876 assert_eq!(
1877 scan_tarball(&at_bound, SMALL_CAP).unwrap().skill_name,
1878 "demo"
1879 );
1880 }
1881
1882 #[test]
1883 fn scan_bounds_the_decoded_stream_for_many_empty_entries() {
1884 let bytes = test_archives::empty_entries_archive(("SKILL.md", SKILL_MD), 600);
1885 assert_oversized(&scan_tarball(&bytes, SMALL_CAP).err().unwrap());
1886 let few = test_archives::empty_entries_archive(("SKILL.md", SKILL_MD), 20);
1887 assert_eq!(scan_tarball(&few, SMALL_CAP).unwrap().skill_name, "demo");
1888 }
1889
1890 #[test]
1891 fn archive_prefix_comes_from_every_entry_not_the_first_one() {
1892 let body = b"---\nname: demo\ndescription: test\n---\nbody";
1893 let nested = b"---\nname: nested\ndescription: test\n---\nbody";
1894 let wrapped = |files: &[(&str, &[u8])]| {
1895 let encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::fast());
1896 let mut builder = tar::Builder::new(encoder);
1897 let mut global = tar::Header::new_ustar();
1898 global.set_entry_type(tar::EntryType::XGlobalHeader);
1899 global.set_size(0);
1900 global.set_cksum();
1901 builder
1902 .append_data(&mut global, "pax_global_header", &b""[..])
1903 .unwrap();
1904 let mut dir = tar::Header::new_gnu();
1905 dir.set_entry_type(tar::EntryType::Directory);
1906 dir.set_size(0);
1907 dir.set_mode(0o755);
1908 dir.set_cksum();
1909 builder
1910 .append_data(&mut dir, "repo-main/", &b""[..])
1911 .unwrap();
1912 for (path, data) in files {
1913 let mut header = tar::Header::new_gnu();
1914 header.set_size(data.len() as u64);
1915 header.set_mode(0o644);
1916 header.set_cksum();
1917 builder.append_data(&mut header, path, *data).unwrap();
1918 }
1919 builder.into_inner().unwrap().finish().unwrap()
1920 };
1921 let tmp = tempfile::tempdir().unwrap();
1922
1923 let named_dir = wrapped(&[
1924 ("repo-main/README.md", b"readme"),
1925 ("repo-main/demo/SKILL.md", body),
1926 ]);
1927 let staged = stage_tarball(&named_dir, tmp.path(), DEFAULT_MAX_SIZE_BYTES).unwrap();
1928 assert_eq!(staged.skill_name, "demo");
1929 assert!(staged.staged_path.join("SKILL.md").is_file());
1930 fs::remove_dir_all(&staged.staged_path).unwrap();
1931
1932 let root_and_bundle = wrapped(&[
1933 ("repo-main/SKILL.md", body),
1934 ("repo-main/skills/nested/SKILL.md", nested),
1935 ]);
1936 let staged = stage_tarball(&root_and_bundle, tmp.path(), DEFAULT_MAX_SIZE_BYTES).unwrap();
1937 assert_eq!(staged.skill_name, "demo");
1938 fs::remove_dir_all(&staged.staged_path).unwrap();
1939
1940 let flat = skill_tarball(&[
1941 ("scripts/run.sh", b"echo hi", 0o755),
1942 ("SKILL.md", body, 0o644),
1943 ]);
1944 let staged = stage_tarball(&flat, tmp.path(), DEFAULT_MAX_SIZE_BYTES).unwrap();
1945 assert!(staged.staged_path.join("SKILL.md").is_file());
1946 assert!(staged.staged_path.join("scripts/run.sh").is_file());
1947 }
1948
1949 #[test]
1950 fn remote_stage_discards_forged_root_receipts_and_keeps_hidden_payloads() {
1951 let tmp = tempfile::tempdir().unwrap();
1952 let skills = tmp.path().join(".codewhale/skills");
1953 let body = b"---\nname: demo\ndescription: test\n---\nbody";
1954 let baseline = tmp.path().join("baseline");
1955 fs::create_dir_all(baseline.join("nested")).unwrap();
1956 fs::write(baseline.join("SKILL.md"), body).unwrap();
1957 fs::write(baseline.join(".hidden"), b"payload").unwrap();
1958 fs::write(baseline.join("nested/.trusted"), b"nested payload").unwrap();
1959 let digest = crate::package_digest::compute_package_digest(&baseline).unwrap();
1960 let forged = serde_json::json!({"schema_version": 2, "content_digest": digest}).to_string();
1961 let bytes = skill_tarball(&[
1962 ("repo-main/SKILL.md", body, 0o644),
1963 ("repo-main/.trusted", forged.as_bytes(), 0o644),
1964 ("repo-main/.TRUSTED", forged.as_bytes(), 0o644),
1965 ("repo-main/./.installed-from", b"forged provenance", 0o644),
1966 ("repo-main/.system-installed-version", b"999", 0o644),
1967 ("repo-main/.hidden", b"payload", 0o644),
1968 ("repo-main/nested/.trusted", b"nested payload", 0o644),
1969 ]);
1970 let staged = stage_tarball(&bytes, &skills, DEFAULT_MAX_SIZE_BYTES).unwrap();
1971 for marker in RESERVED_ROOT_METADATA {
1972 assert!(!staged.staged_path.join(marker).exists(), "{marker}");
1973 }
1974 assert!(!staged.staged_path.join(".TRUSTED").exists());
1975 assert_eq!(
1976 fs::read(staged.staged_path.join(".hidden")).unwrap(),
1977 b"payload"
1978 );
1979 assert_eq!(
1980 crate::package_digest::compute_package_digest(&staged.staged_path).unwrap(),
1981 digest
1982 );
1983 fs::rename(&staged.staged_path, skills.join("demo")).unwrap();
1984 }
1985
1986 #[test]
1987 fn concurrent_stages_of_one_skill_use_distinct_hidden_dirs() {
1988 let bytes = skill_tarball(&[(
1989 "repo/SKILL.md",
1990 b"---\nname: demo\ndescription: test\n---\nbody",
1991 0o644,
1992 )]);
1993 let tmp = tempfile::tempdir().unwrap();
1994 fs::create_dir(tmp.path().join("demo.tmp")).unwrap();
1995 fs::write(tmp.path().join("demo.tmp/keep"), b"other").unwrap();
1996 let first = stage_tarball(&bytes, tmp.path(), DEFAULT_MAX_SIZE_BYTES).unwrap();
1997 let second = stage_tarball(&bytes, tmp.path(), DEFAULT_MAX_SIZE_BYTES).unwrap();
1998 assert_ne!(first.staged_path, second.staged_path);
1999 for staged in [&first, &second] {
2000 assert!(staged.staged_path.join("SKILL.md").is_file());
2001 let name = staged.staged_path.file_name().unwrap().to_string_lossy();
2002 assert!(name.starts_with(".staging-"), "{name}");
2003 }
2004 assert!(tmp.path().join("demo.tmp/keep").is_file());
2005 }
2006
2007 #[test]
2008 fn stage_accepts_a_skill_name_near_the_component_limit() {
2009 let name = "a".repeat(250);
2010 let skill_md = format!("---\nname: {name}\ndescription: test\n---\nbody");
2011 let bytes = skill_tarball(&[("repo/SKILL.md", skill_md.as_bytes(), 0o644)]);
2012 let tmp = tempfile::tempdir().unwrap();
2013 let staged = stage_tarball(&bytes, tmp.path(), DEFAULT_MAX_SIZE_BYTES).unwrap();
2014 assert_eq!(staged.skill_name, name);
2015 assert!(staged.staged_path.join("SKILL.md").is_file());
2016 }
2017
2018 #[cfg(unix)]
2019 #[test]
2020 fn remote_skill_stage_preserves_only_owner_executable_intent() {
2021 use std::os::unix::fs::PermissionsExt as _;
2022
2023 let bytes = skill_tarball(&[
2024 (
2025 "repo/SKILL.md",
2026 b"---\nname: demo\ndescription: test\n---\nbody",
2027 0o644,
2028 ),
2029 ("repo/scripts/run.sh", b"#!/bin/sh\nexit 0\n", 0o6755),
2030 ("repo/scripts/group-only.sh", b"#!/bin/sh\nexit 0\n", 0o010),
2031 ("repo/data.txt", b"data", 0o666),
2032 ]);
2033 let tmp = tempfile::tempdir().unwrap();
2034 let staged = stage_tarball(&bytes, tmp.path(), DEFAULT_MAX_SIZE_BYTES).unwrap();
2035 for (path, expected) in [
2036 ("scripts/run.sh", 0o700),
2037 ("scripts/group-only.sh", 0o700),
2038 ("data.txt", 0o600),
2039 ] {
2040 assert_eq!(
2041 fs::metadata(staged.staged_path.join(path))
2042 .unwrap()
2043 .permissions()
2044 .mode()
2045 & 0o7777,
2046 expected,
2047 "{path}"
2048 );
2049 }
2050 }
2051
2052 #[tokio::test]
2053 async fn registry_sync_refuses_a_key_that_is_not_a_single_segment() {
2054 let root = tempfile::tempdir().expect("tempdir");
2055 let cache_dir = root.path().join("cache");
2056 std::fs::create_dir_all(&cache_dir).expect("cache dir");
2057 let entry = RegistryEntry {
2058 source: "https://example.invalid/skill.tar.gz".to_string(),
2059 description: None,
2060 keywords: Vec::new(),
2061 domains: Vec::new(),
2062 };
2063 for name in ["../escape", "..", "a/b", "/abs"] {
2064 let outcome =
2065 sync_one_skill(name, &entry, &NetworkPolicy::default(), &cache_dir, 1024).await;
2066 assert!(
2067 matches!(outcome, SkillSyncOutcome::Failed { ref reason, .. }
2068 if reason.contains("single path-safe segment")),
2069 "{name}: {outcome:?}"
2070 );
2071 }
2072 assert!(!root.path().join("escape").exists());
2073 }
2074
2075 /// Serve one response per connection: an endless chunked body, or a
2076 /// small body that declares an oversized `Content-Length`.
2077 async fn oversized_body_server() -> std::net::SocketAddr {
2078 use tokio::io::{AsyncReadExt, AsyncWriteExt};
2079 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
2080 let addr = listener.local_addr().unwrap();
2081 tokio::spawn(async move {
2082 while let Ok((mut socket, _)) = listener.accept().await {
2083 tokio::spawn(async move {
2084 let mut request = Vec::new();
2085 let mut buf = [0u8; 1024];
2086 while let Ok(n) = socket.read(&mut buf).await {
2087 if n == 0 {
2088 return;
2089 }
2090 request.extend_from_slice(&buf[..n]);
2091 if request.windows(4).any(|window| window == b"\r\n\r\n") {
2092 break;
2093 }
2094 }
2095 if request.starts_with(b"GET /declared ") {
2096 let _ = socket
2097 .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 999999999\r\n\r\nxx")
2098 .await;
2099 return;
2100 }
2101 let _ = socket
2102 .write_all(b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n")
2103 .await;
2104 let chunk = [b'x'; 4096];
2105 // Never terminates: only a streaming cap ends this read.
2106 loop {
2107 if socket.write_all(b"1000\r\n").await.is_err()
2108 || socket.write_all(&chunk).await.is_err()
2109 || socket.write_all(b"\r\n").await.is_err()
2110 {
2111 return;
2112 }
2113 }
2114 });
2115 }
2116 });
2117 addr
2118 }
2119
2120 #[tokio::test]
2121 async fn download_with_cap_stops_reading_at_the_cap() {
2122 let addr = oversized_body_server().await;
2123 for path in ["endless", "declared"] {
2124 let url = format!("http://{addr}/{path}");
2125 let result = tokio::time::timeout(
2126 std::time::Duration::from_secs(20),
2127 download_with_cap(&url, &NetworkPolicy::default(), 16 * 1024),
2128 )
2129 .await
2130 .unwrap_or_else(|_| panic!("{path}: the size cap must end the read"));
2131 let err = match result {
2132 Ok(_) => panic!("{path}: an oversized body must be refused"),
2133 Err(err) => format!("{err:#}"),
2134 };
2135 assert!(err.contains("exceeds"), "{path}: {err}");
2136 }
2137 }
2138
2139 /// A server that accepts the connection and then never reads or writes
2140 /// another byte, so the request can only end through the client's own
2141 /// timeouts.
2142 async fn stalled_server() -> std::net::SocketAddr {
2143 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
2144 let addr = listener.local_addr().unwrap();
2145 tokio::spawn(async move {
2146 // Hold every accepted socket open without responding.
2147 let mut held = Vec::new();
2148 while let Ok((socket, _)) = listener.accept().await {
2149 held.push(socket);
2150 }
2151 });
2152 addr
2153 }
2154
2155 #[tokio::test]
2156 async fn stalled_registry_fetch_fails_through_the_client_timeouts() {
2157 let addr = stalled_server().await;
2158 let url = format!("http://{addr}/index.json");
2159 let policy = NetworkPolicy {
2160 default: Decision::Allow.into(),
2161 allow: Vec::new(),
2162 deny: Vec::new(),
2163 proxy: Vec::new(),
2164 proxy_fake_ip_cidrs: Vec::new(),
2165 audit: false,
2166 };
2167 // Without the install client's own timeouts this call never returns;
2168 // the outer bound only converts that hang into a test failure.
2169 let outcome = tokio::time::timeout(
2170 std::time::Duration::from_secs(30),
2171 fetch_registry(&policy, &url),
2172 )
2173 .await
2174 .unwrap_or_else(|_| panic!("install HTTP must honor its own timeouts"));
2175 let err = match outcome {
2176 Ok(_) => panic!("a stalled registry connection must fail, not succeed"),
2177 Err(err) => format!("{err:#}"),
2178 };
2179 assert!(err.contains("timed out"), "{err}");
2180 }
2181
2182 async fn counting_server(
2183 response: String,
2184 ) -> (
2185 std::net::SocketAddr,
2186 std::sync::Arc<std::sync::atomic::AtomicUsize>,
2187 ) {
2188 use std::sync::atomic::{AtomicUsize, Ordering};
2189 use tokio::io::{AsyncReadExt, AsyncWriteExt};
2190 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
2191 let addr = listener.local_addr().unwrap();
2192 let hits = std::sync::Arc::new(AtomicUsize::new(0));
2193 let counter = std::sync::Arc::clone(&hits);
2194 tokio::spawn(async move {
2195 while let Ok((mut socket, _)) = listener.accept().await {
2196 counter.fetch_add(1, Ordering::SeqCst);
2197 let response = response.clone();
2198 tokio::spawn(async move {
2199 let mut buf = [0u8; 1024];
2200 let _ = socket.read(&mut buf).await;
2201 let _ = socket.write_all(response.as_bytes()).await;
2202 });
2203 }
2204 });
2205 (addr, hits)
2206 }
2207
2208 #[tokio::test]
2209 async fn an_allow_listed_hop_to_a_local_address_is_refused() {
2210 use std::sync::atomic::Ordering;
2211 let (internal, internal_hits) = counting_server(
2212 "HTTP/1.1 200 OK\r\nContent-Length: 13\r\nConnection: close\r\n\r\ninternal-only"
2213 .to_string(),
2214 )
2215 .await;
2216 let location = format!("http://127.0.0.1:{}/secret", internal.port());
2217 let (entry, _) = counting_server(format!(
2218 "HTTP/1.1 302 Found\r\nLocation: {location}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
2219 ))
2220 .await;
2221 let policy = NetworkPolicy {
2222 default: Decision::Prompt.into(),
2223 allow: vec!["127.0.0.1".to_string()],
2224 deny: Vec::new(),
2225 proxy: Vec::new(),
2226 proxy_fake_ip_cidrs: Vec::new(),
2227 audit: false,
2228 };
2229 let outcome = guarded_get(&format!("http://{entry}/start"), &policy, None).await;
2230 assert!(
2231 outcome.is_err(),
2232 "the hop to an allow-listed local name must be refused"
2233 );
2234 assert_eq!(internal_hits.load(Ordering::SeqCst), 0);
2235 }
2236
2237 #[tokio::test]
2238 async fn sync_one_skill_reports_failure_when_cache_meta_cannot_be_written() {
2239 let skill_body = "---\nname: demo\ndescription: test\n---\nbody\n";
2240 let response = format!(
2241 "HTTP/1.1 200 OK\r\nETag: \"v1\"\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
2242 skill_body.len(),
2243 skill_body
2244 );
2245 let (addr, _hits) = counting_server(response).await;
2246 let root = tempfile::tempdir().unwrap();
2247 let cache_dir = root.path().join("cache");
2248 // Occupy `.cache-meta.json` with a directory so writing the file fails portably.
2249 std::fs::create_dir_all(cache_dir.join("demo/.cache-meta.json")).unwrap();
2250 let entry = RegistryEntry {
2251 source: format!("http://{addr}/SKILL.md"),
2252 description: None,
2253 keywords: Vec::new(),
2254 domains: Vec::new(),
2255 };
2256 let policy = NetworkPolicy {
2257 default: Decision::Allow.into(),
2258 allow: Vec::new(),
2259 deny: Vec::new(),
2260 proxy: Vec::new(),
2261 proxy_fake_ip_cidrs: Vec::new(),
2262 audit: false,
2263 };
2264 let outcome = sync_one_skill("demo", &entry, &policy, &cache_dir, 64 * 1024).await;
2265 assert!(
2266 matches!(
2267 outcome,
2268 SkillSyncOutcome::Failed { ref name, ref reason }
2269 if name == "demo" && reason.contains("cache metadata")
2270 ),
2271 "expected Failed when .cache-meta.json is unwritable, got: {outcome:?}"
2272 );
2273 }
2274
2275 #[tokio::test]
2276 async fn marker_writes_are_atomic_and_truncated_marker_fails_closed_on_update() {
2277 let root = tempfile::tempdir().unwrap();
2278 let skill_dir = root.path().join("demo");
2279 std::fs::create_dir_all(&skill_dir).unwrap();
2280 write_installed_from_v2(
2281 &skill_dir,
2282 "https://example.invalid/demo.tar.gz",
2283 Some("https://example.invalid/demo.tar.gz"),
2284 "abc123",
2285 "def456",
2286 "demo",
2287 )
2288 .unwrap();
2289 write_trust_v2(&skill_dir, "def456").unwrap();
2290
2291 let mut names: Vec<String> = std::fs::read_dir(&skill_dir)
2292 .unwrap()
2293 .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
2294 .collect();
2295 names.sort();
2296 assert_eq!(
2297 names,
2298 vec![
2299 INSTALLED_FROM_MARKER.to_string(),
2300 TRUSTED_MARKER.to_string()
2301 ]
2302 );
2303
2304 // Truncated `.installed-from` must fail closed during update.
2305 std::fs::write(skill_dir.join(INSTALLED_FROM_MARKER), "").unwrap();
2306 let err = update_with_registry(
2307 "demo",
2308 root.path(),
2309 64 * 1024,
2310 &NetworkPolicy::default(),
2311 DEFAULT_REGISTRY_URL,
2312 )
2313 .await
2314 .unwrap_err();
2315 assert!(
2316 format!("{err:#}").contains("malformed .installed-from"),
2317 "unexpected error: {err:#}"
2318 );
2319 }
2320
2321 #[test]
2322 fn parse_github_source() {
2323 let s = InstallSource::parse("github:Hmbown/test-skill").unwrap();
2324 assert_eq!(
2325 s,
2326 InstallSource::GitHubRepo("Hmbown/test-skill".to_string())
2327 );
2328 }
2329
2330 #[test]
2331 fn parse_github_source_rejects_missing_repo() {
2332 let err = InstallSource::parse("github:Hmbown").unwrap_err();
2333 assert!(err.to_string().contains("github source must"), "got: {err}");
2334 }
2335
2336 #[test]
2337 fn parse_github_source_rejects_extra_slashes() {
2338 let err = InstallSource::parse("github:Hmbown/repo/extra").unwrap_err();
2339 assert!(err.to_string().contains("github source must"), "got: {err}");
2340 }
2341
2342 #[test]
2343 fn parse_direct_url_source() {
2344 let s = InstallSource::parse("https://example.com/skill.tar.gz").unwrap();
2345 assert_eq!(
2346 s,
2347 InstallSource::DirectUrl("https://example.com/skill.tar.gz".to_string())
2348 );
2349 let s = InstallSource::parse("http://example.com/skill.tar.gz").unwrap();
2350 assert_eq!(
2351 s,
2352 InstallSource::DirectUrl("http://example.com/skill.tar.gz".to_string())
2353 );
2354 }
2355
2356 #[test]
2357 fn parse_github_browser_url_routes_to_github_repo() {
2358 // Regression for #269: `https://github.com/<owner>/<repo>` was being
2359 // parsed as a DirectUrl, so the installer downloaded the HTML repo
2360 // page and tried to gzip-decode HTML ("invalid gzip header").
2361 for spec in [
2362 "https://github.com/obra/superpowers",
2363 "https://github.com/obra/superpowers/",
2364 "https://github.com/obra/superpowers.git",
2365 "https://github.com/obra/superpowers.git/",
2366 "https://www.github.com/obra/superpowers",
2367 "http://github.com/obra/superpowers",
2368 " https://github.com/obra/superpowers ",
2369 ] {
2370 let parsed = InstallSource::parse(spec)
2371 .unwrap_or_else(|err| panic!("parse({spec}) failed: {err}"));
2372 assert_eq!(
2373 parsed,
2374 InstallSource::GitHubRepo("obra/superpowers".to_string()),
2375 "spec {spec} must route to GitHubRepo",
2376 );
2377 }
2378 }
2379
2380 #[test]
2381 fn parse_github_archive_url_stays_direct() {
2382 // URLs that point at a specific subresource (archive tarball, blob,
2383 // tree) are real direct URLs — the user picked that exact path.
2384 for spec in [
2385 "https://github.com/obra/superpowers/archive/refs/heads/main.tar.gz",
2386 "https://github.com/obra/superpowers/blob/main/README.md",
2387 "https://github.com/obra/superpowers/tree/main",
2388 ] {
2389 let parsed = InstallSource::parse(spec).unwrap();
2390 assert!(
2391 matches!(parsed, InstallSource::DirectUrl(_)),
2392 "spec {spec} must stay DirectUrl, got {parsed:?}",
2393 );
2394 }
2395 }
2396
2397 #[test]
2398 fn parse_registry_source() {
2399 let s = InstallSource::parse("my-skill").unwrap();
2400 assert_eq!(s, InstallSource::Registry("my-skill".to_string()));
2401 }
2402
2403 #[test]
2404 fn parse_rejects_empty() {
2405 assert!(InstallSource::parse("").is_err());
2406 assert!(InstallSource::parse(" ").is_err());
2407 }
2408
2409 #[test]
2410 fn is_safe_path_rejects_traversal() {
2411 assert!(!is_safe_path(Path::new("../etc/passwd")));
2412 assert!(!is_safe_path(Path::new("foo/../bar")));
2413 assert!(!is_safe_path(Path::new("/etc/passwd")));
2414 assert!(is_safe_path(Path::new("foo/bar/baz")));
2415 assert!(is_safe_path(Path::new("SKILL.md")));
2416 }
2417
2418 #[test]
2419 fn parse_frontmatter_extracts_name() {
2420 let body = b"---\nname: hello\ndescription: greeter\n---\nbody\n";
2421 assert_eq!(parse_frontmatter_name(body).unwrap(), "hello");
2422 }
2423
2424 #[test]
2425 fn installer_uses_shared_frontmatter_without_weakening_name_checks() {
2426 let body = "\u{feff}---\r\nname: 'hello'\r\ndescription: Deploy --- safely\r\n with details: here\r\n---\r\nbody";
2427 assert_eq!(parse_frontmatter_name(body.as_bytes()).unwrap(), "hello");
2428 assert!(parse_frontmatter_name(body.replace("'hello'", "'../escape'").as_bytes()).is_err());
2429 assert!(parse_frontmatter_name(b"---\nname: hello\ndescription: ''\n---\n").is_err());
2430 assert!(
2431 parse_frontmatter_name(b"---\nname: hello\ndescription: missing --- fence").is_err()
2432 );
2433 }
2434
2435 #[test]
2436 fn parse_frontmatter_missing_name_fails() {
2437 let body = b"---\ndescription: x\n---\n";
2438 let err = parse_frontmatter_name(body).unwrap_err();
2439 assert!(format!("{err}").contains("name"));
2440 }
2441
2442 #[test]
2443 fn parse_frontmatter_missing_description_fails() {
2444 let body = b"---\nname: x\n---\n";
2445 let err = parse_frontmatter_name(body).unwrap_err();
2446 assert!(format!("{err}").contains("description"));
2447 }
2448
2449 #[test]
2450 fn parse_frontmatter_rejects_unsafe_name() {
2451 let body = b"---\nname: ../evil\ndescription: x\n---\n";
2452 assert!(parse_frontmatter_name(body).is_err());
2453
2454 let body = b"---\nname: a name with spaces\ndescription: x\n---\n";
2455 assert!(parse_frontmatter_name(body).is_err());
2456
2457 let body = b"---\nname: tab\tname\ndescription: x\n---\n";
2458 assert!(parse_frontmatter_name(body).is_err());
2459 }
2460
2461 #[test]
2462 fn parse_frontmatter_requires_opening_fence() {
2463 let body = b"name: hello\ndescription: x\n";
2464 assert!(parse_frontmatter_name(body).is_err());
2465 }
2466
2467 #[test]
2468 fn update_refuses_to_replace_a_directory_without_an_install_marker() {
2469 let tmp = tempfile::tempdir().expect("tempdir");
2470 let dest = tmp.path().join("hand-authored");
2471 std::fs::create_dir_all(&dest).expect("dest");
2472 std::fs::write(dest.join("SKILL.md"), "---\nname: hand-authored\n---\n").expect("skill md");
2473 assert!(!dest.join(INSTALLED_FROM_MARKER).exists());
2474 let err = reject_unmarked_update(&dest, "hand-authored").unwrap_err();
2475 assert!(matches!(err, InstallError::NotInstalledHere(name) if name == "hand-authored"));
2476 assert!(dest.join("SKILL.md").exists(), "unmarked tree must survive");
2477 }
2478
2479 #[test]
2480 fn user_skill_names_must_be_single_safe_segments() {
2481 for bad in [
2482 "",
2483 "../evil",
2484 "/tmp/evil",
2485 "two words",
2486 "two\twords",
2487 "evil/name",
2488 "evil\\name",
2489 ".",
2490 "..",
2491 " leading",
2492 "trailing ",
2493 ] {
2494 assert!(
2495 validate_skill_name_segment(bad).is_err(),
2496 "expected {bad:?} to be rejected"
2497 );
2498 }
2499 assert_eq!(
2500 validate_skill_name_segment("safe-name_1").unwrap(),
2501 "safe-name_1"
2502 );
2503 }
2504
2505 #[test]
2506 fn uninstall_and_trust_reject_unsafe_skill_names_before_path_join() {
2507 let tmp = tempfile::tempdir().expect("tempdir");
2508 let skills_dir = tmp.path().join("skills");
2509 std::fs::create_dir_all(&skills_dir).expect("skills dir");
2510
2511 for bad in [
2512 "../evil",
2513 "/tmp/evil",
2514 "evil/name",
2515 "evil\\name",
2516 "two words",
2517 ] {
2518 assert!(uninstall(bad, &skills_dir).is_err());
2519 assert!(trust(bad, &skills_dir).is_err());
2520 }
2521 }
2522
2523 #[cfg(unix)]
2524 #[test]
2525 fn uninstall_rejects_symlink_target_escaping_skills_dir() {
2526 let tmp = tempfile::tempdir().expect("tempdir");
2527 let skills_dir = tmp.path().join("skills");
2528 let outside = tmp.path().join("outside");
2529 std::fs::create_dir_all(&skills_dir).expect("skills dir");
2530 std::fs::create_dir_all(&outside).expect("outside dir");
2531 std::fs::write(outside.join(INSTALLED_FROM_MARKER), "{}").expect("marker");
2532 std::os::unix::fs::symlink(&outside, skills_dir.join("linked")).expect("symlink");
2533
2534 let err = uninstall("linked", &skills_dir).unwrap_err();
2535 assert!(err.to_string().contains("escapes skills directory"));
2536 assert!(outside.exists());
2537 }
2538
2539 #[test]
2540 fn strip_prefix_handles_all_cases() {
2541 assert_eq!(strip_prefix("foo/bar", "foo"), "bar");
2542 assert_eq!(strip_prefix("foo", "foo"), "");
2543 assert_eq!(strip_prefix("baz/bar", "foo"), "baz/bar");
2544 assert_eq!(strip_prefix("foo/bar", ""), "foo/bar");
2545 }
2546
2547 #[test]
2548 fn source_spec_string_roundtrips() {
2549 assert_eq!(
2550 source_spec_string(&InstallSource::GitHubRepo("a/b".into())),
2551 "github:a/b"
2552 );
2553 assert_eq!(
2554 source_spec_string(&InstallSource::DirectUrl("https://x".into())),
2555 "https://x"
2556 );
2557 assert_eq!(
2558 source_spec_string(&InstallSource::Registry("x".into())),
2559 "x"
2560 );
2561 }
2562 }
2563
2563 lines RUST