| 1 | //! Plugin install on-ramp (#5182). |
| 2 | //! |
| 3 | //! Fetches a plugin bundle from a local directory, a `github:owner/repo` |
| 4 | //! archive, or a direct tarball URL, and places it under the user plugins |
| 5 | //! root (`~/.codewhale/plugins/<name>/`). This module deliberately mirrors |
| 6 | //! [`codewhale_skill_install::install`]: the download, network-gating, traversal |
| 7 | //! rejection, and marker machinery is *reused* from there (`fetch_tarball`, |
| 8 | //! `is_safe_path`, `write_installed_from_v2`, `INSTALLED_FROM_MARKER`), while |
| 9 | //! the scan/extract step is plugin-shaped (a bundle is rooted at the single |
| 10 | //! supported plugin manifest in the tree, not at a `SKILL.md`). |
| 11 | //! |
| 12 | //! # Hard rules |
| 13 | //! |
| 14 | //! * Everything is staged in a private `.staging-*` sibling first. The |
| 15 | //! destination is only created (via atomic rename) once the bundle clears |
| 16 | //! every check — half-installed plugins never appear on disk. |
| 17 | //! * The fetched tree must contain **exactly one** plugin bundle root holding |
| 18 | //! `plugin.json`, `kimi.plugin.json`, or `plugin.toml`. Zero (not a plugin) |
| 19 | //! or more than one (ambiguous mono-repo) are both rejected. |
| 20 | //! * Path traversal (`..`, absolute paths) and symlinks/hard links inside the |
| 21 | //! selected bundle subtree are rejected. Entries outside the subtree are |
| 22 | //! never extracted. |
| 23 | //! * The manifest `[plugin].name` must be a single path-safe segment; it |
| 24 | //! becomes the destination directory name. |
| 25 | //! * Overwriting a bundle that lacks the `.installed-from` marker is refused |
| 26 | //! — hand-placed bundles are never clobbered. `update` publishes a replacement |
| 27 | //! when source or installed content differs; a changed bundle automatically |
| 28 | //! invalidates the hash-bound trust receipt at the next discovery. |
| 29 | //! * Installed bits land **disabled and untrusted**; trust/enablement is the |
| 30 | //! existing registry flow, not this module's concern. |
| 31 | |
| 32 | //! |
| 33 | //! # Module map |
| 34 | //! |
| 35 | //! This module owns the source spec, the result types, and the three |
| 36 | //! verbs. The pipeline stages each live next door: |
| 37 | //! |
| 38 | //! * `stage` — copy a local bundle into a private `.staging-*` sibling |
| 39 | //! (symlink, file-count, and size rejection; manifest validation). |
| 40 | //! * `tarball` — the two-pass archive reader: scan for the single |
| 41 | //! supported manifest under the size cap, then extract just that subtree. |
| 42 | //! * `place` — atomic rename into `<name>/`, marker write, and the |
| 43 | //! containment guards shared with discovery. |
| 44 | //! |
| 45 | //! Fetching is not ours: remote bytes come from |
| 46 | //! [`codewhale_skill_install::install::fetch_tarball`], network gating included. |
| 47 | |
| 48 | use std::fs; |
| 49 | use std::path::{Path, PathBuf}; |
| 50 | |
| 51 | use anyhow::{Context, Result, bail}; |
| 52 | use thiserror::Error; |
| 53 | |
| 54 | /// A validated manifest name is already occupied by another loaded bundle. |
| 55 | /// Keep this typed so API clients receive a conflict, not a server failure. |
| 56 | #[derive(Debug, Error)] |
| 57 | #[error("{0}")] |
| 58 | pub struct PluginNameConflict(pub String); |
| 59 | |
| 60 | #[derive(Debug, Error)] |
| 61 | #[error( |
| 62 | "plugin source changed after review: expected content hash {expected}, copied bytes hash is {actual}; nothing was installed" |
| 63 | )] |
| 64 | pub struct PluginContentMismatch { |
| 65 | pub expected: String, |
| 66 | pub actual: String, |
| 67 | } |
| 68 | |
| 69 | #[derive(Debug, Error)] |
| 70 | #[error( |
| 71 | "plugin archive {url} does not match its pinned sha256: expected {expected}, downloaded bytes hash {actual}; nothing was installed" |
| 72 | )] |
| 73 | pub struct PluginArchiveMismatch { |
| 74 | pub url: String, |
| 75 | pub expected: String, |
| 76 | pub actual: String, |
| 77 | } |
| 78 | |
| 79 | use crate::manifest::PluginManifest; |
| 80 | use codewhale_net::network_policy::NetworkPolicy; |
| 81 | use codewhale_skill_install::install::{ |
| 82 | FetchOutcome, INSTALLED_FROM_MARKER, InstallSource, InstalledFromMarker, fetch_tarball, |
| 83 | sha256_hex, source_spec_string, |
| 84 | }; |
| 85 | |
| 86 | pub mod dsh; |
| 87 | pub(crate) mod npm_deps; |
| 88 | mod place; |
| 89 | mod stage; |
| 90 | mod summary; |
| 91 | mod tarball; |
| 92 | |
| 93 | #[cfg(test)] |
| 94 | mod tests; |
| 95 | |
| 96 | pub use npm_deps::NpmDepsNetworkError; |
| 97 | use place::{ensure_target_within_plugins_dir, finalize_install, plugin_target_path}; |
| 98 | use stage::stage_local_copy; |
| 99 | pub use summary::{PluginSummary, PreviousInstall, SummaryClause, SummaryInput, build_summary}; |
| 100 | use tarball::stage_tarball_with_network; |
| 101 | |
| 102 | /// Default per-bundle size cap. Mirrors the skill installer; the runtime |
| 103 | /// staging budget in `registry.rs` stays the outer bound. |
| 104 | pub const DEFAULT_MAX_SIZE_BYTES: u64 = 256 * 1024 * 1024; |
| 105 | |
| 106 | // ───────────────────────────────────────────────────────────────────────────── |
| 107 | // Source parsing |
| 108 | // ───────────────────────────────────────────────────────────────────────────── |
| 109 | |
| 110 | /// Where a plugin bundle is installed from. See [`PluginInstallSource::parse`]. |
| 111 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 112 | pub enum PluginInstallSource { |
| 113 | /// Local bundle directory (copied, never executed). Parsed from a plain |
| 114 | /// path or an explicit `path:<dir>` spec (the marker round-trip form). |
| 115 | LocalPath(PathBuf), |
| 116 | /// `github:owner/repo` or a direct `http(s)://…` tarball URL, downloaded |
| 117 | /// through the shared skill-install machinery. There is no registry |
| 118 | /// index in v1. |
| 119 | Remote(InstallSource), |
| 120 | /// A local DeepSeek Harness bundle package, converted by [`dsh`] into a |
| 121 | /// native bundle that then takes the same staged, reviewed install path. |
| 122 | /// Parsed from `dsh:<dir>`, or from a plain local path that holds a DSH |
| 123 | /// `package.json` and no native manifest. |
| 124 | Dsh(PathBuf), |
| 125 | } |
| 126 | |
| 127 | impl PluginInstallSource { |
| 128 | /// Parse a user-supplied spec. |
| 129 | /// |
| 130 | /// * `github:owner/repo`, `https://…` → [`PluginInstallSource::Remote`] |
| 131 | /// (via [`InstallSource::parse`]; registry names are unreachable here) |
| 132 | /// * `path:<dir>` or any other value → [`PluginInstallSource::LocalPath`] |
| 133 | pub fn parse(spec: &str) -> Result<Self> { |
| 134 | Self::parse_inner(spec, true) |
| 135 | } |
| 136 | |
| 137 | pub fn parse_syntax(spec: &str) -> Result<Self> { |
| 138 | Self::parse_inner(spec, false) |
| 139 | } |
| 140 | |
| 141 | fn parse_inner(spec: &str, inspect_fs: bool) -> Result<Self> { |
| 142 | let trimmed = spec.trim(); |
| 143 | if trimmed.is_empty() { |
| 144 | bail!("install source must not be empty"); |
| 145 | } |
| 146 | if let Some(spec) = trimmed.strip_prefix("git:") { |
| 147 | let spec = spec.strip_prefix("https://").unwrap_or(spec); |
| 148 | let spec = spec |
| 149 | .strip_prefix("github.com/") |
| 150 | .context("git plugin sources must use git:github.com/owner/repo[@ref]")?; |
| 151 | let (repo, revision) = spec |
| 152 | .rsplit_once('@') |
| 153 | .map_or((spec, None), |(repo, revision)| (repo, Some(revision))); |
| 154 | let repo = repo.strip_suffix(".git").unwrap_or(repo); |
| 155 | let valid = |part: &str| { |
| 156 | !part.is_empty() |
| 157 | && part != "." |
| 158 | && part != ".." |
| 159 | && part |
| 160 | .bytes() |
| 161 | .all(|ch| ch.is_ascii_alphanumeric() || b"-_.".contains(&ch)) |
| 162 | }; |
| 163 | let parts: Vec<_> = repo.split('/').collect(); |
| 164 | if parts.len() != 2 || !parts.iter().all(|part| valid(part)) { |
| 165 | bail!("git plugin source must name one GitHub owner/repository"); |
| 166 | } |
| 167 | return match revision { |
| 168 | None => Ok(Self::Remote(InstallSource::GitHubRepo(repo.to_owned()))), |
| 169 | Some(revision) if valid(revision) => Ok(Self::Remote(InstallSource::DirectUrl( |
| 170 | format!("https://github.com/{repo}/archive/{revision}.tar.gz"), |
| 171 | ))), |
| 172 | _ => bail!("git plugin ref must be a single safe tag, branch name or commit"), |
| 173 | }; |
| 174 | } |
| 175 | if let Some(spec) = trimmed.strip_prefix("npm:") { |
| 176 | let (package, version) = spec |
| 177 | .rsplit_once('@') |
| 178 | .context("npm plugin sources require an exact version: npm:package@1.2.3")?; |
| 179 | let valid = |part: &str| { |
| 180 | !part.is_empty() |
| 181 | && part != "." |
| 182 | && part != ".." |
| 183 | && part.bytes().all(|ch| { |
| 184 | ch.is_ascii_lowercase() || ch.is_ascii_digit() || b"-_.".contains(&ch) |
| 185 | }) |
| 186 | }; |
| 187 | let name = if let Some(scoped) = package.strip_prefix('@') { |
| 188 | let (scope, name) = scoped.split_once('/').context("invalid npm scope/name")?; |
| 189 | if !valid(scope) || !valid(name) { |
| 190 | bail!("invalid npm scope/name"); |
| 191 | } |
| 192 | name |
| 193 | } else { |
| 194 | if !valid(package) { |
| 195 | bail!("invalid npm package name"); |
| 196 | } |
| 197 | package |
| 198 | }; |
| 199 | let parsed = |
| 200 | semver::Version::parse(version).context("npm plugin version must be exact")?; |
| 201 | if parsed.to_string() != version { |
| 202 | bail!("npm plugin version must be canonical"); |
| 203 | } |
| 204 | return Ok(Self::Remote(InstallSource::DirectUrl(format!( |
| 205 | "https://registry.npmjs.org/{package}/-/{name}-{version}.tgz" |
| 206 | )))); |
| 207 | } |
| 208 | if let Some(path) = trimmed.strip_prefix("path:") { |
| 209 | return Self::local(path, inspect_fs); |
| 210 | } |
| 211 | if let Some(path) = trimmed.strip_prefix("dsh:") { |
| 212 | let path = path.trim(); |
| 213 | if path.is_empty() { |
| 214 | bail!("DSH package path must not be empty"); |
| 215 | } |
| 216 | return Ok(Self::Dsh(PathBuf::from(path))); |
| 217 | } |
| 218 | if trimmed.starts_with("github:") |
| 219 | || trimmed.starts_with("https://") |
| 220 | || trimmed.starts_with("http://") |
| 221 | { |
| 222 | let source = InstallSource::parse(trimmed)?; |
| 223 | return match source { |
| 224 | InstallSource::GitHubRepo(_) | InstallSource::DirectUrl(_) => { |
| 225 | remote_fragment(&source)?; |
| 226 | Ok(Self::Remote(source)) |
| 227 | } |
| 228 | InstallSource::Registry(_) => { |
| 229 | unreachable!("prefixed specs never parse as a registry name") |
| 230 | } |
| 231 | }; |
| 232 | } |
| 233 | Self::local(trimmed, inspect_fs) |
| 234 | } |
| 235 | |
| 236 | fn local(spec: &str, inspect_fs: bool) -> Result<Self> { |
| 237 | let trimmed = spec.trim(); |
| 238 | if trimmed.is_empty() { |
| 239 | bail!("local install path must not be empty"); |
| 240 | } |
| 241 | let path = PathBuf::from(trimmed); |
| 242 | if inspect_fs && dsh::try_is_dsh_package(&path)? { |
| 243 | return Ok(Self::Dsh(path)); |
| 244 | } |
| 245 | Ok(Self::LocalPath(path)) |
| 246 | } |
| 247 | |
| 248 | pub(crate) fn pin_archive_spec(spec: &str, sha256: &str) -> Result<(String, String), String> { |
| 249 | let digest = sha256.trim().to_ascii_lowercase(); |
| 250 | if digest.len() != 64 || !digest.bytes().all(|ch| ch.is_ascii_hexdigit()) { |
| 251 | return Err(format!( |
| 252 | "archive sha256 pin `{sha256}` must be 64 hexadecimal characters" |
| 253 | )); |
| 254 | } |
| 255 | let spec = spec.trim(); |
| 256 | let separator = if spec.contains('#') { '&' } else { '#' }; |
| 257 | let pinned = format!("{spec}{separator}sha256={digest}"); |
| 258 | match Self::parse(&pinned) { |
| 259 | Ok(Self::Remote(InstallSource::DirectUrl(_))) => Ok((pinned, digest)), |
| 260 | Ok(_) => Err("a sha256 pin applies only to an http(s) archive URL source".to_string()), |
| 261 | Err(err) => Err(format!("cannot pin `{spec}` to a sha256: {err}")), |
| 262 | } |
| 263 | } |
| 264 | } |
| 265 | |
| 266 | /// Read a repository archive's fragment: `path=` selects one manifest-rooted |
| 267 | /// bundle and `sha256=` pins the archive bytes. The fragment is local install |
| 268 | /// metadata, never sent to or executed by a server. |
| 269 | fn remote_fragment(source: &InstallSource) -> Result<(Option<String>, Option<String>)> { |
| 270 | let InstallSource::DirectUrl(raw) = source else { |
| 271 | return Ok((None, None)); |
| 272 | }; |
| 273 | let url = reqwest::Url::parse(raw).context("invalid plugin archive URL")?; |
| 274 | let Some(fragment) = url.fragment() else { |
| 275 | return Ok((None, None)); |
| 276 | }; |
| 277 | let (mut path, mut sha256) = (None, None); |
| 278 | for part in fragment.split('&') { |
| 279 | match part.split_once('=') { |
| 280 | Some(("path", value)) if path.is_none() => path = Some(value), |
| 281 | Some(("sha256", value)) if sha256.is_none() => sha256 = Some(value), |
| 282 | _ => bail!( |
| 283 | "plugin archive fragment must be #path=<bundle-directory>, #sha256=<hex>, or both joined by &" |
| 284 | ), |
| 285 | } |
| 286 | } |
| 287 | if let Some(path) = path |
| 288 | && (path.is_empty() |
| 289 | || !path.split('/').all(|part| { |
| 290 | !part.is_empty() |
| 291 | && part != "." |
| 292 | && part != ".." |
| 293 | && part |
| 294 | .bytes() |
| 295 | .all(|ch| ch.is_ascii_alphanumeric() || matches!(ch, b'-' | b'_' | b'.')) |
| 296 | })) |
| 297 | { |
| 298 | bail!("plugin archive bundle path must contain only safe relative directory names"); |
| 299 | } |
| 300 | if let Some(digest) = sha256 |
| 301 | && (digest.len() != 64 |
| 302 | || !digest |
| 303 | .bytes() |
| 304 | .all(|ch| ch.is_ascii_digit() || (b'a'..=b'f').contains(&ch))) |
| 305 | { |
| 306 | bail!("plugin archive sha256 pin must be 64 lowercase hexadecimal characters"); |
| 307 | } |
| 308 | Ok((path.map(str::to_string), sha256.map(str::to_string))) |
| 309 | } |
| 310 | |
| 311 | /// Serialize a source for the `.installed-from` marker. Must round-trip |
| 312 | /// through [`PluginInstallSource::parse`]. |
| 313 | fn plugin_spec_string(source: &PluginInstallSource, canonical_source: Option<&Path>) -> String { |
| 314 | match source { |
| 315 | PluginInstallSource::LocalPath(_) => { |
| 316 | let path = canonical_source.expect("local installs record the canonical source"); |
| 317 | format!("path:{}", path.display()) |
| 318 | } |
| 319 | PluginInstallSource::Remote(remote) => source_spec_string(remote), |
| 320 | PluginInstallSource::Dsh(_) => { |
| 321 | let path = canonical_source.expect("DSH installs record the canonical source"); |
| 322 | format!("dsh:{}", path.display()) |
| 323 | } |
| 324 | } |
| 325 | } |
| 326 | |
| 327 | // ───────────────────────────────────────────────────────────────────────────── |
| 328 | // Outcome / result types |
| 329 | // ───────────────────────────────────────────────────────────────────────────── |
| 330 | |
| 331 | /// Outcome of an install attempt. Same shape as the skill installer's so the |
| 332 | /// caller can drop `NeedsApproval`/`NetworkDenied` into its approval flow. |
| 333 | #[derive(Debug)] |
| 334 | pub enum PluginInstallOutcome { |
| 335 | /// The bundle was installed (atomic rename + marker write succeeded). |
| 336 | Installed(InstalledPlugin), |
| 337 | /// The download host requires user approval; nothing touched disk. |
| 338 | NeedsApproval(String), |
| 339 | /// The download host is denied by network policy. |
| 340 | NetworkDenied(String), |
| 341 | } |
| 342 | |
| 343 | /// Metadata for a successfully installed plugin bundle. |
| 344 | #[derive(Debug, Clone)] |
| 345 | pub struct InstalledPlugin { |
| 346 | /// Plugin name from `[plugin].name`; also the destination directory name. |
| 347 | pub name: String, |
| 348 | /// Final on-disk path: `<user_plugins_dir>/<name>/`. |
| 349 | pub path: PathBuf, |
| 350 | /// Whole-bundle content hash of the staged tree (pre-marker). Informational; |
| 351 | /// trust receipts always bind to the discovery-time hash. |
| 352 | pub content_hash: String, |
| 353 | /// Whole-bundle hash after the provenance marker is written. Callers can |
| 354 | /// compare this with immediate rediscovery before reporting success. |
| 355 | pub installed_content_hash: String, |
| 356 | /// SHA-256 over the downloaded tarball bytes (empty for local copies). |
| 357 | /// Used by [`update`] to detect upstream changes without re-extracting. |
| 358 | pub source_checksum: String, |
| 359 | } |
| 360 | |
| 361 | /// Result of an [`update`] call. |
| 362 | #[derive(Debug)] |
| 363 | pub enum PluginUpdateResult { |
| 364 | /// Source is unchanged; local bundles also match the actual installed tree. |
| 365 | NoChange, |
| 366 | /// Content changed and a replacement bundle was published. |
| 367 | Updated(InstalledPlugin), |
| 368 | /// Network policy requires approval for the download host. |
| 369 | NeedsApproval(String), |
| 370 | /// Network policy denied the download host. |
| 371 | NetworkDenied(String), |
| 372 | } |
| 373 | |
| 374 | /// Install-time errors, kept as an enum so tests can pattern-match without |
| 375 | /// parsing strings. |
| 376 | #[derive(Debug, Error)] |
| 377 | pub enum PluginInstallError { |
| 378 | #[error("entry escapes destination directory: {0}")] |
| 379 | PathTraversal(String), |
| 380 | #[error("bundle is too large; uncompressed total would exceed {limit} bytes")] |
| 381 | OversizedBundle { limit: u64 }, |
| 382 | #[error("archive entry name is longer than {limit} bytes")] |
| 383 | EntryNameTooLong { limit: usize }, |
| 384 | #[error( |
| 385 | "archive must contain exactly one plugin bundle root (a directory holding plugin.json, kimi.plugin.json, plugin.toml, or a DeepSeek Harness package.json); found {0} (install a single plugin bundle, not a mono-repo)" |
| 386 | )] |
| 387 | PluginTomlRoots(usize), |
| 388 | #[error("symlinks and hard links are not allowed in plugin bundles")] |
| 389 | SymlinkRejected, |
| 390 | #[error("plugin '{0}' is already installed; use /plugin update or uninstall it first")] |
| 391 | AlreadyInstalled(String), |
| 392 | #[error( |
| 393 | "plugin '{0}' was not installed via /plugin install (no .installed-from marker); refusing to touch the hand-placed bundle" |
| 394 | )] |
| 395 | NotInstalledHere(String), |
| 396 | } |
| 397 | |
| 398 | // ───────────────────────────────────────────────────────────────────────────── |
| 399 | // Public API |
| 400 | // ───────────────────────────────────────────────────────────────────────────── |
| 401 | |
| 402 | /// Install a plugin bundle into `user_plugins_dir`. |
| 403 | /// |
| 404 | /// Steps: resolve source → (remote only) network-gate and download under the |
| 405 | /// size cap → stage into a `.staging-*` sibling, enforcing traversal/symlink/ |
| 406 | /// size rules and the single-manifest-root requirement → validate the staged |
| 407 | /// manifest → `name_conflict` check → atomic rename into `<name>/` → write |
| 408 | /// `.installed-from` last. |
| 409 | /// |
| 410 | /// `update = false` rejects an existing destination. `update = true` (only |
| 411 | /// called from [`update`]) requires the marker and reserves a unique backup. |
| 412 | /// A failed placement restores only into an absent destination; errors after |
| 413 | /// publication retain the current path and prior backup for recovery. |
| 414 | /// |
| 415 | /// `name_conflict` is consulted with the validated manifest name before the |
| 416 | /// rename; returning `Some(message)` aborts the install. It lets the caller |
| 417 | /// reject names already claimed by builtin/workspace bundles. |
| 418 | pub async fn install( |
| 419 | source: PluginInstallSource, |
| 420 | user_plugins_dir: &Path, |
| 421 | max_size: u64, |
| 422 | network: &NetworkPolicy, |
| 423 | update: bool, |
| 424 | name_conflict: &(dyn Fn(&str) -> Option<String> + Send + Sync), |
| 425 | ) -> Result<PluginInstallOutcome> { |
| 426 | install_inner( |
| 427 | source, |
| 428 | user_plugins_dir, |
| 429 | max_size, |
| 430 | network, |
| 431 | update, |
| 432 | name_conflict, |
| 433 | None, |
| 434 | ) |
| 435 | .await |
| 436 | } |
| 437 | |
| 438 | /// Install only when the exact bytes copied into staging match a prior |
| 439 | /// review hash. The comparison happens before atomic placement, so a source |
| 440 | /// that changes between inspection and copying leaves no installed bundle. |
| 441 | pub async fn install_with_expected_content_hash( |
| 442 | source: PluginInstallSource, |
| 443 | user_plugins_dir: &Path, |
| 444 | max_size: u64, |
| 445 | network: &NetworkPolicy, |
| 446 | name_conflict: &(dyn Fn(&str) -> Option<String> + Send + Sync), |
| 447 | expected_content_hash: &str, |
| 448 | ) -> Result<PluginInstallOutcome> { |
| 449 | install_inner( |
| 450 | source, |
| 451 | user_plugins_dir, |
| 452 | max_size, |
| 453 | network, |
| 454 | false, |
| 455 | name_conflict, |
| 456 | Some(expected_content_hash), |
| 457 | ) |
| 458 | .await |
| 459 | } |
| 460 | |
| 461 | async fn install_inner( |
| 462 | source: PluginInstallSource, |
| 463 | user_plugins_dir: &Path, |
| 464 | max_size: u64, |
| 465 | network: &NetworkPolicy, |
| 466 | update: bool, |
| 467 | name_conflict: &(dyn Fn(&str) -> Option<String> + Send + Sync), |
| 468 | expected_content_hash: Option<&str>, |
| 469 | ) -> Result<PluginInstallOutcome> { |
| 470 | match &source { |
| 471 | PluginInstallSource::LocalPath(path) => { |
| 472 | let path = path.clone(); |
| 473 | let dir = user_plugins_dir.to_path_buf(); |
| 474 | let expected = expected_content_hash.map(str::to_string); |
| 475 | let (staged, canonical) = off_runtime(move || { |
| 476 | let staged = stage_local_copy(&path, &dir, max_size)?; |
| 477 | verify_expected_content_hash(&staged, expected.as_deref())?; |
| 478 | match path.canonicalize() { |
| 479 | Ok(canonical) => Ok((staged, canonical)), |
| 480 | Err(error) => { |
| 481 | let _ = fs::remove_dir_all(&staged.staged_path); |
| 482 | Err(error).with_context(|| format!("failed to resolve {}", path.display())) |
| 483 | } |
| 484 | } |
| 485 | }) |
| 486 | .await?; |
| 487 | publish_staged( |
| 488 | StagedOutcome::Ready(staged), |
| 489 | name_conflict, |
| 490 | plugin_spec_string(&source, Some(&canonical)), |
| 491 | None, |
| 492 | String::new(), |
| 493 | user_plugins_dir, |
| 494 | update, |
| 495 | ) |
| 496 | .await |
| 497 | .map(|outcome| outcome.expect("fresh installs are never unchanged")) |
| 498 | } |
| 499 | PluginInstallSource::Dsh(package) => { |
| 500 | let converted = match convert_dsh_off_runtime(package.clone(), network.clone()).await { |
| 501 | Ok(converted) => converted, |
| 502 | Err(err) => { |
| 503 | if let Some(net_err) = err.downcast_ref::<NpmDepsNetworkError>() { |
| 504 | return Ok(match net_err { |
| 505 | NpmDepsNetworkError::NeedsApproval(host) => { |
| 506 | PluginInstallOutcome::NeedsApproval((*host).to_string()) |
| 507 | } |
| 508 | NpmDepsNetworkError::Denied(host) => { |
| 509 | PluginInstallOutcome::NetworkDenied((*host).to_string()) |
| 510 | } |
| 511 | }); |
| 512 | } |
| 513 | return Err(err); |
| 514 | } |
| 515 | }; |
| 516 | install_converted_dsh( |
| 517 | converted, |
| 518 | user_plugins_dir, |
| 519 | max_size, |
| 520 | update, |
| 521 | name_conflict, |
| 522 | expected_content_hash, |
| 523 | None, |
| 524 | ) |
| 525 | .await |
| 526 | .map(|outcome| outcome.expect("fresh installs are never unchanged")) |
| 527 | } |
| 528 | PluginInstallSource::Remote(remote) => { |
| 529 | let (bytes, url) = match fetch_tarball(remote, network, max_size).await? { |
| 530 | FetchOutcome::Bytes { bytes, url } => (bytes, url), |
| 531 | FetchOutcome::NeedsApproval(host) => { |
| 532 | return Ok(PluginInstallOutcome::NeedsApproval(host)); |
| 533 | } |
| 534 | FetchOutcome::Denied(host) => { |
| 535 | return Ok(PluginInstallOutcome::NetworkDenied(host)); |
| 536 | } |
| 537 | }; |
| 538 | install_remote_bytes( |
| 539 | remote, |
| 540 | bytes, |
| 541 | &url, |
| 542 | network, |
| 543 | user_plugins_dir, |
| 544 | max_size, |
| 545 | update, |
| 546 | name_conflict, |
| 547 | expected_content_hash, |
| 548 | None, |
| 549 | ) |
| 550 | .await |
| 551 | .map(|outcome| outcome.expect("fresh installs are never unchanged")) |
| 552 | } |
| 553 | } |
| 554 | } |
| 555 | |
| 556 | /// A DSH package converted into scratch; the scratch directory lives as long |
| 557 | /// as this value. |
| 558 | struct ConvertedDsh { |
| 559 | canonical: PathBuf, |
| 560 | _scratch: tempfile::TempDir, |
| 561 | bundle: PathBuf, |
| 562 | } |
| 563 | |
| 564 | /// Parse and convert off the async runtime: conversion reads and copies the |
| 565 | /// whole package synchronously. |
| 566 | async fn convert_dsh_off_runtime(package: PathBuf, network: NetworkPolicy) -> Result<ConvertedDsh> { |
| 567 | #[cfg(any(test, feature = "test-support"))] |
| 568 | let env_scope = codewhale_runtime::test_support::env_scope_ticket(); |
| 569 | tokio::task::spawn_blocking(move || { |
| 570 | #[cfg(any(test, feature = "test-support"))] |
| 571 | let _env_scope = codewhale_runtime::test_support::join_env_scope(env_scope); |
| 572 | let canonical = package |
| 573 | .canonicalize() |
| 574 | .with_context(|| format!("failed to resolve {}", package.display()))?; |
| 575 | let (scratch, bundle, _conversion) = |
| 576 | dsh::convert_to_scratch_with_network(&canonical, Some(&network))?; |
| 577 | Ok(ConvertedDsh { |
| 578 | canonical, |
| 579 | _scratch: scratch, |
| 580 | bundle, |
| 581 | }) |
| 582 | }) |
| 583 | .await |
| 584 | .context("DSH conversion task failed")? |
| 585 | } |
| 586 | |
| 587 | struct DshUnchangedCheck { |
| 588 | expected_source_checksum: String, |
| 589 | target: PathBuf, |
| 590 | marker_body: String, |
| 591 | } |
| 592 | |
| 593 | /// Stage, verify and place a converted DSH bundle exactly like a local one. |
| 594 | /// The marker records the package and the converted bundle's content hash, |
| 595 | /// so update re-converts and can tell an unchanged package from a changed one. |
| 596 | #[allow(clippy::too_many_arguments)] |
| 597 | async fn install_converted_dsh( |
| 598 | converted: ConvertedDsh, |
| 599 | user_plugins_dir: &Path, |
| 600 | max_size: u64, |
| 601 | update: bool, |
| 602 | name_conflict: &(dyn Fn(&str) -> Option<String> + Send + Sync), |
| 603 | expected_content_hash: Option<&str>, |
| 604 | unchanged_check: Option<DshUnchangedCheck>, |
| 605 | ) -> Result<Option<PluginInstallOutcome>> { |
| 606 | let canonical = converted.canonical.clone(); |
| 607 | let dir = user_plugins_dir.to_path_buf(); |
| 608 | let expected = expected_content_hash.map(str::to_string); |
| 609 | let staged = off_runtime(move || { |
| 610 | let staged = stage_local_copy(&converted.bundle, &dir, max_size)?; |
| 611 | verify_expected_content_hash(&staged, expected.as_deref())?; |
| 612 | let unchanged_from = unchanged_check.and_then(|check| { |
| 613 | (staged.content_hash == check.expected_source_checksum) |
| 614 | .then_some((check.target, check.marker_body)) |
| 615 | }); |
| 616 | ready_or_unchanged(staged, unchanged_from) |
| 617 | }) |
| 618 | .await?; |
| 619 | let checksum = match &staged { |
| 620 | StagedOutcome::Ready(staged) => staged.content_hash.clone(), |
| 621 | _ => String::new(), |
| 622 | }; |
| 623 | publish_staged( |
| 624 | staged, |
| 625 | name_conflict, |
| 626 | plugin_spec_string( |
| 627 | &PluginInstallSource::Dsh(canonical.clone()), |
| 628 | Some(&canonical), |
| 629 | ), |
| 630 | None, |
| 631 | checksum, |
| 632 | user_plugins_dir, |
| 633 | update, |
| 634 | ) |
| 635 | .await |
| 636 | } |
| 637 | |
| 638 | enum StagedOutcome { |
| 639 | Ready(stage::StagedPlugin), |
| 640 | Blocked(PluginInstallOutcome), |
| 641 | Unchanged, |
| 642 | } |
| 643 | |
| 644 | async fn off_runtime<T: Send + 'static>( |
| 645 | work: impl FnOnce() -> Result<T> + Send + 'static, |
| 646 | ) -> Result<T> { |
| 647 | #[cfg(any(test, feature = "test-support"))] |
| 648 | let env_scope = codewhale_runtime::test_support::env_scope_ticket(); |
| 649 | tokio::task::spawn_blocking(move || { |
| 650 | #[cfg(any(test, feature = "test-support"))] |
| 651 | let _env_scope = codewhale_runtime::test_support::join_env_scope(env_scope); |
| 652 | work() |
| 653 | }) |
| 654 | .await |
| 655 | .context("plugin install task failed")? |
| 656 | } |
| 657 | |
| 658 | fn network_outcome(err: anyhow::Error) -> Result<PluginInstallOutcome> { |
| 659 | match err.downcast_ref::<NpmDepsNetworkError>() { |
| 660 | Some(NpmDepsNetworkError::NeedsApproval(host)) => { |
| 661 | Ok(PluginInstallOutcome::NeedsApproval((*host).to_string())) |
| 662 | } |
| 663 | Some(NpmDepsNetworkError::Denied(host)) => { |
| 664 | Ok(PluginInstallOutcome::NetworkDenied((*host).to_string())) |
| 665 | } |
| 666 | None => Err(err), |
| 667 | } |
| 668 | } |
| 669 | |
| 670 | fn installed_matches_staged(staged_path: &Path, target: &Path, marker_body: &str) -> Result<bool> { |
| 671 | fs::write(staged_path.join(INSTALLED_FROM_MARKER), marker_body)?; |
| 672 | let (_, expected_hash) = stage::validate_staged(staged_path)?; |
| 673 | let (_, installed_hash) = stage::validate_staged(target).context( |
| 674 | "installed plugin failed validation; unchanged source was not accepted and the installed copy was preserved", |
| 675 | )?; |
| 676 | fs::remove_file(staged_path.join(INSTALLED_FROM_MARKER))?; |
| 677 | Ok(expected_hash == installed_hash) |
| 678 | } |
| 679 | |
| 680 | fn ready_or_unchanged( |
| 681 | staged: stage::StagedPlugin, |
| 682 | unchanged_from: Option<(PathBuf, String)>, |
| 683 | ) -> Result<StagedOutcome> { |
| 684 | let Some((target, marker_body)) = unchanged_from else { |
| 685 | return Ok(StagedOutcome::Ready(staged)); |
| 686 | }; |
| 687 | match installed_matches_staged(&staged.staged_path, &target, &marker_body) { |
| 688 | Ok(true) => { |
| 689 | fs::remove_dir_all(&staged.staged_path) |
| 690 | .context("failed to remove unchanged plugin staging copy")?; |
| 691 | Ok(StagedOutcome::Unchanged) |
| 692 | } |
| 693 | Ok(false) => Ok(StagedOutcome::Ready(staged)), |
| 694 | Err(err) => { |
| 695 | let _ = fs::remove_dir_all(&staged.staged_path); |
| 696 | Err(err) |
| 697 | } |
| 698 | } |
| 699 | } |
| 700 | |
| 701 | async fn publish_staged( |
| 702 | staged: StagedOutcome, |
| 703 | name_conflict: &(dyn Fn(&str) -> Option<String> + Send + Sync), |
| 704 | spec: String, |
| 705 | url: Option<String>, |
| 706 | checksum: String, |
| 707 | user_plugins_dir: &Path, |
| 708 | update: bool, |
| 709 | ) -> Result<Option<PluginInstallOutcome>> { |
| 710 | let staged = match staged { |
| 711 | StagedOutcome::Ready(staged) => staged, |
| 712 | StagedOutcome::Blocked(outcome) => return Ok(Some(outcome)), |
| 713 | StagedOutcome::Unchanged => return Ok(None), |
| 714 | }; |
| 715 | if let Some(conflict) = name_conflict(&staged.name) { |
| 716 | let _ = tokio::fs::remove_dir_all(&staged.staged_path).await; |
| 717 | return Err(PluginNameConflict(conflict).into()); |
| 718 | } |
| 719 | let dir = user_plugins_dir.to_path_buf(); |
| 720 | off_runtime(move || { |
| 721 | finalize_install(staged, &spec, url.as_deref(), &checksum, &dir, update).map(Some) |
| 722 | }) |
| 723 | .await |
| 724 | } |
| 725 | |
| 726 | /// Review a DSH package without installing it: the conversion receipt and the |
| 727 | /// content hash that an exact install of the same package will stage. |
| 728 | pub fn preview_dsh(package: &Path) -> Result<(dsh::DshConversion, String)> { |
| 729 | preview_dsh_with_network_opt(package, None) |
| 730 | } |
| 731 | |
| 732 | pub fn preview_dsh_with_network( |
| 733 | package: &Path, |
| 734 | network: &NetworkPolicy, |
| 735 | ) -> Result<(dsh::DshConversion, String)> { |
| 736 | preview_dsh_with_network_opt(package, Some(network)) |
| 737 | } |
| 738 | |
| 739 | fn preview_dsh_with_network_opt( |
| 740 | package: &Path, |
| 741 | network: Option<&NetworkPolicy>, |
| 742 | ) -> Result<(dsh::DshConversion, String)> { |
| 743 | let (_scratch, bundle, conversion) = dsh::convert_to_scratch_with_network(package, network)?; |
| 744 | let manifest = crate::agent_plugin::resolve_manifest_path(&bundle) |
| 745 | .context("converted DSH bundle has no manifest")?; |
| 746 | let validated = PluginManifest::validate_from_path(&manifest) |
| 747 | .map_err(|error| anyhow::anyhow!("converted DSH bundle failed validation: {error}"))?; |
| 748 | Ok((conversion, validated.content_hash)) |
| 749 | } |
| 750 | |
| 751 | fn verify_expected_content_hash( |
| 752 | staged: &stage::StagedPlugin, |
| 753 | expected_content_hash: Option<&str>, |
| 754 | ) -> Result<()> { |
| 755 | let Some(expected) = expected_content_hash else { |
| 756 | return Ok(()); |
| 757 | }; |
| 758 | if staged.content_hash == expected { |
| 759 | return Ok(()); |
| 760 | } |
| 761 | let actual = staged.content_hash.clone(); |
| 762 | let _ = fs::remove_dir_all(&staged.staged_path); |
| 763 | Err(PluginContentMismatch { |
| 764 | expected: expected.to_string(), |
| 765 | actual, |
| 766 | } |
| 767 | .into()) |
| 768 | } |
| 769 | |
| 770 | #[derive(Debug, Clone)] |
| 771 | pub struct DownloadedRemote { |
| 772 | pub remote: InstallSource, |
| 773 | pub resolved_url: String, |
| 774 | pub bytes: Vec<u8>, |
| 775 | } |
| 776 | |
| 777 | #[derive(Debug)] |
| 778 | pub enum RemoteDownloadOutcome { |
| 779 | Downloaded { |
| 780 | archive: DownloadedRemote, |
| 781 | has_npm_deps: bool, |
| 782 | }, |
| 783 | NeedsApproval(String), |
| 784 | NetworkDenied(String), |
| 785 | } |
| 786 | |
| 787 | #[derive(Debug, Clone)] |
| 788 | pub struct PreparedRemote { |
| 789 | pub remote: InstallSource, |
| 790 | pub resolved_url: String, |
| 791 | pub bytes: Vec<u8>, |
| 792 | pub name: String, |
| 793 | pub content_hash: String, |
| 794 | } |
| 795 | |
| 796 | #[derive(Debug)] |
| 797 | pub enum RemotePreviewOutcome { |
| 798 | Ready(PreparedRemote), |
| 799 | NeedsApproval(String), |
| 800 | NetworkDenied(String), |
| 801 | } |
| 802 | |
| 803 | pub async fn download_remote_install_archive( |
| 804 | remote: InstallSource, |
| 805 | max_size: u64, |
| 806 | network: &NetworkPolicy, |
| 807 | ) -> Result<RemoteDownloadOutcome> { |
| 808 | let (bytes, url) = match fetch_tarball(&remote, network, max_size).await? { |
| 809 | FetchOutcome::Bytes { bytes, url } => (bytes, url), |
| 810 | FetchOutcome::NeedsApproval(host) => { |
| 811 | return Ok(RemoteDownloadOutcome::NeedsApproval(host)); |
| 812 | } |
| 813 | FetchOutcome::Denied(host) => { |
| 814 | return Ok(RemoteDownloadOutcome::NetworkDenied(host)); |
| 815 | } |
| 816 | }; |
| 817 | let checksum = sha256_hex(&bytes); |
| 818 | let (bundle_path, pinned_sha256) = remote_fragment(&remote)?; |
| 819 | if let Some(pinned) = pinned_sha256 |
| 820 | && pinned != checksum |
| 821 | { |
| 822 | return Err(PluginArchiveMismatch { |
| 823 | url, |
| 824 | expected: pinned, |
| 825 | actual: checksum, |
| 826 | } |
| 827 | .into()); |
| 828 | } |
| 829 | let bytes_clone = bytes.clone(); |
| 830 | #[cfg(any(test, feature = "test-support"))] |
| 831 | let env_scope = codewhale_runtime::test_support::env_scope_ticket(); |
| 832 | let has_npm_deps = tokio::task::spawn_blocking(move || -> Result<bool> { |
| 833 | #[cfg(any(test, feature = "test-support"))] |
| 834 | let _env_scope = codewhale_runtime::test_support::join_env_scope(env_scope); |
| 835 | let scan = |
| 836 | tarball::scan_tarball_for_bundle(&bytes_clone, max_size, bundle_path.as_deref())?; |
| 837 | if !scan.is_dsh { |
| 838 | return Ok(false); |
| 839 | } |
| 840 | let raw_dir = tempfile::tempdir().context("failed to create DSH extraction dir")?; |
| 841 | tarball::extract_into(&scan, &bytes_clone, raw_dir.path(), max_size)?; |
| 842 | dsh::has_unresolved_npm_dependencies(raw_dir.path()) |
| 843 | }) |
| 844 | .await |
| 845 | .context("remote archive inspection task failed")??; |
| 846 | Ok(RemoteDownloadOutcome::Downloaded { |
| 847 | archive: DownloadedRemote { |
| 848 | remote, |
| 849 | resolved_url: url, |
| 850 | bytes, |
| 851 | }, |
| 852 | has_npm_deps, |
| 853 | }) |
| 854 | } |
| 855 | |
| 856 | pub async fn stage_downloaded_remote_install( |
| 857 | archive: DownloadedRemote, |
| 858 | max_size: u64, |
| 859 | network: Option<&NetworkPolicy>, |
| 860 | ) -> Result<RemotePreviewOutcome> { |
| 861 | let (bundle_path, _) = remote_fragment(&archive.remote)?; |
| 862 | let network_clone = network.cloned(); |
| 863 | let bytes_clone = archive.bytes.clone(); |
| 864 | #[cfg(any(test, feature = "test-support"))] |
| 865 | let env_scope = codewhale_runtime::test_support::env_scope_ticket(); |
| 866 | let staged = tokio::task::spawn_blocking(move || -> Result<_> { |
| 867 | #[cfg(any(test, feature = "test-support"))] |
| 868 | let _env_scope = codewhale_runtime::test_support::join_env_scope(env_scope); |
| 869 | let stage_root = tempfile::Builder::new() |
| 870 | .prefix("codewhale-remote-preview-") |
| 871 | .tempdir()?; |
| 872 | let staged = stage_tarball_with_network( |
| 873 | &bytes_clone, |
| 874 | stage_root.path(), |
| 875 | max_size, |
| 876 | bundle_path.as_deref(), |
| 877 | network_clone.as_ref(), |
| 878 | )?; |
| 879 | Ok((staged.name, staged.content_hash)) |
| 880 | }) |
| 881 | .await |
| 882 | .context("remote preview staging task failed")?; |
| 883 | match staged { |
| 884 | Ok((name, content_hash)) => Ok(RemotePreviewOutcome::Ready(PreparedRemote { |
| 885 | remote: archive.remote, |
| 886 | resolved_url: archive.resolved_url, |
| 887 | bytes: archive.bytes, |
| 888 | name, |
| 889 | content_hash, |
| 890 | })), |
| 891 | Err(err) => match err.downcast_ref::<NpmDepsNetworkError>() { |
| 892 | Some(NpmDepsNetworkError::NeedsApproval(host)) => { |
| 893 | Ok(RemotePreviewOutcome::NeedsApproval((*host).to_string())) |
| 894 | } |
| 895 | Some(NpmDepsNetworkError::Denied(host)) => { |
| 896 | Ok(RemotePreviewOutcome::NetworkDenied((*host).to_string())) |
| 897 | } |
| 898 | None => Err(err), |
| 899 | }, |
| 900 | } |
| 901 | } |
| 902 | |
| 903 | pub async fn prepare_remote_install( |
| 904 | remote: InstallSource, |
| 905 | max_size: u64, |
| 906 | network: &NetworkPolicy, |
| 907 | ) -> Result<RemotePreviewOutcome> { |
| 908 | match download_remote_install_archive(remote, max_size, network).await? { |
| 909 | RemoteDownloadOutcome::Downloaded { archive, .. } => { |
| 910 | stage_downloaded_remote_install(archive, max_size, Some(network)).await |
| 911 | } |
| 912 | RemoteDownloadOutcome::NeedsApproval(host) => Ok(RemotePreviewOutcome::NeedsApproval(host)), |
| 913 | RemoteDownloadOutcome::NetworkDenied(host) => Ok(RemotePreviewOutcome::NetworkDenied(host)), |
| 914 | } |
| 915 | } |
| 916 | |
| 917 | pub async fn install_prepared_remote( |
| 918 | prepared: &PreparedRemote, |
| 919 | user_plugins_dir: &Path, |
| 920 | max_size: u64, |
| 921 | network: &NetworkPolicy, |
| 922 | name_conflict: &(dyn Fn(&str) -> Option<String> + Send + Sync), |
| 923 | expected_content_hash: &str, |
| 924 | ) -> Result<PluginInstallOutcome> { |
| 925 | install_remote_bytes( |
| 926 | &prepared.remote, |
| 927 | prepared.bytes.clone(), |
| 928 | &prepared.resolved_url, |
| 929 | network, |
| 930 | user_plugins_dir, |
| 931 | max_size, |
| 932 | false, |
| 933 | name_conflict, |
| 934 | Some(expected_content_hash), |
| 935 | None, |
| 936 | ) |
| 937 | .await |
| 938 | .map(|outcome| outcome.expect("fresh installs are never unchanged")) |
| 939 | } |
| 940 | |
| 941 | /// Stage and finalize an already-downloaded remote tarball. Kept separate |
| 942 | /// from [`install`] so [`update`] can compare the checksum of the bytes it |
| 943 | /// already fetched instead of downloading twice. |
| 944 | #[allow(clippy::too_many_arguments)] |
| 945 | async fn install_remote_bytes( |
| 946 | remote: &InstallSource, |
| 947 | bytes: Vec<u8>, |
| 948 | url: &str, |
| 949 | network: &NetworkPolicy, |
| 950 | user_plugins_dir: &Path, |
| 951 | max_size: u64, |
| 952 | update: bool, |
| 953 | name_conflict: &(dyn Fn(&str) -> Option<String> + Send + Sync), |
| 954 | expected_content_hash: Option<&str>, |
| 955 | unchanged_from: Option<(PathBuf, String)>, |
| 956 | ) -> Result<Option<PluginInstallOutcome>> { |
| 957 | let checksum = sha256_hex(&bytes); |
| 958 | let (bundle_path, pinned_sha256) = remote_fragment(remote)?; |
| 959 | if let Some(pinned) = pinned_sha256 |
| 960 | && pinned != checksum |
| 961 | { |
| 962 | return Err(PluginArchiveMismatch { |
| 963 | url: url.to_string(), |
| 964 | expected: pinned, |
| 965 | actual: checksum, |
| 966 | } |
| 967 | .into()); |
| 968 | } |
| 969 | let dir = user_plugins_dir.to_path_buf(); |
| 970 | let network = network.clone(); |
| 971 | let expected = expected_content_hash.map(str::to_string); |
| 972 | let staged = off_runtime(move || { |
| 973 | let staged = match stage_tarball_with_network( |
| 974 | &bytes, |
| 975 | &dir, |
| 976 | max_size, |
| 977 | bundle_path.as_deref(), |
| 978 | Some(&network), |
| 979 | ) { |
| 980 | Ok(staged) => staged, |
| 981 | Err(err) => return network_outcome(err).map(StagedOutcome::Blocked), |
| 982 | }; |
| 983 | verify_expected_content_hash(&staged, expected.as_deref())?; |
| 984 | ready_or_unchanged(staged, unchanged_from) |
| 985 | }) |
| 986 | .await?; |
| 987 | publish_staged( |
| 988 | staged, |
| 989 | name_conflict, |
| 990 | source_spec_string(remote), |
| 991 | Some(url.to_string()), |
| 992 | checksum, |
| 993 | user_plugins_dir, |
| 994 | update, |
| 995 | ) |
| 996 | .await |
| 997 | } |
| 998 | |
| 999 | /// Refresh a previously installed plugin from its recorded source and publish |
| 1000 | /// a replacement if its content differs. A changed discovery-time hash requires |
| 1001 | /// current review through the registry's existing hash-bound trust receipts. |
| 1002 | /// |
| 1003 | /// Local bundles use the same bounded staging and backup/restore publication |
| 1004 | /// as installation. A failed source validation leaves the installed copy intact. |
| 1005 | pub async fn update( |
| 1006 | name: &str, |
| 1007 | user_plugins_dir: &Path, |
| 1008 | max_size: u64, |
| 1009 | network: &NetworkPolicy, |
| 1010 | ) -> Result<PluginUpdateResult> { |
| 1011 | let target = plugin_target_path(name, user_plugins_dir)?; |
| 1012 | if tokio::fs::try_exists(&target).await.unwrap_or(false) { |
| 1013 | ensure_target_within_plugins_dir(&target, user_plugins_dir)?; |
| 1014 | } |
| 1015 | let marker_path = target.join(INSTALLED_FROM_MARKER); |
| 1016 | if !tokio::fs::try_exists(&marker_path).await.unwrap_or(false) { |
| 1017 | return Err(PluginInstallError::NotInstalledHere(name.to_string()).into()); |
| 1018 | } |
| 1019 | let marker_body = tokio::fs::read_to_string(&marker_path) |
| 1020 | .await |
| 1021 | .with_context(|| format!("failed to read {}", marker_path.display()))?; |
| 1022 | let marker: InstalledFromMarker = serde_json::from_str(&marker_body) |
| 1023 | .with_context(|| format!("malformed {INSTALLED_FROM_MARKER} for {name}"))?; |
| 1024 | let source = if let Some(path) = marker.spec.trim().strip_prefix("path:") { |
| 1025 | let trimmed = path.trim(); |
| 1026 | if trimmed.is_empty() { |
| 1027 | bail!("local install path must not be empty"); |
| 1028 | } |
| 1029 | PluginInstallSource::LocalPath(PathBuf::from(trimmed)) |
| 1030 | } else { |
| 1031 | PluginInstallSource::parse(&marker.spec)? |
| 1032 | }; |
| 1033 | if let PluginInstallSource::LocalPath(path) = &source { |
| 1034 | let path = path.clone(); |
| 1035 | let user_plugins_dir = user_plugins_dir.to_path_buf(); |
| 1036 | let name = name.to_string(); |
| 1037 | #[cfg(any(test, feature = "test-support"))] |
| 1038 | let env_scope = codewhale_runtime::test_support::env_scope_ticket(); |
| 1039 | return tokio::task::spawn_blocking(move || { |
| 1040 | #[cfg(any(test, feature = "test-support"))] |
| 1041 | let _env_scope = codewhale_runtime::test_support::join_env_scope(env_scope); |
| 1042 | let staged = stage_local_copy(&path, &user_plugins_dir, max_size)?; |
| 1043 | let staged_path = staged.staged_path.clone(); |
| 1044 | let result = (|| { |
| 1045 | if staged.name != name { |
| 1046 | return Err(PluginNameConflict(format!( |
| 1047 | "updated plugin changed name from {name} to {}; original plugin preserved", |
| 1048 | staged.name |
| 1049 | )) |
| 1050 | .into()); |
| 1051 | } |
| 1052 | // Compare the actual installed tree using the existing complete |
| 1053 | // bundle hash, including executable intent and provenance. A historical |
| 1054 | // source digest alone cannot detect an altered installed payload. |
| 1055 | if installed_matches_staged(&staged_path, &target, &marker_body)? { |
| 1056 | fs::remove_dir_all(&staged_path) |
| 1057 | .context("failed to remove unchanged plugin staging copy")?; |
| 1058 | return Ok(PluginUpdateResult::NoChange); |
| 1059 | } |
| 1060 | match finalize_install(staged, &marker.spec, None, "", &user_plugins_dir, true)? { |
| 1061 | PluginInstallOutcome::Installed(installed) => { |
| 1062 | Ok(PluginUpdateResult::Updated(installed)) |
| 1063 | } |
| 1064 | PluginInstallOutcome::NeedsApproval(host) => { |
| 1065 | Ok(PluginUpdateResult::NeedsApproval(host)) |
| 1066 | } |
| 1067 | PluginInstallOutcome::NetworkDenied(host) => { |
| 1068 | Ok(PluginUpdateResult::NetworkDenied(host)) |
| 1069 | } |
| 1070 | } |
| 1071 | })(); |
| 1072 | if result.is_err() { |
| 1073 | let _ = fs::remove_dir_all(&staged_path); |
| 1074 | } |
| 1075 | result |
| 1076 | }) |
| 1077 | .await |
| 1078 | .context("local plugin update task failed")?; |
| 1079 | } |
| 1080 | if let PluginInstallSource::Dsh(package) = &source { |
| 1081 | let converted = match convert_dsh_off_runtime(package.clone(), network.clone()).await { |
| 1082 | Ok(converted) => converted, |
| 1083 | Err(err) => { |
| 1084 | if let Some(net_err) = err.downcast_ref::<NpmDepsNetworkError>() { |
| 1085 | return Ok(match net_err { |
| 1086 | NpmDepsNetworkError::NeedsApproval(host) => { |
| 1087 | PluginUpdateResult::NeedsApproval((*host).to_string()) |
| 1088 | } |
| 1089 | NpmDepsNetworkError::Denied(host) => { |
| 1090 | PluginUpdateResult::NetworkDenied((*host).to_string()) |
| 1091 | } |
| 1092 | }); |
| 1093 | } |
| 1094 | return Err(err); |
| 1095 | } |
| 1096 | }; |
| 1097 | let unchanged_check = Some(DshUnchangedCheck { |
| 1098 | expected_source_checksum: marker.source_checksum().to_string(), |
| 1099 | target: target.clone(), |
| 1100 | marker_body: marker_body.clone(), |
| 1101 | }); |
| 1102 | let Some(outcome) = install_converted_dsh( |
| 1103 | converted, |
| 1104 | user_plugins_dir, |
| 1105 | max_size, |
| 1106 | true, |
| 1107 | &|actual| { |
| 1108 | (actual != name).then(|| { |
| 1109 | format!("updated plugin changed name from {name} to {actual}; original plugin preserved") |
| 1110 | }) |
| 1111 | }, |
| 1112 | None, |
| 1113 | unchanged_check, |
| 1114 | ) |
| 1115 | .await? |
| 1116 | else { |
| 1117 | return Ok(PluginUpdateResult::NoChange); |
| 1118 | }; |
| 1119 | return match outcome { |
| 1120 | PluginInstallOutcome::Installed(installed) => { |
| 1121 | Ok(PluginUpdateResult::Updated(installed)) |
| 1122 | } |
| 1123 | PluginInstallOutcome::NeedsApproval(host) => { |
| 1124 | Ok(PluginUpdateResult::NeedsApproval(host)) |
| 1125 | } |
| 1126 | PluginInstallOutcome::NetworkDenied(host) => { |
| 1127 | Ok(PluginUpdateResult::NetworkDenied(host)) |
| 1128 | } |
| 1129 | }; |
| 1130 | } |
| 1131 | let PluginInstallSource::Remote(remote) = source else { |
| 1132 | unreachable!("local and converted sources returned above"); |
| 1133 | }; |
| 1134 | |
| 1135 | let (bytes, url) = match fetch_tarball(&remote, network, max_size).await? { |
| 1136 | FetchOutcome::Bytes { bytes, url } => (bytes, url), |
| 1137 | FetchOutcome::NeedsApproval(host) => { |
| 1138 | return Ok(PluginUpdateResult::NeedsApproval(host)); |
| 1139 | } |
| 1140 | FetchOutcome::Denied(host) => return Ok(PluginUpdateResult::NetworkDenied(host)), |
| 1141 | }; |
| 1142 | let unchanged_from = |
| 1143 | (sha256_hex(&bytes) == marker.source_checksum()).then(|| (target.clone(), marker_body)); |
| 1144 | |
| 1145 | let Some(outcome) = install_remote_bytes( |
| 1146 | &remote, |
| 1147 | bytes, |
| 1148 | &url, |
| 1149 | network, |
| 1150 | user_plugins_dir, |
| 1151 | max_size, |
| 1152 | true, |
| 1153 | &|actual| { |
| 1154 | (actual != name).then(|| { |
| 1155 | format!( |
| 1156 | "updated plugin changed name from {name} to {actual}; original plugin preserved" |
| 1157 | ) |
| 1158 | }) |
| 1159 | }, |
| 1160 | None, |
| 1161 | unchanged_from, |
| 1162 | ) |
| 1163 | .await? |
| 1164 | else { |
| 1165 | return Ok(PluginUpdateResult::NoChange); |
| 1166 | }; |
| 1167 | match outcome { |
| 1168 | PluginInstallOutcome::Installed(installed) => Ok(PluginUpdateResult::Updated(installed)), |
| 1169 | PluginInstallOutcome::NeedsApproval(host) => Ok(PluginUpdateResult::NeedsApproval(host)), |
| 1170 | PluginInstallOutcome::NetworkDenied(host) => Ok(PluginUpdateResult::NetworkDenied(host)), |
| 1171 | } |
| 1172 | } |
| 1173 | |
| 1174 | /// Check whether `bundle_root` carries a regular, non-link `.installed-from` file. |
| 1175 | pub fn has_regular_install_marker(bundle_root: &Path) -> bool { |
| 1176 | let marker = bundle_root.join(INSTALLED_FROM_MARKER); |
| 1177 | let Ok(meta) = fs::symlink_metadata(&marker) else { |
| 1178 | return false; |
| 1179 | }; |
| 1180 | if codewhale_util::path_identity::metadata_is_link_or_reparse(&meta) || !meta.is_file() { |
| 1181 | return false; |
| 1182 | } |
| 1183 | let Ok(file) = codewhale_util::bundle_file::open_bundle_file(&marker) else { |
| 1184 | return false; |
| 1185 | }; |
| 1186 | file.metadata().is_ok_and(|opened| { |
| 1187 | opened.is_file() && !codewhale_util::path_identity::metadata_is_link_or_reparse(&opened) |
| 1188 | }) |
| 1189 | } |
| 1190 | |
| 1191 | /// Remove a plugin installed via `/plugin install`. |
| 1192 | /// |
| 1193 | /// Refuses to touch any directory that doesn't carry the `.installed-from` |
| 1194 | /// marker — that's our cue that it's hand-placed and not ours to delete. |
| 1195 | /// Callers must require the bundle to be disabled first (the mutation |
| 1196 | /// controller does) and prune the registry state entry afterwards. |
| 1197 | pub fn uninstall(name: &str, user_plugins_dir: &Path) -> Result<()> { |
| 1198 | let target = plugin_target_path(name, user_plugins_dir)?; |
| 1199 | let Ok(target_meta) = fs::symlink_metadata(&target) else { |
| 1200 | bail!("plugin '{name}' is not installed at {}", target.display()); |
| 1201 | }; |
| 1202 | ensure_target_within_plugins_dir(&target, user_plugins_dir)?; |
| 1203 | if codewhale_util::path_identity::metadata_is_link_or_reparse(&target_meta) |
| 1204 | || !target_meta.is_dir() |
| 1205 | || !has_regular_install_marker(&target) |
| 1206 | { |
| 1207 | return Err(PluginInstallError::NotInstalledHere(name.to_string()).into()); |
| 1208 | } |
| 1209 | fs::remove_dir_all(&target) |
| 1210 | .with_context(|| format!("failed to remove {}", target.display()))?; |
| 1211 | Ok(()) |
| 1212 | } |
| 1213 | |
| 1214 | #[derive(PartialEq, Eq)] |
| 1215 | enum NormalizedSegment { |
| 1216 | Disk(u8), |
| 1217 | Unc(String, String), |
| 1218 | Device(String), |
| 1219 | Verbatim(String), |
| 1220 | Root, |
| 1221 | Normal(std::ffi::OsString), |
| 1222 | } |
| 1223 | |
| 1224 | fn normalized_segments(path: &Path) -> Option<Vec<NormalizedSegment>> { |
| 1225 | use std::path::{Component, Prefix}; |
| 1226 | |
| 1227 | let mut segments = Vec::new(); |
| 1228 | for component in path.components() { |
| 1229 | match component { |
| 1230 | Component::Prefix(prefix) => { |
| 1231 | let seg = match prefix.kind() { |
| 1232 | Prefix::Disk(drive) | Prefix::VerbatimDisk(drive) => { |
| 1233 | NormalizedSegment::Disk(drive.to_ascii_uppercase()) |
| 1234 | } |
| 1235 | Prefix::UNC(server, share) | Prefix::VerbatimUNC(server, share) => { |
| 1236 | NormalizedSegment::Unc( |
| 1237 | server.to_string_lossy().to_ascii_lowercase(), |
| 1238 | share.to_string_lossy().to_ascii_lowercase(), |
| 1239 | ) |
| 1240 | } |
| 1241 | Prefix::DeviceNS(device) => { |
| 1242 | NormalizedSegment::Device(device.to_string_lossy().to_ascii_lowercase()) |
| 1243 | } |
| 1244 | Prefix::Verbatim(rest) => { |
| 1245 | NormalizedSegment::Verbatim(rest.to_string_lossy().to_ascii_lowercase()) |
| 1246 | } |
| 1247 | }; |
| 1248 | segments.push(seg); |
| 1249 | } |
| 1250 | Component::RootDir => segments.push(NormalizedSegment::Root), |
| 1251 | Component::CurDir => {} |
| 1252 | Component::ParentDir => return None, |
| 1253 | Component::Normal(part) => { |
| 1254 | #[cfg(windows)] |
| 1255 | let normalized = |
| 1256 | std::ffi::OsString::from(part.to_string_lossy().to_ascii_lowercase()); |
| 1257 | #[cfg(not(windows))] |
| 1258 | let normalized = part.to_os_string(); |
| 1259 | segments.push(NormalizedSegment::Normal(normalized)); |
| 1260 | } |
| 1261 | } |
| 1262 | } |
| 1263 | Some(segments) |
| 1264 | } |
| 1265 | |
| 1266 | #[must_use] |
| 1267 | pub fn path_is_within(parent: &Path, child: &Path, allow_equal: bool) -> bool { |
| 1268 | let (Some(parent), Some(child)) = (normalized_segments(parent), normalized_segments(child)) |
| 1269 | else { |
| 1270 | return false; |
| 1271 | }; |
| 1272 | if child.len() < parent.len() || (!allow_equal && child.len() == parent.len()) { |
| 1273 | return false; |
| 1274 | } |
| 1275 | child[..parent.len()] == parent[..] |
| 1276 | } |
| 1277 | |
| 1278 | #[must_use] |
| 1279 | pub fn clean_dir_is_strictly_inside(folder: &Path, project: &Path) -> bool { |
| 1280 | use std::ffi::OsStr; |
| 1281 | use std::path::Component; |
| 1282 | |
| 1283 | if !folder.is_absolute() |
| 1284 | || folder |
| 1285 | .components() |
| 1286 | .any(|component| matches!(component, Component::ParentDir)) |
| 1287 | { |
| 1288 | return false; |
| 1289 | } |
| 1290 | let (Ok(canon_folder), Ok(canon_project)) = |
| 1291 | (fs::canonicalize(folder), fs::canonicalize(project)) |
| 1292 | else { |
| 1293 | return false; |
| 1294 | }; |
| 1295 | if !path_is_within(&canon_project, &canon_folder, false) { |
| 1296 | return false; |
| 1297 | } |
| 1298 | let mut cursor = Some(folder); |
| 1299 | while let Some(current) = cursor { |
| 1300 | let Ok(canon_current) = fs::canonicalize(current) else { |
| 1301 | return false; |
| 1302 | }; |
| 1303 | if !path_is_within(&canon_project, &canon_current, false) { |
| 1304 | return path_is_within(&canon_project, &canon_current, true); |
| 1305 | } |
| 1306 | let Ok(metadata) = fs::symlink_metadata(current) else { |
| 1307 | return false; |
| 1308 | }; |
| 1309 | if codewhale_util::path_identity::metadata_is_link_or_reparse(&metadata) |
| 1310 | || !metadata.file_type().is_dir() |
| 1311 | { |
| 1312 | return false; |
| 1313 | } |
| 1314 | if current.file_name() == Some(OsStr::new(".git")) { |
| 1315 | return false; |
| 1316 | } |
| 1317 | cursor = current.parent(); |
| 1318 | } |
| 1319 | false |
| 1320 | } |
| 1321 | |
| 1322 | #[must_use] |
| 1323 | pub fn installed_by_the_agent(bundle_root: &Path, project: &Path) -> bool { |
| 1324 | use std::io::Read as _; |
| 1325 | |
| 1326 | let marker_path = bundle_root.join(INSTALLED_FROM_MARKER); |
| 1327 | let Ok(metadata) = fs::symlink_metadata(&marker_path) else { |
| 1328 | return false; |
| 1329 | }; |
| 1330 | if codewhale_util::path_identity::metadata_is_link_or_reparse(&metadata) |
| 1331 | || !metadata.file_type().is_file() |
| 1332 | { |
| 1333 | return false; |
| 1334 | } |
| 1335 | let Ok(file) = codewhale_util::bundle_file::open_bundle_file(&marker_path) else { |
| 1336 | return false; |
| 1337 | }; |
| 1338 | let mut body = String::new(); |
| 1339 | if file.take(64 * 1024 + 1).read_to_string(&mut body).is_err() || body.len() > 64 * 1024 { |
| 1340 | return false; |
| 1341 | } |
| 1342 | let Ok(marker) = serde_json::from_str::<InstalledFromMarker>(&body) else { |
| 1343 | return false; |
| 1344 | }; |
| 1345 | let Ok(source) = PluginInstallSource::parse(&marker.spec) else { |
| 1346 | return false; |
| 1347 | }; |
| 1348 | match source { |
| 1349 | PluginInstallSource::LocalPath(folder) | PluginInstallSource::Dsh(folder) => { |
| 1350 | clean_dir_is_strictly_inside(&folder, project) |
| 1351 | } |
| 1352 | PluginInstallSource::Remote(_) => false, |
| 1353 | } |
| 1354 | } |
| 1355 |