| 1 | //! Automatic updates for release-binary installs: the mode setting, the |
| 2 | //! organization policy that can override it, and the on-disk state under |
| 3 | //! `<CODEWHALE_HOME>/updates/`. |
| 4 | //! |
| 5 | //! - `staged/` holds one downloaded, checksum-verified release binary and |
| 6 | //! `staged.json`. It is applied at the start of the next `codewhale` process, |
| 7 | //! never while a session runs. An unsigned stage applies only after the |
| 8 | //! person says yes once; a signed one applies by itself. |
| 9 | //! - `previous/` holds the binary that the last update or rollback replaced, so |
| 10 | //! `codewhale update --rollback` can swap it back. |
| 11 | //! - `state.json` remembers a rolled-back version so it is not staged again, |
| 12 | //! and the last staging attempt so offline or rate-limited machines retry at |
| 13 | //! the check interval, not on every launch. |
| 14 | //! |
| 15 | //! Known limits: the user's `[update] mode` is read when the TUI stages; a |
| 16 | //! change to it before the next start does not cancel an already staged |
| 17 | //! update (policy and environment opt-outs do). Package-managed and app-bundled |
| 18 | //! copies never stage. |
| 19 | |
| 20 | use std::fs; |
| 21 | use std::path::{Path, PathBuf}; |
| 22 | |
| 23 | use anyhow::{Context, Result}; |
| 24 | use serde::{Deserialize, Serialize}; |
| 25 | |
| 26 | pub const UPDATES_DIR: &str = "updates"; |
| 27 | pub const MODE_ENV: &str = "CODEWHALE_UPDATE_MODE"; |
| 28 | pub const POLICY_PATH_ENV: &str = "CODEWHALE_UPDATE_POLICY_PATH"; |
| 29 | |
| 30 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 31 | pub enum UpdateMode { |
| 32 | Auto, |
| 33 | Notify, |
| 34 | Off, |
| 35 | } |
| 36 | |
| 37 | impl UpdateMode { |
| 38 | #[must_use] |
| 39 | pub fn parse(raw: &str) -> Option<Self> { |
| 40 | match raw.trim().to_ascii_lowercase().as_str() { |
| 41 | "auto" | "on" | "true" => Some(Self::Auto), |
| 42 | "notify" | "check" | "check-only" => Some(Self::Notify), |
| 43 | "off" | "false" | "never" | "disabled" => Some(Self::Off), |
| 44 | _ => None, |
| 45 | } |
| 46 | } |
| 47 | |
| 48 | #[must_use] |
| 49 | pub fn label(self) -> &'static str { |
| 50 | match self { |
| 51 | Self::Auto => "auto", |
| 52 | Self::Notify => "notify", |
| 53 | Self::Off => "off", |
| 54 | } |
| 55 | } |
| 56 | } |
| 57 | |
| 58 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 59 | pub struct ResolvedMode { |
| 60 | pub mode: UpdateMode, |
| 61 | pub source: String, |
| 62 | } |
| 63 | |
| 64 | impl ResolvedMode { |
| 65 | #[must_use] |
| 66 | pub fn describe(&self) -> String { |
| 67 | format!("{} ({})", self.mode.label(), self.source) |
| 68 | } |
| 69 | } |
| 70 | |
| 71 | #[derive(Debug, Deserialize)] |
| 72 | struct PolicyFile { |
| 73 | #[serde(default)] |
| 74 | update: PolicyUpdate, |
| 75 | } |
| 76 | |
| 77 | #[derive(Debug, Default, Deserialize)] |
| 78 | struct PolicyUpdate { |
| 79 | mode: Option<String>, |
| 80 | } |
| 81 | |
| 82 | fn policy_paths() -> Vec<PathBuf> { |
| 83 | if cfg!(debug_assertions) |
| 84 | && let Some(path) = std::env::var_os(POLICY_PATH_ENV).filter(|p| !p.is_empty()) |
| 85 | { |
| 86 | return vec![PathBuf::from(path)]; |
| 87 | } |
| 88 | if cfg!(windows) { |
| 89 | std::env::var_os("ProgramData") |
| 90 | .map(|root| vec![PathBuf::from(root).join("Codewhale").join("policy.toml")]) |
| 91 | .unwrap_or_default() |
| 92 | } else if cfg!(target_os = "macos") { |
| 93 | vec![ |
| 94 | PathBuf::from("/Library/Application Support/Codewhale/policy.toml"), |
| 95 | PathBuf::from("/etc/codewhale/policy.toml"), |
| 96 | ] |
| 97 | } else { |
| 98 | vec![PathBuf::from("/etc/codewhale/policy.toml")] |
| 99 | } |
| 100 | } |
| 101 | |
| 102 | #[cfg(unix)] |
| 103 | fn trusted_policy_owner(meta: &fs::Metadata) -> bool { |
| 104 | use std::os::unix::fs::MetadataExt; |
| 105 | cfg!(debug_assertions) && std::env::var_os(POLICY_PATH_ENV).is_some() |
| 106 | || (meta.uid() == 0 && meta.mode() & 0o022 == 0) |
| 107 | } |
| 108 | |
| 109 | #[cfg(not(unix))] |
| 110 | fn trusted_policy_owner(_meta: &fs::Metadata) -> bool { |
| 111 | true |
| 112 | } |
| 113 | |
| 114 | #[must_use] |
| 115 | pub fn managed_policy_mode() -> Option<(UpdateMode, PathBuf)> { |
| 116 | for path in policy_paths() { |
| 117 | let Ok(meta) = fs::metadata(&path) else { |
| 118 | continue; |
| 119 | }; |
| 120 | if !meta.is_file() || !trusted_policy_owner(&meta) || meta.len() > 64 * 1024 { |
| 121 | continue; |
| 122 | } |
| 123 | let mode = fs::read_to_string(&path) |
| 124 | .ok() |
| 125 | .and_then(|text| toml::from_str::<PolicyFile>(&text).ok()) |
| 126 | .map(|policy| policy.update.mode.as_deref().map(UpdateMode::parse)); |
| 127 | match mode { |
| 128 | Some(None) => continue, |
| 129 | Some(Some(Some(mode))) => return Some((mode, path)), |
| 130 | Some(Some(None)) | None => return Some((UpdateMode::Off, path)), |
| 131 | } |
| 132 | } |
| 133 | None |
| 134 | } |
| 135 | |
| 136 | #[must_use] |
| 137 | pub fn resolve_mode(config_mode: Option<&str>, check_for_updates: bool) -> ResolvedMode { |
| 138 | if let Some((mode, path)) = managed_policy_mode() { |
| 139 | return ResolvedMode { |
| 140 | mode, |
| 141 | source: format!("set by your organization in {}", path.display()), |
| 142 | }; |
| 143 | } |
| 144 | if let Some(mode) = std::env::var(MODE_ENV) |
| 145 | .ok() |
| 146 | .as_deref() |
| 147 | .and_then(UpdateMode::parse) |
| 148 | { |
| 149 | return ResolvedMode { |
| 150 | mode, |
| 151 | source: MODE_ENV.to_string(), |
| 152 | }; |
| 153 | } |
| 154 | if let Some(reason) = crate::suppression_reason() { |
| 155 | return ResolvedMode { |
| 156 | mode: UpdateMode::Off, |
| 157 | source: reason.variable().to_string(), |
| 158 | }; |
| 159 | } |
| 160 | if !check_for_updates { |
| 161 | return ResolvedMode { |
| 162 | mode: UpdateMode::Off, |
| 163 | source: "update.check_for_updates = false".to_string(), |
| 164 | }; |
| 165 | } |
| 166 | if let Some(mode) = config_mode.and_then(UpdateMode::parse) { |
| 167 | return ResolvedMode { |
| 168 | mode, |
| 169 | source: "update.mode".to_string(), |
| 170 | }; |
| 171 | } |
| 172 | ResolvedMode { |
| 173 | mode: UpdateMode::Auto, |
| 174 | source: "default".to_string(), |
| 175 | } |
| 176 | } |
| 177 | |
| 178 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 179 | pub struct StagedUpdate { |
| 180 | pub version: String, |
| 181 | pub sha256: String, |
| 182 | pub signed: bool, |
| 183 | pub source: String, |
| 184 | pub target_dir: PathBuf, |
| 185 | #[serde(default)] |
| 186 | pub declined: bool, |
| 187 | #[serde(default)] |
| 188 | pub staged_at_unix: u64, |
| 189 | } |
| 190 | |
| 191 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 192 | pub struct PreviousBinary { |
| 193 | pub version: String, |
| 194 | pub sha256: String, |
| 195 | } |
| 196 | |
| 197 | #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] |
| 198 | pub struct UpdateState { |
| 199 | #[serde(default)] |
| 200 | pub skip_version: Option<String>, |
| 201 | #[serde(default)] |
| 202 | pub last_stage_attempt_unix: u64, |
| 203 | #[serde(default)] |
| 204 | pub last_stage_version: Option<String>, |
| 205 | /// Why the last background stage or start-up apply failed, kept until one |
| 206 | /// succeeds so `doctor` and the update notice can show it. |
| 207 | #[serde(default)] |
| 208 | pub last_failure: Option<String>, |
| 209 | } |
| 210 | |
| 211 | /// Park (or with `None`, clear) the reason the last automatic update failed. |
| 212 | pub fn record_failure(home: &Path, reason: Option<String>) { |
| 213 | let mut state = load_state(home); |
| 214 | if state.last_failure != reason { |
| 215 | state.last_failure = reason; |
| 216 | let _ = store_state(home, &state); |
| 217 | } |
| 218 | } |
| 219 | |
| 220 | #[must_use] |
| 221 | pub fn updates_dir(home: &Path) -> PathBuf { |
| 222 | home.join(UPDATES_DIR) |
| 223 | } |
| 224 | |
| 225 | #[must_use] |
| 226 | pub fn staged_dir(home: &Path) -> PathBuf { |
| 227 | updates_dir(home).join("staged") |
| 228 | } |
| 229 | |
| 230 | #[must_use] |
| 231 | pub fn previous_dir(home: &Path) -> PathBuf { |
| 232 | updates_dir(home).join("previous") |
| 233 | } |
| 234 | |
| 235 | #[must_use] |
| 236 | pub fn binary_name() -> String { |
| 237 | format!("codewhale{}", std::env::consts::EXE_SUFFIX) |
| 238 | } |
| 239 | |
| 240 | fn load_json<T: for<'de> Deserialize<'de>>(path: &Path) -> Option<T> { |
| 241 | let meta = fs::symlink_metadata(path).ok()?; |
| 242 | if !meta.is_file() || meta.len() > 64 * 1024 { |
| 243 | return None; |
| 244 | } |
| 245 | serde_json::from_slice(&fs::read(path).ok()?).ok() |
| 246 | } |
| 247 | |
| 248 | pub fn store_json<T: Serialize>(path: &Path, value: &T) -> Result<()> { |
| 249 | let dir = path.parent().context("state path has no parent")?; |
| 250 | let name = path |
| 251 | .file_name() |
| 252 | .and_then(|name| name.to_str()) |
| 253 | .context("state path has no valid file name")?; |
| 254 | let bytes = serde_json::to_vec_pretty(value)?; |
| 255 | crate::installs::write_file_atomically(dir, name, &bytes, false) |
| 256 | } |
| 257 | |
| 258 | #[must_use] |
| 259 | pub fn load_staged(home: &Path) -> Option<StagedUpdate> { |
| 260 | load_json(&staged_dir(home).join("staged.json")) |
| 261 | } |
| 262 | |
| 263 | pub fn store_staged(home: &Path, staged: &StagedUpdate) -> Result<()> { |
| 264 | store_json(&staged_dir(home).join("staged.json"), staged) |
| 265 | } |
| 266 | |
| 267 | pub fn discard_staged(home: &Path) { |
| 268 | let _ = fs::remove_dir_all(staged_dir(home)); |
| 269 | } |
| 270 | |
| 271 | #[must_use] |
| 272 | pub fn load_previous(home: &Path) -> Option<PreviousBinary> { |
| 273 | load_json(&previous_dir(home).join("previous.json")) |
| 274 | } |
| 275 | |
| 276 | /// Why `codewhale update --rollback` would refuse to go from `current` back |
| 277 | /// to `previous`, or `None` when it would roll back. Workspace state migrated |
| 278 | /// by v0.10.3 cannot be verified against earlier releases. |
| 279 | #[must_use] |
| 280 | pub fn rollback_blocker(previous: &str, current: &str) -> Option<String> { |
| 281 | let (Ok(previous_version), Ok(current_version)) = ( |
| 282 | crate::parse_release_version(previous), |
| 283 | crate::parse_release_version(current), |
| 284 | ) else { |
| 285 | return Some(format!( |
| 286 | "cannot compare v{previous} with v{current}, so rollback is disabled" |
| 287 | )); |
| 288 | }; |
| 289 | let triple = |v: &semver::Version| (v.major, v.minor, v.patch); |
| 290 | (triple(¤t_version) >= (0, 10, 3) && triple(&previous_version) <= (0, 10, 3)).then(|| { |
| 291 | format!( |
| 292 | "rollback to v{previous} is disabled because its compatibility with migrated workspace state cannot be verified" |
| 293 | ) |
| 294 | }) |
| 295 | } |
| 296 | |
| 297 | #[must_use] |
| 298 | pub fn load_state(home: &Path) -> UpdateState { |
| 299 | load_json(&updates_dir(home).join("state.json")).unwrap_or_default() |
| 300 | } |
| 301 | |
| 302 | pub fn store_state(home: &Path, state: &UpdateState) -> Result<()> { |
| 303 | store_json(&updates_dir(home).join("state.json"), state) |
| 304 | } |
| 305 | |
| 306 | #[must_use] |
| 307 | pub fn changelog_url_for_locale(site_locale: &str, version: Option<&str>) -> String { |
| 308 | match version |
| 309 | .map(|value| value.trim().trim_start_matches('v')) |
| 310 | .filter(|value| !value.is_empty()) |
| 311 | { |
| 312 | Some(version) => format!("https://codewhale.net/{site_locale}/changelog/{version}"), |
| 313 | None => format!("https://codewhale.net/{site_locale}/changelog"), |
| 314 | } |
| 315 | } |
| 316 | |
| 317 | #[must_use] |
| 318 | pub fn changelog_url(version: &str) -> String { |
| 319 | changelog_url_for_locale("en", Some(version)) |
| 320 | } |
| 321 |