Skip to content
Merged
48 changes: 48 additions & 0 deletions clients/openframe-client/src/platform/uninstall.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use crate::services::{
AgentConfigurationService, DeregistrationService, InitialConfigurationService,
InstalledToolsService, ToolCommandParamsResolver, ToolKillService, ToolUninstallService,
UpdateCleanupService,
};

const SERVICE_NAME: &str = "client";
Expand All @@ -16,6 +17,43 @@
/// CLI subcommand the detached process runs to remove the client.
const UNINSTALL_SUBCOMMAND: &str = "uninstall";

/// Removes the copies the update flow leaves next to the binary: `<exe>.lkg`,
/// `<exe>.prev`, `<exe>.old`, `<exe>.bad`, `<exe>.bak`, `<exe>.backup.<ts>`.
/// Matched by prefix on purpose: every sibling written next to the binary is
/// an update artefact, and an enumerated list would leave the next suffix
/// behind on uninstall again.
#[cfg(any(target_os = "windows", target_os = "macos"))]
fn remove_binary_siblings(install_path: &Path) {
let Some(dir) = install_path.parent() else {
return;
};
let Some(exe_name) = install_path
.file_name()
.map(|n| n.to_string_lossy().to_string())
else {
return;
};
let prefix = format!("{exe_name}.");
let Ok(entries) = std::fs::read_dir(dir) else {
return;
};
for entry in entries.flatten() {
if !entry.file_name().to_string_lossy().starts_with(&prefix) {
continue;
}
let path = entry.path();
match std::fs::remove_file(&path) {
Ok(()) => info!("Removed update leftover: {}", path.display()),
Err(e) => warn!("Failed to remove update leftover {}: {}", path.display(), e),
}
}

Check warning on line 49 in clients/openframe-client/src/platform/uninstall.rs

View workflow job for this annotation

GitHub Actions / Flamingo Code Review

remove_binary_siblings uses a bare prefix match that also deletes unrelated files sharing the binary name as a prefix

remove_binary_siblings uses a bare prefix match that also deletes unrelated files sharing the binary name as a prefix The doc comment says the function matches update-artifact suffixes like `.lkg`, `.prev`, `.old`, `.bad`, `.bak`, `.backup.<ts>`, but the implementation only checks `starts_with(&prefix)` where `prefix = format!("{exe_name}.")`. This means ANY file in the same directory whose name begins with `<exe_name>.` gets deleted, not just known update-artifact suffixes — e.g. a hypothetical `openframe-client.exe.config.json` or `openframe-client.exe.log` sitting next to the binary would also be silently removed. The test suite only exercises the specific suffixes documented, so this over-broad deletion is not caught. Since this runs during uninstall (a destructive, one-way operation), consider tightening the match to the known suffix set (`.lkg`, `.lkg.tmp`, `.prev`, `.old`, `.bad`, `.bak`, or `.backup.<digits>`), or clearly document that ALL dot-suffixed siblings are considered update artifacts and must never be used for other purposes.
Comment thread
danylo-babenko-flamingo marked this conversation as resolved.
Resolved
}

#[cfg(any(target_os = "windows", target_os = "macos"))]
fn remove_update_temp_files(install_path: &Path) {
UpdateCleanupService::for_binary(install_path.to_path_buf()).sweep_temp_leftovers(None);
}

/// Spawn a detached `openframe-client uninstall` that survives this service being stopped.
/// Self-uninstall stops the `com.openframe.client` service (our own process), so it must run
/// out-of-process. macOS + Windows only — Linux client self-uninstall is unsupported.
Expand Down Expand Up @@ -416,6 +454,9 @@
deregistration_service.retry_if_unreported().await;
}

remove_binary_siblings(install_path);
remove_update_temp_files(install_path);

// Launch cleanup script to remove binary after process exit
if install_path.exists() {
info!("Launching binary cleanup script...");
Expand Down Expand Up @@ -531,6 +572,9 @@
}
}

remove_binary_siblings(install_path);
remove_update_temp_files(install_path);

// Final chance to report the uninstall now that the wipe is done.
if let Some(deregistration_service) = &deregistration_service {
deregistration_service.retry_if_unreported().await;
Expand All @@ -543,3 +587,7 @@

Ok(())
}

#[cfg(all(test, any(target_os = "windows", target_os = "macos")))]
#[path = "uninstall_tests.rs"]
mod tests;
76 changes: 76 additions & 0 deletions clients/openframe-client/src/platform/uninstall_tests.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
use super::remove_binary_siblings;
use std::fs;
use std::path::Path;

fn touch(dir: &Path, name: &str) {
fs::write(dir.join(name), b"x").unwrap();
}

fn remaining(dir: &Path) -> Vec<String> {
let mut names: Vec<String> = fs::read_dir(dir)
.unwrap()
.map(|e| e.unwrap().file_name().to_string_lossy().to_string())
.collect();
names.sort();
names
}

#[test]
fn removes_update_leftovers_next_to_windows_binary() {
let dir = tempfile::tempdir().unwrap();
for name in [
"openframe-client.exe",
"openframe-client.exe.lkg",
"openframe-client.exe.lkg.tmp",
"openframe-client.exe.prev",
"openframe-client.exe.old",
"openframe-client.exe.bak",
"openframe-client.exe.bad",
"openframe-client.exe.backup.1700000000",
"openframe-client-updater.exe",
"openframe-client-updater.exe.lkg",
"openframe.cmd",
] {
touch(dir.path(), name);
}

remove_binary_siblings(&dir.path().join("openframe-client.exe"));

assert_eq!(
remaining(dir.path()),
vec![
"openframe-client-updater.exe",
"openframe-client-updater.exe.lkg",
"openframe-client.exe",
"openframe.cmd",
]
);
}

#[test]
fn removes_update_leftovers_next_to_unix_binary() {
let dir = tempfile::tempdir().unwrap();
for name in [
"openframe-client",
"openframe-client.lkg",
"openframe-client.prev",
"openframe-client.backup.1700000000",
"openframe-client-updater",
"openframe",
] {
touch(dir.path(), name);
}

remove_binary_siblings(&dir.path().join("openframe-client"));

assert_eq!(
remaining(dir.path()),
vec!["openframe", "openframe-client", "openframe-client-updater"]
);
}

#[test]
fn missing_directory_is_ignored() {
let dir = tempfile::tempdir().unwrap();
remove_binary_siblings(&dir.path().join("missing").join("openframe-client"));
}
133 changes: 80 additions & 53 deletions clients/openframe-client/src/services/update_cleanup_service.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
use anyhow::{Context, Result};
use std::fs;
use std::path::PathBuf;
use std::path::{Path, PathBuf};
use std::time::Duration;
use tracing::{info, warn};

use crate::config::update_config::TEMP_LEFTOVER_MIN_AGE_SECS;

#[derive(Clone)]
pub struct UpdateCleanupService {
exe_path: PathBuf,
Expand All @@ -11,108 +14,132 @@ pub struct UpdateCleanupService {
impl UpdateCleanupService {
pub fn new() -> Result<Self> {
let exe_path = std::env::current_exe().context("Failed to get current executable path")?;
Ok(Self::for_binary(exe_path))
}

Ok(Self { exe_path })
/// For an uninstall started from a copy that is not the installed binary.
pub fn for_binary(exe_path: PathBuf) -> Self {
Self { exe_path }
}

/// Routine sweep after an update: old backups next to the binary and temp
/// leftovers older than TEMP_LEFTOVER_MIN_AGE_SECS.
pub async fn cleanup_all(&self) {
let mut cleaned = 0;

match self.cleanup_all_old_backups().await {
match self.cleanup_all_old_backups() {
Ok(count) => cleaned += count,
Err(e) => warn!("Failed to cleanup old backups: {:#}", e),
}

match self.cleanup_temp_update_leftovers().await {
Ok(count) => cleaned += count,
Err(e) => warn!("Failed to cleanup temp update leftovers: {:#}", e),
}
cleaned += self.sweep_temp_leftovers(Some(Duration::from_secs(TEMP_LEFTOVER_MIN_AGE_SECS)));

if cleaned > 0 {
info!("Cleanup: removed {} old files", cleaned);
}
}

async fn cleanup_all_old_backups(&self) -> Result<usize> {
/// The pre-swap copy is only needed until the new binary has verified its
/// boot; after promotion nothing reads it.
pub fn remove_pre_swap_copy(&self) {
let mut prev = self.exe_path.clone().into_os_string();
prev.push(".prev");
let prev = PathBuf::from(prev);
if !prev.exists() {
return;
}
match fs::remove_file(&prev) {
Ok(()) => info!("Removed pre-swap copy: {}", prev.display()),
Err(e) => warn!("Failed to remove pre-swap copy {}: {}", prev.display(), e),
}
}

fn cleanup_all_old_backups(&self) -> Result<usize> {
let exe_dir = self
.exe_path
.parent()
.context("Failed to get executable directory")?;

let exe_name = self
.exe_path
.file_name()
.context("Failed to get executable name")?
.to_string_lossy();

let backup_pattern = format!("{}.backup.", exe_name);

let mut cleaned = 0;
if let Ok(entries) = fs::read_dir(exe_dir) {
for entry in entries.filter_map(|e| e.ok()) {
let file_name = entry.file_name().to_string_lossy().to_string();
if file_name.starts_with(&backup_pattern) {
match fs::remove_file(entry.path()) {
Ok(_) => {
info!("Removed old backup: {}", entry.path().display());
cleaned += 1;
}
Err(e) => {
warn!("Failed to remove backup {}: {}", entry.path().display(), e);
}
}
for path in Self::matching_entries(exe_dir, |name| name.starts_with(&backup_pattern)) {
match fs::remove_file(&path) {
Ok(()) => {
info!("Removed old backup: {}", path.display());
cleaned += 1;
}
Err(e) => warn!("Failed to remove backup {}: {}", path.display(), e),
}
}

Ok(cleaned)
}

async fn cleanup_temp_update_leftovers(&self) -> Result<usize> {
/// Temp-dir leftovers of the script-based updater (`openframe-update-*`
/// staging dirs, `openframe-updater-*.ps1|.sh`). `min_age` = `None` removes
/// them regardless of age (uninstall); otherwise anything younger is kept
/// because an update may still be using it.
pub fn sweep_temp_leftovers(&self, min_age: Option<Duration>) -> usize {
let temp_dir = std::env::temp_dir();

let mut cleaned = 0;
if let Ok(entries) = fs::read_dir(&temp_dir) {
for entry in entries.filter_map(|e| e.ok()) {
let name = entry.file_name().to_string_lossy().to_string();
let is_update_artifact = name.starts_with("openframe-update-")
|| (name.starts_with("openframe-updater-")
&& (name.ends_with(".ps1") || name.ends_with(".sh")));
if !is_update_artifact {
continue;
}
let Ok(entries) = fs::read_dir(&temp_dir) else {
return 0;
};
for entry in entries.flatten() {
let name = entry.file_name().to_string_lossy().to_string();
let is_update_artifact = name.starts_with("openframe-update-")
|| (name.starts_with("openframe-updater-")
&& (name.ends_with(".ps1") || name.ends_with(".sh")));
if !is_update_artifact {
continue;
}

if let Some(min_age) = min_age {
let too_fresh = entry
.metadata()
.ok()
.and_then(|m| m.modified().ok())
.and_then(|t| t.elapsed().ok())
.map(|age| {
age.as_secs() < crate::config::update_config::TEMP_LEFTOVER_MIN_AGE_SECS
})
.map(|age| age < min_age)
.unwrap_or(true);
if too_fresh {
continue;
}
}

let path = entry.path();
let result = if path.is_dir() {
fs::remove_dir_all(&path)
} else {
fs::remove_file(&path)
};
match result {
Ok(_) => {
info!("Removed update leftover: {}", path.display());
cleaned += 1;
}
Err(e) => {
warn!("Failed to remove update leftover {}: {}", path.display(), e);
}
let path = entry.path();
let result = if path.is_dir() {
fs::remove_dir_all(&path)
} else {
fs::remove_file(&path)
};
match result {
Ok(()) => {
info!("Removed update leftover: {}", path.display());
cleaned += 1;
}
Err(e) => warn!("Failed to remove update leftover {}: {}", path.display(), e),
}
}
cleaned
}

Ok(cleaned)
fn matching_entries(dir: &Path, matches: impl Fn(&str) -> bool) -> Vec<PathBuf> {
let Ok(entries) = fs::read_dir(dir) else {
return Vec::new();
};
entries
.flatten()
.filter(|e| matches(&e.file_name().to_string_lossy()))
.map(|e| e.path())
.collect()
}
}

#[cfg(test)]
#[path = "update_cleanup_service_tests.rs"]
mod tests;
Loading
Loading