| 1 | //! Plugin mutation controller (#5182). |
| 2 | //! |
| 3 | //! All plugin install / update / uninstall writes go through this module. |
| 4 | //! Discovery stays read-only: this controller is the only writer of the user |
| 5 | //! plugins root, and every request is gated by the per-domain |
| 6 | //! [`codewhale_net::network_policy::NetworkPolicy`] before any network or disk |
| 7 | //! mutation happens. Trust and enablement are *not* mutations of this module — |
| 8 | //! they remain the registry's hash-bound receipt flow (`PluginRegistry::trust` |
| 9 | //! / `enable`), which installed bits must pass through like any other bundle. |
| 10 | |
| 11 | use std::path::PathBuf; |
| 12 | |
| 13 | use anyhow::{Context, Result, bail}; |
| 14 | |
| 15 | use codewhale_net::network_policy::NetworkPolicy; |
| 16 | |
| 17 | use super::install::{self, PluginInstallOutcome, PluginInstallSource, PluginUpdateResult}; |
| 18 | use super::registry::PluginRegistry; |
| 19 | use super::types::PluginScope; |
| 20 | |
| 21 | /// A single plugin write operation. |
| 22 | #[derive(Debug, Clone)] |
| 23 | pub enum PluginMutationRequest { |
| 24 | /// Fetch (or copy) a bundle into the user plugins root. The bundle lands |
| 25 | /// disabled and untrusted; the caller should route to the trust review. |
| 26 | Install { source: PluginInstallSource }, |
| 27 | /// Install only when the staged copy matches a prior content review. |
| 28 | /// A mismatch is rejected before the destination is created. |
| 29 | InstallExact { |
| 30 | source: PluginInstallSource, |
| 31 | expected_content_hash: String, |
| 32 | }, |
| 33 | /// Install a previously prepared remote tarball only after final approval |
| 34 | /// and when the re-staged content hash still matches the previewed hash. |
| 35 | InstallRemoteExact { |
| 36 | prepared: install::PreparedRemote, |
| 37 | expected_content_hash: String, |
| 38 | }, |
| 39 | /// Refresh a previously installed bundle by name or id. A changed |
| 40 | /// bundle automatically invalidates its trust receipt at next discovery. |
| 41 | Update { selector: String }, |
| 42 | /// Delete an installed bundle and prune its persisted state entry. |
| 43 | /// Requires the bundle to be disabled first. |
| 44 | Uninstall { selector: String }, |
| 45 | } |
| 46 | |
| 47 | /// Outcome of a [`PluginMutationRequest`]. The `NeedsApproval` / |
| 48 | /// `NetworkDenied` variants carry the blocked host and are returned without |
| 49 | /// side effects so the caller can route through its own approval flow. |
| 50 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 51 | pub enum PluginMutationOutcome { |
| 52 | Installed, |
| 53 | Updated, |
| 54 | NoChange, |
| 55 | Uninstalled, |
| 56 | NeedsApproval(String), |
| 57 | NetworkDenied(String), |
| 58 | } |
| 59 | |
| 60 | /// What a mutation did, for the caller to render. |
| 61 | #[derive(Debug, Clone)] |
| 62 | pub struct PluginMutationReceipt { |
| 63 | /// Installed/updated/removed plugin name (empty when blocked by policy). |
| 64 | pub name: String, |
| 65 | /// Final bundle path (present for install/update). |
| 66 | pub path: Option<PathBuf>, |
| 67 | /// Source payload hash before installer provenance is added. |
| 68 | pub content_hash: Option<String>, |
| 69 | /// Exact complete-tree hash after installer provenance is written. |
| 70 | pub installed_content_hash: Option<String>, |
| 71 | pub outcome: PluginMutationOutcome, |
| 72 | } |
| 73 | |
| 74 | /// Inputs shared by mutation operations. |
| 75 | pub struct PluginMutationContext<'a> { |
| 76 | pub network: &'a NetworkPolicy, |
| 77 | pub max_size: u64, |
| 78 | } |
| 79 | |
| 80 | /// Execute a mutation against the user plugins root described by `registry`. |
| 81 | /// |
| 82 | /// The registry is the source of truth for the (pre-dotenv) user plugins |
| 83 | /// root, for name-collision checks across scopes, and — on uninstall — for |
| 84 | /// the disabled precondition and the state-entry prune. Callers rediscover |
| 85 | /// after a successful mutation; the in-memory registry is not updated here. |
| 86 | pub async fn execute( |
| 87 | request: PluginMutationRequest, |
| 88 | ctx: &PluginMutationContext<'_>, |
| 89 | registry: &mut PluginRegistry, |
| 90 | ) -> Result<PluginMutationReceipt> { |
| 91 | match request { |
| 92 | PluginMutationRequest::Install { source } => { |
| 93 | install_plugin(InstallKind::Source(source), None, ctx, registry).await |
| 94 | } |
| 95 | PluginMutationRequest::InstallExact { |
| 96 | source, |
| 97 | expected_content_hash, |
| 98 | } => { |
| 99 | install_plugin( |
| 100 | InstallKind::Source(source), |
| 101 | Some(expected_content_hash.as_str()), |
| 102 | ctx, |
| 103 | registry, |
| 104 | ) |
| 105 | .await |
| 106 | } |
| 107 | PluginMutationRequest::InstallRemoteExact { |
| 108 | prepared, |
| 109 | expected_content_hash, |
| 110 | } => { |
| 111 | install_plugin( |
| 112 | InstallKind::PreparedRemote(prepared), |
| 113 | Some(expected_content_hash.as_str()), |
| 114 | ctx, |
| 115 | registry, |
| 116 | ) |
| 117 | .await |
| 118 | } |
| 119 | PluginMutationRequest::Update { selector } => update_plugin(&selector, ctx, registry).await, |
| 120 | PluginMutationRequest::Uninstall { selector } => uninstall_plugin(&selector, registry), |
| 121 | } |
| 122 | } |
| 123 | |
| 124 | pub fn check_network_outcome(outcome: &PluginMutationOutcome) -> Result<()> { |
| 125 | match outcome { |
| 126 | PluginMutationOutcome::NeedsApproval(host) => { |
| 127 | bail!(install::npm_deps::network_approval_message(host, None)) |
| 128 | } |
| 129 | PluginMutationOutcome::NetworkDenied(host) => bail!("Network access denied for {host}"), |
| 130 | _ => Ok(()), |
| 131 | } |
| 132 | } |
| 133 | |
| 134 | pub async fn install_from_cli_receipt( |
| 135 | source: String, |
| 136 | config: codewhale_runtime::config::Config, |
| 137 | registry: PluginRegistry, |
| 138 | ) -> Result<PluginMutationReceipt> { |
| 139 | install_cli_receipt_inner(source, None, config, registry).await |
| 140 | } |
| 141 | |
| 142 | pub async fn install_exact_from_cli_receipt( |
| 143 | source: String, |
| 144 | expected_content_hash: String, |
| 145 | config: codewhale_runtime::config::Config, |
| 146 | registry: PluginRegistry, |
| 147 | ) -> Result<PluginMutationReceipt> { |
| 148 | install_cli_receipt_inner(source, Some(expected_content_hash), config, registry).await |
| 149 | } |
| 150 | |
| 151 | async fn install_cli_receipt_inner( |
| 152 | source: String, |
| 153 | expected_content_hash: Option<String>, |
| 154 | config: codewhale_runtime::config::Config, |
| 155 | mut registry: PluginRegistry, |
| 156 | ) -> Result<PluginMutationReceipt> { |
| 157 | let runtime = tokio::runtime::Handle::current(); |
| 158 | let policy = crate::activation::extension_host_policy_enabled(); |
| 159 | let receipt = tokio::task::spawn_blocking(move || { |
| 160 | let _scope = crate::activation::PolicyScope::propagate(policy); |
| 161 | let network = config |
| 162 | .network |
| 163 | .map(codewhale_net::network_policy::NetworkPolicy::from) |
| 164 | .unwrap_or_default(); |
| 165 | let source = PluginInstallSource::parse(&source)?; |
| 166 | let request = match expected_content_hash { |
| 167 | Some(expected_content_hash) => PluginMutationRequest::InstallExact { |
| 168 | source, |
| 169 | expected_content_hash, |
| 170 | }, |
| 171 | None => PluginMutationRequest::Install { source }, |
| 172 | }; |
| 173 | runtime.block_on(execute( |
| 174 | request, |
| 175 | &PluginMutationContext { |
| 176 | network: &network, |
| 177 | max_size: install::DEFAULT_MAX_SIZE_BYTES, |
| 178 | }, |
| 179 | &mut registry, |
| 180 | )) |
| 181 | }) |
| 182 | .await??; |
| 183 | check_network_outcome(&receipt.outcome)?; |
| 184 | Ok(receipt) |
| 185 | } |
| 186 | |
| 187 | pub async fn install_from_cli( |
| 188 | source: String, |
| 189 | config: codewhale_runtime::config::Config, |
| 190 | registry: PluginRegistry, |
| 191 | ) -> Result<()> { |
| 192 | let receipt = install_from_cli_receipt(source, config, registry).await?; |
| 193 | match receipt.outcome { |
| 194 | PluginMutationOutcome::Installed => { |
| 195 | println!("Installed {} (disabled, untrusted).", receipt.name); |
| 196 | println!( |
| 197 | "Open Codewhale, review `/plugin trust {}`, then enable it with `/plugin enable {}`. Start a new session after enabling provider declarations.", |
| 198 | receipt.name, receipt.name |
| 199 | ); |
| 200 | Ok(()) |
| 201 | } |
| 202 | _ => bail!("Unexpected plugin install outcome"), |
| 203 | } |
| 204 | } |
| 205 | |
| 206 | fn user_plugins_dir(registry: &PluginRegistry) -> Result<PathBuf> { |
| 207 | registry |
| 208 | .user_plugins_dir() |
| 209 | .map(PathBuf::from) |
| 210 | .context("plugin registry has no user plugins root; install is fail-closed") |
| 211 | } |
| 212 | |
| 213 | enum InstallKind { |
| 214 | Source(PluginInstallSource), |
| 215 | PreparedRemote(install::PreparedRemote), |
| 216 | } |
| 217 | |
| 218 | async fn install_plugin( |
| 219 | kind: InstallKind, |
| 220 | expected_content_hash: Option<&str>, |
| 221 | ctx: &PluginMutationContext<'_>, |
| 222 | registry: &mut PluginRegistry, |
| 223 | ) -> Result<PluginMutationReceipt> { |
| 224 | let plugins_dir = user_plugins_dir(registry)?; |
| 225 | // Pre-check name collisions across scopes: a builtin or workspace bundle |
| 226 | // with the same name would shadow (or be shadowed by) the install. |
| 227 | let name_conflict = |name: &str| -> Option<String> { |
| 228 | registry.get(name).map(|existing| { |
| 229 | format!( |
| 230 | "plugin name '{name}' is already used by the {} bundle at {}; \ |
| 231 | choose a different name or remove that bundle first", |
| 232 | existing.scope.as_str(), |
| 233 | existing.canonical_root.display() |
| 234 | ) |
| 235 | }) |
| 236 | }; |
| 237 | let outcome = match kind { |
| 238 | InstallKind::Source(source) => match expected_content_hash { |
| 239 | Some(expected) => { |
| 240 | install::install_with_expected_content_hash( |
| 241 | source, |
| 242 | &plugins_dir, |
| 243 | ctx.max_size, |
| 244 | ctx.network, |
| 245 | &name_conflict, |
| 246 | expected, |
| 247 | ) |
| 248 | .await? |
| 249 | } |
| 250 | None => { |
| 251 | install::install( |
| 252 | source, |
| 253 | &plugins_dir, |
| 254 | ctx.max_size, |
| 255 | ctx.network, |
| 256 | false, |
| 257 | &name_conflict, |
| 258 | ) |
| 259 | .await? |
| 260 | } |
| 261 | }, |
| 262 | InstallKind::PreparedRemote(prepared) => { |
| 263 | let expected = expected_content_hash |
| 264 | .context("prepared remote install requires an expected content hash")?; |
| 265 | install::install_prepared_remote( |
| 266 | &prepared, |
| 267 | &plugins_dir, |
| 268 | ctx.max_size, |
| 269 | ctx.network, |
| 270 | &name_conflict, |
| 271 | expected, |
| 272 | ) |
| 273 | .await? |
| 274 | } |
| 275 | }; |
| 276 | Ok(match outcome { |
| 277 | PluginInstallOutcome::Installed(installed) => PluginMutationReceipt { |
| 278 | name: installed.name, |
| 279 | path: Some(installed.path), |
| 280 | content_hash: Some(installed.content_hash), |
| 281 | installed_content_hash: Some(installed.installed_content_hash), |
| 282 | outcome: PluginMutationOutcome::Installed, |
| 283 | }, |
| 284 | PluginInstallOutcome::NeedsApproval(host) => blocked(host, true), |
| 285 | PluginInstallOutcome::NetworkDenied(host) => blocked(host, false), |
| 286 | }) |
| 287 | } |
| 288 | |
| 289 | async fn update_plugin( |
| 290 | selector: &str, |
| 291 | ctx: &PluginMutationContext<'_>, |
| 292 | registry: &mut PluginRegistry, |
| 293 | ) -> Result<PluginMutationReceipt> { |
| 294 | let plugin = registry |
| 295 | .get(selector) |
| 296 | .with_context(|| format!("Plugin bundle `{selector}` was not found"))? |
| 297 | .clone(); |
| 298 | if plugin.scope != PluginScope::User { |
| 299 | bail!( |
| 300 | "only user-scope bundles installed via /plugin install can be updated; \ |
| 301 | `{selector}` is a {} bundle", |
| 302 | plugin.scope.as_str() |
| 303 | ); |
| 304 | } |
| 305 | let plugins_dir = user_plugins_dir(registry)?; |
| 306 | let outcome = install::update(plugin.name(), &plugins_dir, ctx.max_size, ctx.network).await?; |
| 307 | Ok(match outcome { |
| 308 | PluginUpdateResult::NoChange => PluginMutationReceipt { |
| 309 | name: plugin.name().to_string(), |
| 310 | path: None, |
| 311 | content_hash: None, |
| 312 | installed_content_hash: None, |
| 313 | outcome: PluginMutationOutcome::NoChange, |
| 314 | }, |
| 315 | PluginUpdateResult::Updated(installed) => PluginMutationReceipt { |
| 316 | name: installed.name, |
| 317 | path: Some(installed.path), |
| 318 | content_hash: Some(installed.content_hash), |
| 319 | installed_content_hash: Some(installed.installed_content_hash), |
| 320 | outcome: PluginMutationOutcome::Updated, |
| 321 | }, |
| 322 | PluginUpdateResult::NeedsApproval(host) => blocked(host, true), |
| 323 | PluginUpdateResult::NetworkDenied(host) => blocked(host, false), |
| 324 | }) |
| 325 | } |
| 326 | |
| 327 | fn uninstall_plugin( |
| 328 | selector: &str, |
| 329 | registry: &mut PluginRegistry, |
| 330 | ) -> Result<PluginMutationReceipt> { |
| 331 | let plugin = registry |
| 332 | .get(selector) |
| 333 | .with_context(|| format!("Plugin bundle `{selector}` was not found"))? |
| 334 | .clone(); |
| 335 | if plugin.scope != PluginScope::User { |
| 336 | bail!( |
| 337 | "refusing to uninstall the {} bundle `{selector}`; remove it from its own root", |
| 338 | plugin.scope.as_str() |
| 339 | ); |
| 340 | } |
| 341 | if plugin.enabled { |
| 342 | bail!("plugin `{selector}` is enabled; disable it first with /plugin disable {selector}"); |
| 343 | } |
| 344 | let plugins_dir = user_plugins_dir(registry)?; |
| 345 | install::uninstall(plugin.name(), &plugins_dir)?; |
| 346 | registry |
| 347 | .prune_state_entry(selector) |
| 348 | .map_err(anyhow::Error::msg)?; |
| 349 | Ok(PluginMutationReceipt { |
| 350 | name: plugin.name().to_string(), |
| 351 | path: None, |
| 352 | content_hash: None, |
| 353 | installed_content_hash: None, |
| 354 | outcome: PluginMutationOutcome::Uninstalled, |
| 355 | }) |
| 356 | } |
| 357 | |
| 358 | fn blocked(host: String, needs_approval: bool) -> PluginMutationReceipt { |
| 359 | PluginMutationReceipt { |
| 360 | name: String::new(), |
| 361 | path: None, |
| 362 | content_hash: None, |
| 363 | installed_content_hash: None, |
| 364 | outcome: if needs_approval { |
| 365 | PluginMutationOutcome::NeedsApproval(host) |
| 366 | } else { |
| 367 | PluginMutationOutcome::NetworkDenied(host) |
| 368 | }, |
| 369 | } |
| 370 | } |
| 371 |