| 1 | //! Stage a bundle into a private `.staging-*` sibling of the plugins root. |
| 2 | //! |
| 3 | //! Nothing here ever touches the destination directory: staging either |
| 4 | //! produces a validated [`StagedPlugin`] or removes its own residue. The |
| 5 | //! local-copy path additionally rejects symlinks anywhere in the source and |
| 6 | //! never copies a stale `.installed-from` marker, so provenance always |
| 7 | //! reflects *this* install. |
| 8 | |
| 9 | use std::fs; |
| 10 | use std::path::{Path, PathBuf}; |
| 11 | |
| 12 | use anyhow::{Context, Result, bail}; |
| 13 | |
| 14 | use crate::manifest::PluginManifest; |
| 15 | use codewhale_skill_install::install::{INSTALLED_FROM_MARKER, validate_skill_name_segment}; |
| 16 | |
| 17 | use super::PluginInstallError; |
| 18 | |
| 19 | /// File count cap for local copies, mirroring the registry staging budget. |
| 20 | const MAX_BUNDLE_FILES: usize = 16_384; |
| 21 | |
| 22 | #[derive(Debug)] |
| 23 | pub(super) struct StagedPlugin { |
| 24 | pub(super) name: String, |
| 25 | pub(super) staged_path: PathBuf, |
| 26 | pub(super) content_hash: String, |
| 27 | } |
| 28 | |
| 29 | pub(super) fn fresh_staging_dir(user_plugins_dir: &Path) -> Result<PathBuf> { |
| 30 | ensure_plugins_dir(user_plugins_dir)?; |
| 31 | // Discovery excludes this reserved staging namespace. A crashed stage |
| 32 | // can remain for recovery; later attempts reserve a fresh UUID path and |
| 33 | // never treat the stale copy as an installed bundle or reuse its path. |
| 34 | let staged_path = user_plugins_dir.join(format!(".staging-{}", uuid::Uuid::new_v4().simple())); |
| 35 | fs::create_dir(&staged_path) |
| 36 | .with_context(|| format!("failed to create staging dir {}", staged_path.display()))?; |
| 37 | Ok(staged_path) |
| 38 | } |
| 39 | |
| 40 | /// Create the user plugins root when missing. The persisted plugin state |
| 41 | /// (`state.json`) lives in this same directory, so it must satisfy the |
| 42 | /// registry's owner-only contract the first time `/plugin install` brings it |
| 43 | /// into existence — a pre-existing directory is left untouched (trust reports |
| 44 | /// unsafe permissions fail-closed rather than silently repairing them). |
| 45 | #[cfg(unix)] |
| 46 | fn ensure_plugins_dir(user_plugins_dir: &Path) -> Result<()> { |
| 47 | use std::os::unix::fs::DirBuilderExt as _; |
| 48 | |
| 49 | let mut builder = fs::DirBuilder::new(); |
| 50 | builder.recursive(true).mode(0o700); |
| 51 | builder.create(user_plugins_dir).with_context(|| { |
| 52 | format!( |
| 53 | "failed to create user plugins directory {}", |
| 54 | user_plugins_dir.display() |
| 55 | ) |
| 56 | }) |
| 57 | } |
| 58 | |
| 59 | #[cfg(not(unix))] |
| 60 | fn ensure_plugins_dir(user_plugins_dir: &Path) -> Result<()> { |
| 61 | fs::create_dir_all(user_plugins_dir).with_context(|| { |
| 62 | format!( |
| 63 | "failed to create user plugins directory {}", |
| 64 | user_plugins_dir.display() |
| 65 | ) |
| 66 | }) |
| 67 | } |
| 68 | |
| 69 | /// Validate the staged tree and return the manifest name + content hash. |
| 70 | pub(super) fn validate_staged(staged_path: &Path) -> Result<(String, String)> { |
| 71 | let manifest_path = crate::agent_plugin::resolve_manifest_path(staged_path) |
| 72 | .ok_or_else(|| { |
| 73 | anyhow::anyhow!("staged bundle has no plugin.json, .claude-plugin/plugin.json, kimi.plugin.json, or plugin.toml") |
| 74 | })?; |
| 75 | let validated = PluginManifest::validate_from_path(&manifest_path) |
| 76 | .map_err(|error| anyhow::anyhow!("staged plugin manifest failed validation: {error}"))?; |
| 77 | let name = validated.manifest.plugin.name.clone(); |
| 78 | validate_skill_name_segment(&name).map_err(|error| { |
| 79 | anyhow::anyhow!("[plugin].name is not a safe directory name: {error:#}") |
| 80 | })?; |
| 81 | Ok((name, validated.content_hash)) |
| 82 | } |
| 83 | |
| 84 | /// Copy a local bundle directory into staging. Symlinks anywhere in the |
| 85 | /// source are rejected; a stale `.installed-from` marker is never copied so |
| 86 | /// provenance always reflects *this* install. |
| 87 | pub(super) fn stage_local_copy( |
| 88 | source: &Path, |
| 89 | user_plugins_dir: &Path, |
| 90 | max_size: u64, |
| 91 | ) -> Result<StagedPlugin> { |
| 92 | // Validate the source first; this also rejects symlinked roots/manifests. |
| 93 | let manifest_path = |
| 94 | crate::agent_plugin::resolve_manifest_path(source).ok_or_else(|| { |
| 95 | anyhow::anyhow!( |
| 96 | "source is not a valid plugin bundle: no plugin.json, .claude-plugin/plugin.json, kimi.plugin.json, or plugin.toml" |
| 97 | ) |
| 98 | })?; |
| 99 | PluginManifest::validate_from_path(&manifest_path) |
| 100 | .map_err(|error| anyhow::anyhow!("source is not a valid plugin bundle: {error}"))?; |
| 101 | let canonical_source = source |
| 102 | .canonicalize() |
| 103 | .with_context(|| format!("failed to resolve {}", source.display()))?; |
| 104 | if let Ok(canonical_plugins) = user_plugins_dir.canonicalize() |
| 105 | && crate::install::path_is_within(&canonical_plugins, &canonical_source, true) |
| 106 | { |
| 107 | bail!( |
| 108 | "cannot install a bundle from inside the user plugins directory {}; \ |
| 109 | it is already in place", |
| 110 | canonical_plugins.display() |
| 111 | ); |
| 112 | } |
| 113 | |
| 114 | let staged_path = fresh_staging_dir(user_plugins_dir)?; |
| 115 | let result = (|| -> Result<StagedPlugin> { |
| 116 | let mut budget = CopyBudget::default(); |
| 117 | copy_bundle_regular_files(&canonical_source, &staged_path, max_size, &mut budget)?; |
| 118 | let (name, content_hash) = validate_staged(&staged_path)?; |
| 119 | Ok(StagedPlugin { |
| 120 | name, |
| 121 | staged_path: staged_path.clone(), |
| 122 | content_hash, |
| 123 | }) |
| 124 | })(); |
| 125 | if result.is_err() { |
| 126 | let _ = fs::remove_dir_all(&staged_path); |
| 127 | } |
| 128 | result |
| 129 | } |
| 130 | |
| 131 | #[derive(Default)] |
| 132 | struct CopyBudget { |
| 133 | files: usize, |
| 134 | bytes: u64, |
| 135 | } |
| 136 | |
| 137 | fn copy_bundle_regular_files( |
| 138 | source: &Path, |
| 139 | dest: &Path, |
| 140 | max_size: u64, |
| 141 | budget: &mut CopyBudget, |
| 142 | ) -> Result<()> { |
| 143 | for entry in fs::read_dir(source) |
| 144 | .with_context(|| format!("failed to read bundle dir {}", source.display()))? |
| 145 | { |
| 146 | let entry = entry?; |
| 147 | let path = entry.path(); |
| 148 | let metadata = fs::symlink_metadata(&path)?; |
| 149 | if codewhale_util::path_identity::metadata_is_link_or_reparse(&metadata) { |
| 150 | return Err(PluginInstallError::SymlinkRejected.into()); |
| 151 | } |
| 152 | let name = entry.file_name(); |
| 153 | if name == std::ffi::OsStr::new(INSTALLED_FROM_MARKER) { |
| 154 | continue; |
| 155 | } |
| 156 | let target = dest.join(&name); |
| 157 | if metadata.is_dir() { |
| 158 | fs::create_dir(&target) |
| 159 | .with_context(|| format!("failed to create {}", target.display()))?; |
| 160 | copy_bundle_regular_files(&path, &target, max_size, budget)?; |
| 161 | } else if metadata.is_file() { |
| 162 | #[cfg(unix)] |
| 163 | { |
| 164 | use std::os::unix::fs::MetadataExt as _; |
| 165 | if metadata.nlink() != 1 { |
| 166 | bail!("source file {} has multiple hard links", path.display()); |
| 167 | } |
| 168 | } |
| 169 | budget.files = budget.files.saturating_add(1); |
| 170 | if budget.files > MAX_BUNDLE_FILES { |
| 171 | bail!("bundle exceeds the {MAX_BUNDLE_FILES} file limit"); |
| 172 | } |
| 173 | let src = codewhale_util::bundle_file::open_bundle_file(&path) |
| 174 | .with_context(|| format!("failed to open {} safely", path.display()))?; |
| 175 | let opened_meta = src.metadata()?; |
| 176 | #[cfg(unix)] |
| 177 | { |
| 178 | use std::os::unix::fs::MetadataExt as _; |
| 179 | if (opened_meta.dev(), opened_meta.ino()) != (metadata.dev(), metadata.ino()) |
| 180 | || opened_meta.nlink() != 1 |
| 181 | { |
| 182 | bail!( |
| 183 | "source file {} changed or was linked during staging", |
| 184 | path.display() |
| 185 | ); |
| 186 | } |
| 187 | } |
| 188 | let remaining = max_size.saturating_sub(budget.bytes); |
| 189 | budget.bytes = budget.bytes.saturating_add(opened_meta.len()); |
| 190 | if budget.bytes > max_size { |
| 191 | return Err(PluginInstallError::OversizedBundle { limit: max_size }.into()); |
| 192 | } |
| 193 | let mut dst = fs::OpenOptions::new() |
| 194 | .write(true) |
| 195 | .create_new(true) |
| 196 | .open(&target) |
| 197 | .with_context(|| format!("failed to create {}", target.display()))?; |
| 198 | let copied = std::io::copy( |
| 199 | &mut std::io::Read::take(src, remaining.saturating_add(1)), |
| 200 | &mut dst, |
| 201 | ) |
| 202 | .with_context(|| { |
| 203 | format!("failed to copy {} to {}", path.display(), target.display()) |
| 204 | })?; |
| 205 | if copied > remaining { |
| 206 | return Err(PluginInstallError::OversizedBundle { limit: max_size }.into()); |
| 207 | } |
| 208 | #[cfg(unix)] |
| 209 | dst.set_permissions(opened_meta.permissions()) |
| 210 | .with_context(|| format!("failed to set permissions on {}", target.display()))?; |
| 211 | } |
| 212 | } |
| 213 | Ok(()) |
| 214 | } |
| 215 |