| 1 | //! Two-pass tarball reader for remote bundles. |
| 2 | //! |
| 3 | //! Pass one ([`scan_tarball_for_bundle`]) writes nothing: it rejects traversal and |
| 4 | //! absolute paths, enforces the uncompressed size cap from the headers, and |
| 5 | //! locates the single bundle root — the directory holding the bundle's |
| 6 | //! manifest (`plugin.json`, `kimi.plugin.json`, the legacy `plugin.toml`, or a |
| 7 | //! DeepSeek Harness `package.json`). A Harness `package.json` below a native |
| 8 | //! manifest's directory is a file of that bundle, not a second root; nested |
| 9 | //! native manifests still count as separate roots. Pass two |
| 10 | //! ([`extract_into`]) extracts only entries under that root, so a mono-repo's |
| 11 | //! symlinks elsewhere in the archive are never materialized. |
| 12 | |
| 13 | use std::collections::BTreeSet; |
| 14 | use std::fs; |
| 15 | use std::io::Write; |
| 16 | use std::path::Path; |
| 17 | |
| 18 | use anyhow::{Context, Result}; |
| 19 | use codewhale_skill_install::bounded_tar::{ |
| 20 | MAX_ENTRY_NAME_BYTES, entry_names_within_bound, map_stream_limit, open_bounded_tarball, |
| 21 | read_body_within, |
| 22 | }; |
| 23 | use codewhale_skill_install::install::is_safe_path; |
| 24 | |
| 25 | use super::PluginInstallError; |
| 26 | use super::stage::{StagedPlugin, fresh_staging_dir, validate_staged}; |
| 27 | |
| 28 | /// Validate a tarball and extract the manifest-rooted subtree into a |
| 29 | /// `.staging-*` sibling of the destination. |
| 30 | #[cfg(test)] |
| 31 | pub(super) fn stage_tarball( |
| 32 | bytes: &[u8], |
| 33 | user_plugins_dir: &Path, |
| 34 | max_size: u64, |
| 35 | bundle_path: Option<&str>, |
| 36 | ) -> Result<StagedPlugin> { |
| 37 | stage_tarball_with_network(bytes, user_plugins_dir, max_size, bundle_path, None) |
| 38 | } |
| 39 | |
| 40 | pub(super) fn stage_tarball_with_network( |
| 41 | bytes: &[u8], |
| 42 | user_plugins_dir: &Path, |
| 43 | max_size: u64, |
| 44 | bundle_path: Option<&str>, |
| 45 | network: Option<&codewhale_net::network_policy::NetworkPolicy>, |
| 46 | ) -> Result<StagedPlugin> { |
| 47 | let scan = scan_tarball_for_bundle(bytes, max_size, bundle_path)?; |
| 48 | let staged_path = fresh_staging_dir(user_plugins_dir)?; |
| 49 | let result = if scan.is_dsh { |
| 50 | let raw_dir = tempfile::tempdir().context("failed to create DSH extraction dir")?; |
| 51 | extract_into(&scan, bytes, raw_dir.path(), max_size).and_then(|()| { |
| 52 | let _ = fs::remove_dir_all(&staged_path); |
| 53 | super::dsh::convert_package_with_network(raw_dir.path(), &staged_path, network)?; |
| 54 | validate_staged(&staged_path) |
| 55 | }) |
| 56 | } else { |
| 57 | extract_into(&scan, bytes, &staged_path, max_size) |
| 58 | .and_then(|()| validate_staged(&staged_path)) |
| 59 | }; |
| 60 | match result { |
| 61 | Ok((name, content_hash)) => Ok(StagedPlugin { |
| 62 | name, |
| 63 | staged_path, |
| 64 | content_hash, |
| 65 | }), |
| 66 | Err(error) => { |
| 67 | let _ = fs::remove_dir_all(&staged_path); |
| 68 | Err(error) |
| 69 | } |
| 70 | } |
| 71 | } |
| 72 | |
| 73 | #[derive(Debug)] |
| 74 | pub(super) struct TarballScan { |
| 75 | plugin_root: String, |
| 76 | pub(super) is_dsh: bool, |
| 77 | } |
| 78 | |
| 79 | #[cfg(test)] |
| 80 | pub(super) fn scan_tarball(bytes: &[u8], max_size: u64) -> Result<TarballScan> { |
| 81 | scan_tarball_for_bundle(bytes, max_size, None) |
| 82 | } |
| 83 | |
| 84 | fn oversized_if_stream_limit(err: anyhow::Error, max_size: u64) -> anyhow::Error { |
| 85 | map_stream_limit(err, || { |
| 86 | PluginInstallError::OversizedBundle { limit: max_size }.into() |
| 87 | }) |
| 88 | } |
| 89 | |
| 90 | pub(super) fn scan_tarball_for_bundle( |
| 91 | bytes: &[u8], |
| 92 | max_size: u64, |
| 93 | bundle_path: Option<&str>, |
| 94 | ) -> Result<TarballScan> { |
| 95 | scan_bundle_entries(bytes, max_size, bundle_path) |
| 96 | .map_err(|err| oversized_if_stream_limit(err, max_size)) |
| 97 | } |
| 98 | |
| 99 | fn scan_bundle_entries( |
| 100 | bytes: &[u8], |
| 101 | max_size: u64, |
| 102 | bundle_path: Option<&str>, |
| 103 | ) -> Result<TarballScan> { |
| 104 | let mut archive = open_bounded_tarball(bytes, max_size); |
| 105 | |
| 106 | let mut total_size: u64 = 0; |
| 107 | let mut manifest_paths: Vec<String> = Vec::new(); |
| 108 | let mut dsh_manifest_paths: Vec<String> = Vec::new(); |
| 109 | |
| 110 | for entry in archive |
| 111 | .entries() |
| 112 | .context("failed to read tar entries (corrupt archive?)")? |
| 113 | { |
| 114 | let mut entry = entry.context("failed to read tar entry")?; |
| 115 | if !entry_names_within_bound(&entry) { |
| 116 | return Err(PluginInstallError::EntryNameTooLong { |
| 117 | limit: MAX_ENTRY_NAME_BYTES, |
| 118 | } |
| 119 | .into()); |
| 120 | } |
| 121 | let header = entry.header().clone(); |
| 122 | let path = entry |
| 123 | .path() |
| 124 | .context("tar entry has invalid path")? |
| 125 | .to_path_buf(); |
| 126 | let path_str = path.to_string_lossy().into_owned(); |
| 127 | if !is_safe_path(&path) { |
| 128 | return Err(PluginInstallError::PathTraversal(path_str).into()); |
| 129 | } |
| 130 | total_size = total_size.saturating_add(entry.size()); |
| 131 | if total_size > max_size { |
| 132 | return Err(PluginInstallError::OversizedBundle { limit: max_size }.into()); |
| 133 | } |
| 134 | if header.entry_type().is_file() { |
| 135 | if path.file_name().is_some_and(|name| { |
| 136 | name == std::ffi::OsStr::new(crate::agent_plugin::PLUGIN_JSON_NAME) |
| 137 | || name == std::ffi::OsStr::new(crate::agent_plugin::KIMI_PLUGIN_JSON_NAME) |
| 138 | || name == std::ffi::OsStr::new(crate::agent_plugin::PLUGIN_TOML_NAME) |
| 139 | }) { |
| 140 | manifest_paths.push(path_str); |
| 141 | } else if path.file_name() == Some(std::ffi::OsStr::new("package.json")) |
| 142 | && !path |
| 143 | .components() |
| 144 | .any(|part| part.as_os_str() == std::ffi::OsStr::new("node_modules")) |
| 145 | { |
| 146 | let raw = read_body_within(&mut entry, 1_048_576) |
| 147 | .context("failed to read package.json from archive")? |
| 148 | .ok_or_else(|| { |
| 149 | anyhow::anyhow!("package.json in archive exceeds the 1 MiB metadata limit") |
| 150 | })?; |
| 151 | if let Ok(text) = std::str::from_utf8(&raw) |
| 152 | && let Ok(parsed) = super::dsh::parse_package_json(text) |
| 153 | && parsed |
| 154 | .get("dsh") |
| 155 | .and_then(|dsh| dsh.get("bundle")) |
| 156 | .is_some() |
| 157 | { |
| 158 | dsh_manifest_paths.push(path_str); |
| 159 | } |
| 160 | } |
| 161 | } |
| 162 | } |
| 163 | |
| 164 | let filter_roots = |paths: &[String]| -> BTreeSet<String> { |
| 165 | paths |
| 166 | .iter() |
| 167 | .map(|manifest| { |
| 168 | crate::agent_plugin::plugin_root_for_manifest(Path::new(manifest)) |
| 169 | .map(|root| root.to_string_lossy().into_owned()) |
| 170 | .unwrap_or_default() |
| 171 | }) |
| 172 | .filter(|root| { |
| 173 | bundle_path.is_none_or(|wanted| { |
| 174 | root == wanted |
| 175 | || root |
| 176 | .split_once('/') |
| 177 | .is_some_and(|(_, relative)| relative == wanted) |
| 178 | }) |
| 179 | }) |
| 180 | .collect() |
| 181 | }; |
| 182 | |
| 183 | let roots = filter_roots(&manifest_paths); |
| 184 | let dsh_roots: BTreeSet<String> = filter_roots(&dsh_manifest_paths) |
| 185 | .into_iter() |
| 186 | .filter(|dsh_root| { |
| 187 | !roots |
| 188 | .iter() |
| 189 | .any(|root| dsh_root != root && Path::new(dsh_root).starts_with(root)) |
| 190 | }) |
| 191 | .collect(); |
| 192 | let all_roots: BTreeSet<String> = roots.union(&dsh_roots).cloned().collect(); |
| 193 | if all_roots.len() != 1 { |
| 194 | return Err(PluginInstallError::PluginTomlRoots(all_roots.len()).into()); |
| 195 | } |
| 196 | let plugin_root = all_roots.into_iter().next().unwrap_or_default(); |
| 197 | let is_dsh = dsh_roots.contains(&plugin_root); |
| 198 | Ok(TarballScan { |
| 199 | plugin_root, |
| 200 | is_dsh, |
| 201 | }) |
| 202 | } |
| 203 | |
| 204 | /// Second pass: extract only entries under the scanned bundle root. |
| 205 | pub(super) fn extract_into( |
| 206 | scan: &TarballScan, |
| 207 | bytes: &[u8], |
| 208 | dest: &Path, |
| 209 | max_size: u64, |
| 210 | ) -> Result<()> { |
| 211 | extract_entries(scan, bytes, dest, max_size) |
| 212 | .map_err(|err| oversized_if_stream_limit(err, max_size)) |
| 213 | } |
| 214 | |
| 215 | fn extract_entries(scan: &TarballScan, bytes: &[u8], dest: &Path, max_size: u64) -> Result<()> { |
| 216 | let mut archive = open_bounded_tarball(bytes, max_size); |
| 217 | let mut total_size: u64 = 0; |
| 218 | |
| 219 | for entry in archive |
| 220 | .entries() |
| 221 | .context("failed to read tar entries (corrupt archive?)")? |
| 222 | { |
| 223 | let mut entry = entry.context("failed to read tar entry")?; |
| 224 | if !entry_names_within_bound(&entry) { |
| 225 | return Err(PluginInstallError::EntryNameTooLong { |
| 226 | limit: MAX_ENTRY_NAME_BYTES, |
| 227 | } |
| 228 | .into()); |
| 229 | } |
| 230 | let header = entry.header().clone(); |
| 231 | let entry_type = header.entry_type(); |
| 232 | let path = entry |
| 233 | .path() |
| 234 | .context("tar entry has invalid path")? |
| 235 | .to_path_buf(); |
| 236 | let path_str = path.to_string_lossy().into_owned(); |
| 237 | if !is_safe_path(&path) { |
| 238 | return Err(PluginInstallError::PathTraversal(path_str).into()); |
| 239 | } |
| 240 | |
| 241 | // Keep only the bundle subtree. Entries outside it (including any |
| 242 | // symlinks a mono-repo ships elsewhere) are ignored, never extracted. |
| 243 | let stripped = if scan.plugin_root.is_empty() { |
| 244 | path_str.clone() |
| 245 | } else if path_str == scan.plugin_root { |
| 246 | String::new() |
| 247 | } else if let Some(rest) = path_str.strip_prefix(&format!("{}/", scan.plugin_root)) { |
| 248 | rest.to_string() |
| 249 | } else { |
| 250 | continue; |
| 251 | }; |
| 252 | if stripped.is_empty() { |
| 253 | // The bundle root directory itself — the staging dir already exists. |
| 254 | continue; |
| 255 | } |
| 256 | // Defense-in-depth: re-validate the stripped path. |
| 257 | let stripped_path = Path::new(&stripped); |
| 258 | if !is_safe_path(stripped_path) { |
| 259 | return Err(PluginInstallError::PathTraversal(stripped).into()); |
| 260 | } |
| 261 | if entry_type.is_symlink() || entry_type.is_hard_link() { |
| 262 | return Err(PluginInstallError::SymlinkRejected.into()); |
| 263 | } |
| 264 | |
| 265 | let target = dest.join(stripped_path); |
| 266 | // Final paranoia check: the composed target must stay under dest. |
| 267 | let target_components: Vec<_> = target.components().collect(); |
| 268 | let dest_components: Vec<_> = dest.components().collect(); |
| 269 | if !target_components.starts_with(dest_components.as_slice()) { |
| 270 | return Err(PluginInstallError::PathTraversal(stripped).into()); |
| 271 | } |
| 272 | |
| 273 | if entry_type.is_dir() { |
| 274 | fs::create_dir_all(&target) |
| 275 | .with_context(|| format!("failed to create dir {}", target.display()))?; |
| 276 | continue; |
| 277 | } |
| 278 | if entry_type.is_file() { |
| 279 | if let Some(parent) = target.parent() { |
| 280 | fs::create_dir_all(parent) |
| 281 | .with_context(|| format!("failed to create dir {}", parent.display()))?; |
| 282 | } |
| 283 | let buf = read_body_within(&mut entry, max_size.saturating_sub(total_size)) |
| 284 | .with_context(|| format!("failed to read {}", path.display()))? |
| 285 | .ok_or(PluginInstallError::OversizedBundle { limit: max_size })?; |
| 286 | total_size = total_size.saturating_add(buf.len() as u64); |
| 287 | let mut options = fs::OpenOptions::new(); |
| 288 | options.create_new(true).write(true); |
| 289 | #[cfg(unix)] |
| 290 | { |
| 291 | use std::os::unix::fs::OpenOptionsExt as _; |
| 292 | options.mode(0o600); |
| 293 | } |
| 294 | let mut out = options |
| 295 | .open(&target) |
| 296 | .with_context(|| format!("failed to create {}", target.display()))?; |
| 297 | out.write_all(&buf) |
| 298 | .with_context(|| format!("failed to write {}", target.display()))?; |
| 299 | #[cfg(unix)] |
| 300 | { |
| 301 | use std::os::unix::fs::PermissionsExt as _; |
| 302 | let executable = header.mode().context("invalid archive file mode")? & 0o111 != 0; |
| 303 | let mode = if executable { 0o700 } else { 0o600 }; |
| 304 | out.set_permissions(fs::Permissions::from_mode(mode)) |
| 305 | .with_context(|| format!("failed to set mode for {}", target.display()))?; |
| 306 | } |
| 307 | } |
| 308 | } |
| 309 | Ok(()) |
| 310 | } |
| 311 |