| 1 | //! Place a staged bundle at its final path, and the containment guards. |
| 2 | //! |
| 3 | //! [`finalize_install`] reserves a private unique backup before moving an |
| 4 | //! incumbent and writes `.installed-from` last. Failed publication restores |
| 5 | //! only into an unoccupied destination. After publication, an error retains |
| 6 | //! both the incumbent backup and the current path: without serialization we |
| 7 | //! cannot prove that path still names this operation's publication, so it is |
| 8 | //! never recursively deleted or overwritten as rollback. |
| 9 | //! [`ensure_target_within_plugins_dir`] mirrors discovery's fail-closed rule |
| 10 | //! that a bundle must resolve to a direct child of the plugins root. |
| 11 | //! |
| 12 | //! This is not a serialized or crash-atomic bundle swap. A retained recovery |
| 13 | //! path is not proof that the old bundle was restored or remains active. |
| 14 | |
| 15 | use std::fs; |
| 16 | use std::path::{Path, PathBuf}; |
| 17 | |
| 18 | use anyhow::{Context, Result, bail}; |
| 19 | |
| 20 | use codewhale_skill_install::install::{ |
| 21 | self as skill_install, INSTALLED_FROM_MARKER, validate_skill_name_segment, |
| 22 | }; |
| 23 | |
| 24 | use super::stage::StagedPlugin; |
| 25 | use super::{InstalledPlugin, PluginInstallError, PluginInstallOutcome}; |
| 26 | |
| 27 | pub(super) fn finalize_install( |
| 28 | staged: StagedPlugin, |
| 29 | spec: &str, |
| 30 | url: Option<&str>, |
| 31 | source_checksum: &str, |
| 32 | user_plugins_dir: &Path, |
| 33 | update: bool, |
| 34 | ) -> Result<PluginInstallOutcome> { |
| 35 | let final_path = user_plugins_dir.join(&staged.name); |
| 36 | let mut backup_container: Option<PathBuf> = None; |
| 37 | if final_path.exists() { |
| 38 | if !update { |
| 39 | let has_marker = final_path.join(INSTALLED_FROM_MARKER).exists(); |
| 40 | let _ = fs::remove_dir_all(&staged.staged_path); |
| 41 | if has_marker { |
| 42 | return Err(PluginInstallError::AlreadyInstalled(staged.name).into()); |
| 43 | } |
| 44 | return Err(PluginInstallError::NotInstalledHere(staged.name).into()); |
| 45 | } |
| 46 | if !final_path.join(INSTALLED_FROM_MARKER).exists() { |
| 47 | let _ = fs::remove_dir_all(&staged.staged_path); |
| 48 | return Err(PluginInstallError::NotInstalledHere(staged.name).into()); |
| 49 | } |
| 50 | let mut builder = tempfile::Builder::new(); |
| 51 | builder.prefix(".plugin-backup-").rand_bytes(16); |
| 52 | #[cfg(unix)] |
| 53 | { |
| 54 | use std::os::unix::fs::PermissionsExt as _; |
| 55 | builder.permissions(fs::Permissions::from_mode(0o700)); |
| 56 | } |
| 57 | let reserved = builder |
| 58 | .tempdir_in(user_plugins_dir) |
| 59 | .context("failed to reserve a private plugin backup container")?; |
| 60 | crate::registry::ensure_private_plugin_state_directory(reserved.path()) |
| 61 | .map_err(anyhow::Error::msg)?; |
| 62 | // Persist before moving any user data: TempDir cleanup must never |
| 63 | // delete the incumbent during an error return or unwind. |
| 64 | let container = reserved.keep(); |
| 65 | let backup = container.join("bundle"); |
| 66 | if let Err(error) = crate::builtin::publish_snapshot(&final_path, &backup) { |
| 67 | if let Err(cleanup) = fs::remove_dir(&container) { |
| 68 | tracing::warn!(path = %container.display(), %cleanup, "empty plugin backup container could not be removed"); |
| 69 | } |
| 70 | return Err(error).with_context(|| { |
| 71 | format!( |
| 72 | "failed to backup existing plugin at {}", |
| 73 | final_path.display() |
| 74 | ) |
| 75 | }); |
| 76 | } |
| 77 | backup_container = Some(container); |
| 78 | } |
| 79 | if let Err(error) = crate::builtin::publish_snapshot(&staged.staged_path, &final_path) { |
| 80 | if let Some(container) = backup_container.as_deref() { |
| 81 | return Err(restore_backup(container, &final_path, error.into())); |
| 82 | } |
| 83 | return Err(error) |
| 84 | .context("failed to install staged plugin; existing destination preserved"); |
| 85 | } |
| 86 | |
| 87 | // Discovery fail-closed rule: the installed bundle must canonicalize to a |
| 88 | // direct child of the user plugins root. |
| 89 | if let Err(error) = ensure_target_within_plugins_dir(&final_path, user_plugins_dir) { |
| 90 | return Err(retained_publication_error( |
| 91 | error, |
| 92 | &final_path, |
| 93 | backup_container.as_deref(), |
| 94 | )); |
| 95 | } |
| 96 | |
| 97 | // Write the marker last so a partial install never leaves a stale |
| 98 | // `.installed-from` on disk. |
| 99 | let install_nonce = uuid::Uuid::new_v4().simple().to_string(); |
| 100 | if let Err(error) = skill_install::write_installed_from_v2_with_nonce( |
| 101 | &final_path, |
| 102 | spec, |
| 103 | url, |
| 104 | source_checksum, |
| 105 | &staged.content_hash, |
| 106 | &staged.name, |
| 107 | &install_nonce, |
| 108 | ) { |
| 109 | return Err(retained_publication_error( |
| 110 | error, |
| 111 | &final_path, |
| 112 | backup_container.as_deref(), |
| 113 | )); |
| 114 | } |
| 115 | |
| 116 | let installed_content_hash = match crate::agent_plugin::resolve_manifest_path(&final_path) |
| 117 | .ok_or_else(|| anyhow::anyhow!("installed plugin has no supported manifest")) |
| 118 | .and_then(|manifest_path| { |
| 119 | crate::manifest::PluginManifest::validate_from_path(&manifest_path) |
| 120 | .map(|validated| validated.content_hash) |
| 121 | .map_err(anyhow::Error::msg) |
| 122 | }) { |
| 123 | Ok(hash) => hash, |
| 124 | Err(error) => { |
| 125 | return Err(retained_publication_error( |
| 126 | error.context("installed plugin failed post-copy validation"), |
| 127 | &final_path, |
| 128 | backup_container.as_deref(), |
| 129 | )); |
| 130 | } |
| 131 | }; |
| 132 | if let Some(container) = backup_container |
| 133 | && let Err(error) = fs::remove_dir_all(&container) |
| 134 | { |
| 135 | // The new bundle is already installed and validated. Cleanup failure |
| 136 | // does not undo it; retain the exact old-copy path in the diagnostic. |
| 137 | tracing::warn!(path = %container.display(), %error, "plugin installed but prior backup cleanup failed; retained backup requires recovery cleanup"); |
| 138 | } |
| 139 | |
| 140 | Ok(PluginInstallOutcome::Installed(InstalledPlugin { |
| 141 | name: staged.name, |
| 142 | path: final_path, |
| 143 | content_hash: staged.content_hash, |
| 144 | installed_content_hash, |
| 145 | source_checksum: source_checksum.to_string(), |
| 146 | })) |
| 147 | } |
| 148 | |
| 149 | /// A failed no-replace publication did not install our staged tree. Restore |
| 150 | /// with the same exclusive primitive, so an intervening creator is preserved. |
| 151 | pub(super) fn restore_backup( |
| 152 | container: &Path, |
| 153 | final_path: &Path, |
| 154 | error: anyhow::Error, |
| 155 | ) -> anyhow::Error { |
| 156 | let backup = container.join("bundle"); |
| 157 | match crate::builtin::publish_snapshot(&backup, final_path) { |
| 158 | Ok(()) => { |
| 159 | if let Err(cleanup) = fs::remove_dir(container) { |
| 160 | tracing::warn!(path = %container.display(), %cleanup, "restored plugin but empty recovery container could not be removed"); |
| 161 | } |
| 162 | error.context(format!( |
| 163 | "failed to install staged plugin; previous plugin restored at {}", |
| 164 | final_path.display() |
| 165 | )) |
| 166 | } |
| 167 | Err(restore) => error.context(format!( |
| 168 | "failed to install staged plugin and automatic restoration failed: {restore}; \ |
| 169 | previous plugin retained at {}; current destination {} was not replaced; recovery required", |
| 170 | backup.display(), |
| 171 | final_path.display() |
| 172 | )), |
| 173 | } |
| 174 | } |
| 175 | |
| 176 | fn retained_publication_error( |
| 177 | error: anyhow::Error, |
| 178 | final_path: &Path, |
| 179 | backup_container: Option<&Path>, |
| 180 | ) -> anyhow::Error { |
| 181 | let previous = backup_container.map_or_else( |
| 182 | || "no previous plugin backup exists".to_string(), |
| 183 | |container| { |
| 184 | format!( |
| 185 | "previous plugin retained at {}", |
| 186 | container.join("bundle").display() |
| 187 | ) |
| 188 | }, |
| 189 | ); |
| 190 | error.context(format!( |
| 191 | "plugin publication failed validation; {previous}; current destination {} retained; \ |
| 192 | automatic restoration refused because its publication identity is not pinned; recovery required", |
| 193 | final_path.display() |
| 194 | )) |
| 195 | } |
| 196 | |
| 197 | // ───────────────────────────────────────────────────────────────────────────── |
| 198 | // Path guards |
| 199 | // ───────────────────────────────────────────────────────────────────────────── |
| 200 | |
| 201 | pub(super) fn plugin_target_path(name: &str, user_plugins_dir: &Path) -> Result<PathBuf> { |
| 202 | let name = validate_skill_name_segment(name) |
| 203 | .map_err(|error| anyhow::anyhow!("plugin name is not a safe directory name: {error:#}"))?; |
| 204 | Ok(user_plugins_dir.join(name)) |
| 205 | } |
| 206 | |
| 207 | /// The resolved bundle must be a direct child of the resolved plugins root, |
| 208 | /// matching discovery's fail-closed containment rule. |
| 209 | pub(super) fn ensure_target_within_plugins_dir( |
| 210 | target: &Path, |
| 211 | user_plugins_dir: &Path, |
| 212 | ) -> Result<()> { |
| 213 | let root = fs::canonicalize(user_plugins_dir).with_context(|| { |
| 214 | format!( |
| 215 | "failed to resolve plugins directory {}", |
| 216 | user_plugins_dir.display() |
| 217 | ) |
| 218 | })?; |
| 219 | let target = fs::canonicalize(target) |
| 220 | .with_context(|| format!("failed to resolve {}", target.display()))?; |
| 221 | if target.parent() != Some(root.as_path()) { |
| 222 | bail!( |
| 223 | "plugin path {} escapes plugins directory {}", |
| 224 | target.display(), |
| 225 | root.display() |
| 226 | ); |
| 227 | } |
| 228 | Ok(()) |
| 229 | } |
| 230 |