Free, open-source file converter. Convert 263 formats offline by drag & drop — images, PDF, Word, Excel, PowerPoint, HWP/HWPX, video, audio, e-books and archives. No upload, no Office needed.
C# audio-converteravaloniabatch-conversionconvertercsharpdocument-converterdocx-to-pdfdotnetdrag-and-dropfile-conversionfile-converterheic-converterhwphwpximage-converterlinuxmacospdf-convertervideo-converterwindows
fix(updater): address PR #360 review feedback for Linux updater and installer
Alenboshc6e9d7e3cd5a
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex 4a7c9e40..1adb830c 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -349,3 +349,28 @@ have no semibold) instead of the app's embedded Noto fonts.against `MemoryRegistry`, a fake `ISetupSystem` and scratch folders, and renders every page. `/SANDBOX=<folder>`runs the real Setup with a registry file and all folders inside `<folder>`; `build-installer.ps1 -CheckOnly` (CI)installs, updates and uninstalls that way.++## Linux installer and updates++On Linux, Filee is distributed as a self-contained archive (`Filee-<version>-<rid>.tar.gz` for `linux-x64` and+`linux-arm64`) containing the application, `filee-cli`, bundled conversion engines, application icon, `.desktop` launcher,+and standalone shell scripts (`install.sh`, `uninstall.sh`).++- **Installation**: `install.sh` installs for the current user into `~/.local/share/filee/application` without root,+ creating a launcher symlink at `~/.local/bin/filee` and desktop registration at+ `~/.local/share/applications/com.filee.app.desktop`. A `.filee-package` marker containing `com.filee.app` identifies+ the directory as an authentic managed installation. Running without `--upgrade` refuses to overwrite an existing+ installation.+- **In-app updates** (`UpdateService`): Checks GitHub releases for matching `<rid>.tar.gz` and `<rid>-SHA256SUMS.txt`+ assets. The tarball is verified against SHA-256 before extraction. Archive extraction validates that all entries stay+ within the target directory, rejecting absolute paths, directory symlinks, and escaping links, and masks permissions to+ standard rwx bits (excluding setuid/setgid/sticky bits).+- **Transactional upgrade**: `UpdateAsync` stages the payload in a private directory (`~/.local/share/filee/.update-*`),+ spawns a detached `/bin/sh` helper, and requests application shutdown (`App.Quit`). Once the old process exits, the+ helper executes `install.sh --upgrade` (which safely moves the existing installation to a backup directory, validates the+ new files, and rolls back on failure or signal interruption), and restarts Filee with `--background --whats-new`.+ Output and rollback diagnostics are appended to Filee's daily log (`~/.config/Filee/logs/`). Downloaded conversion engines+ (`~/.local/share/Filee/engines`) and user settings (`~/.config/Filee`) remain untouched.+- **Uninstallation**: `uninstall.sh` removes the application directory, desktop launcher, and `~/.local/bin/filee` symlink+ after verifying the `.filee-package` marker. User settings and converted files are kept.+diff --git a/installer/linux/install.sh b/installer/linux/install.shindex f23bca4c..cdfefacf 100755--- a/installer/linux/install.sh+++ b/installer/linux/install.sh@@ -6,23 +6,19 @@ set -eu# Preserves downloaded conversion engines (~/.local/share/Filee/engines) and user settings (~/.config/Filee).upgrade=0-restart=0for arg docase "$arg" in--upgrade|-u)upgrade=1;;- --restart)- restart=1- ;;--help|-h)- printf '%s\n' "Usage: $0 [--upgrade|-u] [--restart]"+ printf '%s\n' "Usage: $0 [--upgrade|-u]"exit 0;;*)printf '%s\n' "Unknown option: $arg" >&2- printf '%s\n' "Usage: $0 [--upgrade|-u] [--restart]" >&2+ printf '%s\n' "Usage: $0 [--upgrade|-u]" >&2exit 1;;esac@@ -40,16 +36,6 @@ command -v python3 >/dev/null 2>&1 || {exit 1}-# Only enable internal test failure hooks if explicitly requested by the test harness-# AND executing within an isolated temporary test directory.-test_hooks_enabled=0-if [ "${_FILEE_TEST_HARNESS:-}" = "com.filee.test.harness" ]; then- case "$data_dir" in- /tmp/*|/var/tmp/*|*/filee-installer-test-*)- test_hooks_enabled=1- ;;- esac-fiif [ ! -f "$source_dir/Filee" ] || [ ! -x "$source_dir/Filee" ]; thenprintf '%s\n' "Payload validation failed: $source_dir/Filee is missing or not executable." >&2@@ -100,13 +86,11 @@ elseexit 1fi- # Tell running instance to save and exit cleanly before touching files (skipped during in-app updates).- if [ "${FILEE_IN_APP_UPDATE:-0}" != "1" ]; then- if [ -x "$install_dir/Filee" ]; then- if ! "$install_dir/Filee" --quit; then- printf '%s\n' "Could not gracefully shut down the running Filee instance. Please exit Filee and try again." >&2- exit 1- fi+ # Tell running instance to save and exit cleanly before touching files.+ if [ -x "$install_dir/Filee" ]; then+ if ! "$install_dir/Filee" --quit; then+ printf '%s\n' "Could not gracefully shut down the running Filee instance. Please exit Filee and try again." >&2+ exit 1fifi@@ -215,68 +199,12 @@ else# Move active installation to backup.mv "$install_dir" "$backup_dir"- # Test hook: simulate failure after backup but before activation.- if [ "$test_hooks_enabled" -eq 1 ] && [ "${_FILEE_TEST_FAIL_ACTIVATION:-0}" = "1" ]; then- rm -rf "$staging_dir"- fi-- # Test hook: simulate activation destination conflict.- if [ "$test_hooks_enabled" -eq 1 ] && [ "${_FILEE_TEST_FAIL_ACTIVATION_OCCUPIED:-0}" = "1" ]; then- mkdir -p "$install_dir"- touch "$install_dir/conflict"- chmod 555 "$install_dir"- fi-# Activate new installation from staging.if ! mv "$staging_dir" "$install_dir"; thenexit 1fiactivated=1- # Test hook: simulate failure during post-swap validation.- if [ "$test_hooks_enabled" -eq 1 ] && [ "${_FILEE_TEST_FAIL_POST_VALIDATION:-0}" = "1" ]; then- rm -f "$install_dir/.filee-package"- fi-- # Test hook: simulate failure during post-swap validation where failed_dir cleanup will fail.- if [ "$test_hooks_enabled" -eq 1 ] && [ "${_FILEE_TEST_FAIL_CLEANUP_FAILED_DIR:-0}" = "1" ]; then- mkdir -p "$install_dir/locked-folder"- touch "$install_dir/locked-folder/file"- chmod 555 "$install_dir/locked-folder"- rm -f "$install_dir/.filee-package"- fi-- # Test hook: simulate quarantine move failure during rollback.- if [ "$test_hooks_enabled" -eq 1 ] && [ "${_FILEE_TEST_FAIL_QUARANTINE:-0}" = "1" ]; then- mkdir -p "$failed_dir"- touch "$failed_dir/conflict"- exit 1- fi-- # Test hook: simulate replacement of install_dir by a foreign directory before rollback.- if [ "$test_hooks_enabled" -eq 1 ] && [ "${_FILEE_TEST_FAIL_FOREIGN_DESTINATION:-0}" = "1" ]; then- rm -rf "$install_dir"- mkdir -p "$install_dir"- echo "important-foreign-data" > "$install_dir/important.txt"- exit 1- fi-- # Test hook: simulate failure during rollback with occupied destination.- if [ "$test_hooks_enabled" -eq 1 ] && { [ "${_FILEE_TEST_FAIL_ROLLBACK_OCCUPIED:-0}" = "1" ] || [ "${_FILEE_TEST_FAIL_ROLLBACK:-0}" = "1" ]; }; then- rm -rf "$install_dir"- mkdir -p "$install_dir"- touch "$install_dir/conflict"- chmod 555 "$install_dir"- exit 1- fi-- # Test hook: simulate failure during rollback with absent destination.- if [ "$test_hooks_enabled" -eq 1 ] && [ "${_FILEE_TEST_FAIL_ROLLBACK_ABSENT:-0}" = "1" ]; then- rm -rf "$install_dir"- chmod 555 "$data_dir/filee"- exit 1- fi-# Post-swap validation: ensure new installation is active and healthy.if [ ! -x "$install_dir/Filee" ] || [ ! -x "$install_dir/filee-cli" ] || [ ! -f "$install_dir/.filee-package" ]; thenprintf '%s\n' "Activated installation failed post-swap validation. Rolling back..." >&2@@ -321,10 +249,6 @@ fiif [ "$upgrade" -eq 1 ]; thenprintf '%s\n' "Upgraded Filee at $install_dir."- if [ "$restart" -eq 1 ] && [ "${FILEE_IN_APP_UPDATE:-0}" != "1" ]; then- nohup "$install_dir/Filee" </dev/null >/dev/null 2>&1 &- printf '%s\n' "Restarted Filee."- fielseprintf '%s\n' "Installed Filee at $install_dir" "CLI: $bin_dir/filee (add $bin_dir to PATH if needed)."fidiff --git a/src/Filee.App/App.axaml.cs b/src/Filee.App/App.axaml.csindex 51e67161..71819380 100644--- a/src/Filee.App/App.axaml.cs+++ b/src/Filee.App/App.axaml.cs@@ -200,8 +200,7 @@ public partial class App : Applicationprivate static void WatchForUpdates(UserDataStore store){var updates = AppHost.Get<UpdateService>();- updates.RequestApplicationShutdown = () =>- (Application.Current?.ApplicationLifetime as IClassicDesktopStyleApplicationLifetime)?.Shutdown();+ updates.RequestApplicationShutdown = Quit;// Required: the card every time Filee starts (UpdateFound fires once per run). Recommended: once per version.// Optional: no card, the sidebar button only. Frequent releases no longer ask every day.updates.UpdateFound += (_, version) =>diff --git a/src/Filee.App/Services/UpdateService.cs b/src/Filee.App/Services/UpdateService.csindex 35fe4747..834dd562 100644--- a/src/Filee.App/Services/UpdateService.cs+++ b/src/Filee.App/Services/UpdateService.cs@@ -14,6 +14,7 @@ using System.Security.Cryptography;using System.Text.Json;using Avalonia.Threading;using CommunityToolkit.Mvvm.ComponentModel;+using Filee.Core.Settings;using Microsoft.Extensions.Logging;namespace Filee.App.Services;@@ -325,154 +326,131 @@ public sealed partial class UpdateService : ObservableObjectreturn;}- string installer;- string? workspace = null;- try- {- workspace = CreateSecureWorkspace();- var progress = new Progress<int>(percent => DownloadPercent = percent);- installer = await DownloadInstallerAsync(workspace, progress);- }- catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException or IOException- or InvalidDataException or UnauthorizedAccessException)+ if (TargetPlatform == "win"){- DeleteSecureWorkspace(workspace);- Fail("download", ex);- return;- }+ var folder = Path.Combine(Path.GetTempPath(), "Filee-update");+ string installer;+ try+ {+ var progress = new Progress<int>(percent => DownloadPercent = percent);+ installer = await DownloadInstallerAsync(folder, progress);+ }+ catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException or IOException+ or InvalidDataException or UnauthorizedAccessException)+ {+ Fail("download", ex);+ return;+ }- Process? setup;- try- {- if (TargetPlatform == "win")+ Process? setup;+ try{setup = StartProcess(new ProcessStartInfo(installer, InstallerArguments) { UseShellExecute = true });}- else if (TargetPlatform.StartsWith("linux-", StringComparison.OrdinalIgnoreCase))+ catch (Win32Exception ex) when (ex.NativeErrorCode == ErrorCancelled){- var stagingDir = Path.Combine(workspace, "payload");- string payloadDir;- try- {- Directory.CreateDirectory(stagingDir);- payloadDir = ExtractLinuxArchive(installer, stagingDir);- }- catch (Exception ex) when (ex is InvalidDataException or IOException or UnauthorizedAccessException)- {- DeleteSecureWorkspace(workspace);- Fail("extract", ex);- return;- }-- var scriptPath = Path.Combine(payloadDir, "install.sh");- var startInfo = new ProcessStartInfo("/bin/sh")- {- WorkingDirectory = payloadDir,- UseShellExecute = false,- };- startInfo.ArgumentList.Add(scriptPath);- startInfo.ArgumentList.Add("--upgrade");- startInfo.ArgumentList.Add("--restart");- startInfo.Environment["FILEE_IN_APP_UPDATE"] = "1";- setup = StartProcess(startInfo);+ _log.LogInformation("Update cancelled at the administrator prompt");+ Step = UpdateStep.Cancelled;+ return;}- else+ catch (Exception ex) when (ex is Win32Exception or InvalidOperationException){- throw new PlatformNotSupportedException("In-app update is only supported on Windows and Linux");+ Fail("start", ex);+ return;}- }- catch (Win32Exception ex) when (TargetPlatform == "win" && ex.NativeErrorCode == ErrorCancelled)- {- _log.LogInformation("Update cancelled at the administrator prompt");- Step = UpdateStep.Cancelled;- DeleteSecureWorkspace(workspace);- return;- }- catch (Exception ex) when (ex is Win32Exception or InvalidOperationException or PlatformNotSupportedException)- {- DeleteSecureWorkspace(workspace);- Fail("start", ex);- return;- }- _log.LogInformation("Started the installer for {Version}", LatestVersion);- Step = UpdateStep.Installing;- if (setup is null)+ _log.LogInformation("Started the installer for {Version}", LatestVersion);+ Step = UpdateStep.Installing;+ if (setup is null)+ return;++ using (setup)+ await setup.WaitForExitAsync();+ _log.LogInformation("Installer ended with exit code {Code}", setup.ExitCode);+ Step = setup.ExitCode == 0 ? UpdateStep.Idle : UpdateStep.Cancelled;return;+ }- // A successful update closes Filee before Setup exits, so getting here means Setup ended without updating:- // the administrator prompt was declined (Setup asks for it itself), or the user cancelled, or an error occurred.- using (setup)+ if (TargetPlatform.StartsWith("linux-", StringComparison.OrdinalIgnoreCase)){- await setup.WaitForExitAsync();- _log.LogInformation("Installer ended with exit code {Code}", setup.ExitCode);- if (setup.ExitCode == 0)+ string? workspace = null;+ string installer;+ try+ {+ workspace = CreateSecureWorkspace();+ var progress = new Progress<int>(percent => DownloadPercent = percent);+ installer = await DownloadInstallerAsync(workspace, progress);+ }+ catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException or IOException+ or InvalidDataException or UnauthorizedAccessException){- if (TargetPlatform.StartsWith("linux-", StringComparison.OrdinalIgnoreCase))- {- var targetInstallDir = LinuxInstallDirectoryOverride ?? GetLinuxInstallDirectory();- var expectedVersion = LatestVersion;- if (string.IsNullOrWhiteSpace(expectedVersion))- {- var fileName = Path.GetFileName(installer);- var parts = fileName.Split('-');- if (parts.Length >= 2 && TryParse(parts[1], out var parsedVer))- expectedVersion = parsedVer.ToString(3);- expectedVersion ??= "";- }- if (!VerifyInstalledVersion(targetInstallDir, expectedVersion, out var actualVersion))- {- var recovery = FindLinuxRecoveryInfo(targetInstallDir);- var message = $"Update verification failed: installed version '{actualVersion ?? "unknown"}' does not match expected version '{expectedVersion}'. {recovery}";- _log.LogError("{Message}", message);- DeleteSecureWorkspace(workspace);- Fail("verify", new InvalidOperationException(message));- return;- }- // Success on Linux: spawn detached restart watcher and shut down current instance.- try- {- var newExe = Path.Combine(targetInstallDir, "Filee");- var currentPid = Environment.ProcessId;- var restartWatcher = new ProcessStartInfo("/bin/sh")- {- WorkingDirectory = targetInstallDir,- UseShellExecute = false,- };- restartWatcher.ArgumentList.Add("-c");- restartWatcher.ArgumentList.Add("for _ in $(seq 1 600); do if ! kill -0 \"$1\" 2>/dev/null; then exec \"$2\"; fi; sleep 0.1; done; exit 1");- restartWatcher.ArgumentList.Add("_");- restartWatcher.ArgumentList.Add(currentPid.ToString());- restartWatcher.ArgumentList.Add(newExe);- restartWatcher.Environment.Remove("FILEE_IN_APP_UPDATE");- StartProcess(restartWatcher);- }- catch (Exception ex)- {- _log.LogWarning(ex, "Failed to launch restart watcher for {Version}", expectedVersion);- }- RequestApplicationShutdown?.Invoke();- }- Step = UpdateStep.Idle;DeleteSecureWorkspace(workspace);+ Fail("download", ex);+ return;+ }++ var stagingDir = Path.Combine(workspace, "payload");+ string payloadDir;+ try+ {+ Directory.CreateDirectory(stagingDir);+ payloadDir = ExtractLinuxArchive(installer, stagingDir);}- else if (TargetPlatform == "win")+ catch (Exception ex) when (ex is InvalidDataException or IOException or UnauthorizedAccessException){- Step = UpdateStep.Cancelled;DeleteSecureWorkspace(workspace);+ Fail("extract", ex);+ return;}- else++ var scriptPath = Path.Combine(payloadDir, "install.sh");+ var targetInstallDir = LinuxInstallDirectoryOverride ?? GetLinuxInstallDirectory();+ var newExe = Path.Combine(targetInstallDir, "Filee");+ var currentPid = Environment.ProcessId;+ var logDir = Path.Combine(UserDataStore.DefaultDirectory, "logs");+ Directory.CreateDirectory(logDir);+ var logFile = Path.Combine(logDir, $"filee-{DateTime.Now:yyyyMMdd}.log");++ Process? helper;+ try+ {+ var startInfo = new ProcessStartInfo("/bin/sh")+ {+ WorkingDirectory = payloadDir,+ UseShellExecute = false,+ };+ startInfo.ArgumentList.Add("-c");+ startInfo.ArgumentList.Add(+ "for _ in $(seq 1 600); do if ! kill -0 \"$1\" 2>/dev/null; then break; fi; sleep 0.1; done; " ++ "if kill -0 \"$1\" 2>/dev/null; then echo \"Update aborted: Filee (PID $1) did not exit within timeout\" >> \"$4\"; exit 1; fi; " ++ "\"$2\" --upgrade >> \"$4\" 2>&1; " ++ "status=$?; " ++ "rm -rf \"$5\" 2>/dev/null; " ++ "if [ $status -eq 0 ]; then exec \"$3\" --background --whats-new; else echo \"Update failed with status $status\" >> \"$4\"; exit $status; fi"+ );+ startInfo.ArgumentList.Add("_");+ startInfo.ArgumentList.Add(currentPid.ToString());+ startInfo.ArgumentList.Add(scriptPath);+ startInfo.ArgumentList.Add(newExe);+ startInfo.ArgumentList.Add(logFile);+ startInfo.ArgumentList.Add(workspace);++ helper = StartProcess(startInfo);+ }+ catch (Exception ex) when (ex is Win32Exception or InvalidOperationException){- var targetInstallDir = LinuxInstallDirectoryOverride ?? GetLinuxInstallDirectory();- var recovery = FindLinuxRecoveryInfo(targetInstallDir);- var message = string.IsNullOrEmpty(recovery)- ? $"Installer ended with exit code {setup.ExitCode}"- : $"Installer ended with exit code {setup.ExitCode}. {recovery}";- _log.LogError("{Message}", message);DeleteSecureWorkspace(workspace);- Fail("install", new InvalidOperationException(message));+ Fail("start", ex);+ return;}++ _log.LogInformation("Started update helper for {Version}, exiting current process", LatestVersion);+ Step = UpdateStep.Installing;+ RequestApplicationShutdown?.Invoke();+ return;}++ throw new PlatformNotSupportedException("In-app update is only supported on Windows and Linux");}/// <summary>@@ -633,6 +611,11 @@ public sealed partial class UpdateService : ObservableObjectreturn (installer, checksums);}+ private const UnixFileMode RwxMask =+ UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute |+ UnixFileMode.GroupRead | UnixFileMode.GroupWrite | UnixFileMode.GroupExecute |+ UnixFileMode.OtherRead | UnixFileMode.OtherWrite | UnixFileMode.OtherExecute;+/// <summary>/// Extracts a Linux release archive (.tar.gz) into <paramref name="destinationDirectory"/> with security validation/// (rejecting path traversal, absolute paths, unsafe entry types, directory symlinks, and escaping/component symlinks).@@ -704,8 +687,7 @@ public sealed partial class UpdateService : ObservableObjectif (OperatingSystem.IsLinux()){- var mode = entry.Mode;- mode |= UnixFileMode.UserRead | UnixFileMode.UserWrite;+ var mode = (entry.Mode & RwxMask) | UnixFileMode.UserRead | UnixFileMode.UserWrite;File.SetUnixFileMode(destinationPath, mode);}break;@@ -860,8 +842,7 @@ public sealed partial class UpdateService : ObservableObject{if (OperatingSystem.IsLinux() && File.Exists(path)){- var mode = File.GetUnixFileMode(path);- mode |= UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute;+ var mode = (File.GetUnixFileMode(path) & RwxMask) | UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute;File.SetUnixFileMode(path, mode);}}@@ -907,19 +888,26 @@ public sealed partial class UpdateService : ObservableObject{if (string.IsNullOrWhiteSpace(baseDir)){- baseDir = Path.GetTempPath();if (OperatingSystem.IsLinux()){- var runtimeDir = Environment.GetEnvironmentVariable("XDG_RUNTIME_DIR");- if (!string.IsNullOrWhiteSpace(runtimeDir) && Directory.Exists(runtimeDir))- baseDir = runtimeDir;+ var dataHome = Environment.GetEnvironmentVariable("XDG_DATA_HOME");+ var root = !string.IsNullOrWhiteSpace(dataHome)+ ? dataHome+ : Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);+ baseDir = Path.Combine(root, "filee");+ }+ else+ {+ baseDir = Path.GetTempPath();}}+ Directory.CreateDirectory(baseDir);+for (var attempt = 0; attempt < 100; attempt++){var token = Convert.ToHexString(RandomNumberGenerator.GetBytes(16)).ToLowerInvariant();- var candidate = Path.Combine(baseDir, $"filee-update-{Environment.ProcessId}-{token}");+ var candidate = Path.Combine(baseDir, $".update-{Environment.ProcessId}-{token}");if (Path.Exists(candidate))continue;@@ -968,12 +956,13 @@ public sealed partial class UpdateService : ObservableObject/// <summary>Locates the installation directory on Linux.</summary>internal static string GetLinuxInstallDirectory(){- var overrideDir = Environment.GetEnvironmentVariable("FILEE_INSTALL_DIR");- if (!string.IsNullOrWhiteSpace(overrideDir))- return overrideDir;if (IsLinuxInstalled(AppContext.BaseDirectory))return AppContext.BaseDirectory;- return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "filee", "application");+ var dataHome = Environment.GetEnvironmentVariable("XDG_DATA_HOME");+ var root = !string.IsNullOrWhiteSpace(dataHome)+ ? dataHome+ : Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);+ return Path.Combine(root, "filee", "application");}/// <summary>Reads the installed Filee version from the specified installation folder.</summary>@@ -1036,19 +1025,6 @@ public sealed partial class UpdateService : ObservableObject}}- var marker = Path.Combine(installDir, ".filee-version");- if (File.Exists(marker))- {- try- {- return File.ReadAllText(marker).Trim();- }- catch- {- // Fall through- }- }-return null;}@@ -1065,9 +1041,10 @@ public sealed partial class UpdateService : ObservableObjectreturn string.Equals(actualVersion.Trim(), expectedVersion.Trim(), StringComparison.OrdinalIgnoreCase);}- private static string FindLinuxRecoveryInfo(string installDir)+ internal static string FindLinuxRecoveryInfo(string installDir){- var parent = Path.GetDirectoryName(installDir);+ var cleanInstallDir = Path.TrimEndingDirectorySeparator(installDir);+ var parent = Path.GetDirectoryName(cleanInstallDir);if (string.IsNullOrWhiteSpace(parent) || !Directory.Exists(parent))return "";@@ -1077,7 +1054,7 @@ public sealed partial class UpdateService : ObservableObjectif (backups.Length > 0){var latestBackup = backups.OrderByDescending(Directory.GetCreationTimeUtc).First();- return $"Previous installation retained at '{latestBackup}'. To recover manually: mv '{latestBackup}' '{installDir}'";+ return $"Previous installation retained at '{latestBackup}'. To recover manually: mv '{latestBackup}' '{cleanInstallDir}'";}}catchdiff --git a/tests/Filee.App.Tests/UpdateServiceTests.cs b/tests/Filee.App.Tests/UpdateServiceTests.csindex d4ccd96b..1f4db326 100644--- a/tests/Filee.App.Tests/UpdateServiceTests.cs+++ b/tests/Filee.App.Tests/UpdateServiceTests.cs@@ -1,3 +1,4 @@+using System.ComponentModel;using System.Diagnostics;using System.Formats.Tar;using System.IO.Compression;@@ -456,7 +457,7 @@ public class UpdateServiceTests}[AvaloniaFact]- public async Task UpdateAsync_on_linux_downloads_extracts_and_invokes_installer_with_upgrade_and_restart()+ public async Task UpdateAsync_on_linux_downloads_extracts_and_delegates_to_detached_helper(){var tarBytes = CreateTarGz(writer =>{@@ -468,7 +469,6 @@ public class UpdateServiceTestsvar network = new FakeLinuxRelease(tarBytes, hash, "Filee-9.9.9-linux-x64.tar.gz", "9.9.9");var mockInstallDir = TempFolder();- File.WriteAllText(Path.Combine(mockInstallDir, ".filee-version"), "9.9.9");var updates = new UpdateService(NullLogger<UpdateService>.Instance, network){@@ -491,32 +491,25 @@ public class UpdateServiceTestsawait updates.UpdateAsync();- Assert.Equal(UpdateStep.Idle, updates.Step);- Assert.True(processes.Count >= 2);+ Assert.Equal(UpdateStep.Installing, updates.Step);+ Assert.Single(processes);- var installerPsi = processes[0];- Assert.Equal("/bin/sh", installerPsi.FileName);- Assert.Equal(3, installerPsi.ArgumentList.Count);- Assert.EndsWith("install.sh", installerPsi.ArgumentList[0]);- Assert.Equal("--upgrade", installerPsi.ArgumentList[1]);- Assert.Equal("--restart", installerPsi.ArgumentList[2]);- Assert.Equal("1", installerPsi.Environment["FILEE_IN_APP_UPDATE"]);- Assert.Equal(installerPsi.WorkingDirectory, Path.GetDirectoryName(installerPsi.ArgumentList[0]));+ var helperPsi = processes[0];+ Assert.Equal("/bin/sh", helperPsi.FileName);+ Assert.Equal("-c", helperPsi.ArgumentList[0]);+ Assert.Contains("kill -0 \"$1\"", helperPsi.ArgumentList[1]);+ Assert.Contains("\"$2\" --upgrade >> \"$4\" 2>&1", helperPsi.ArgumentList[1]);+ Assert.Contains("exec \"$3\" --background --whats-new", helperPsi.ArgumentList[1]);+ Assert.Equal(Environment.ProcessId.ToString(), helperPsi.ArgumentList[3]);+ Assert.EndsWith("install.sh", helperPsi.ArgumentList[4]);+ Assert.Equal(Path.Combine(mockInstallDir, "Filee"), helperPsi.ArgumentList[5]);+ Assert.EndsWith(".log", helperPsi.ArgumentList[6]);- var restartPsi = processes[1];- Assert.Equal("/bin/sh", restartPsi.FileName);- Assert.Equal("-c", restartPsi.ArgumentList[0]);- Assert.Contains("kill -0", restartPsi.ArgumentList[1]);- Assert.Equal(Environment.ProcessId.ToString(), restartPsi.ArgumentList[3]);- Assert.Equal(Path.Combine(mockInstallDir, "Filee"), restartPsi.ArgumentList[4]);- Assert.Equal(mockInstallDir, restartPsi.WorkingDirectory);- Assert.False(restartPsi.Environment.ContainsKey("FILEE_IN_APP_UPDATE"));-- Assert.True(shutdownRequested, "Application shutdown must be requested after verified installation");+ Assert.True(shutdownRequested, "Application shutdown must be requested before file swap");}[AvaloniaFact]- public async Task UpdateAsync_on_linux_handles_installer_failure()+ public async Task UpdateAsync_on_linux_handles_helper_start_failure(){var tarBytes = CreateTarGz(writer =>{@@ -528,8 +521,6 @@ public class UpdateServiceTestsvar network = new FakeLinuxRelease(tarBytes, hash, "Filee-9.9.9-linux-x64.tar.gz", "9.9.9");var mockInstallDir = TempFolder();- var backupDir = Path.Combine(Path.GetDirectoryName(mockInstallDir)!, ".backup-123");- Directory.CreateDirectory(backupDir);var updates = new UpdateService(NullLogger<UpdateService>.Instance, network){@@ -548,16 +539,15 @@ public class UpdateServiceTestsupdates.RequestApplicationShutdown = () => shutdownRequested = true;updates.StartProcess = psi =>- Process.Start(new ProcessStartInfo("false") { UseShellExecute = false });+ throw new Win32Exception("Cannot spawn helper process");await updates.UpdateAsync();Assert.Equal(UpdateStep.Failed, updates.Step);Assert.Equal(1, failedCount);Assert.NotNull(updates.LastError);- Assert.Contains("Installer ended with exit code 1", updates.LastError.Message);- Assert.Contains("mv '" + backupDir + "' '" + mockInstallDir + "'", updates.LastError.Message);- Assert.False(shutdownRequested, "Application shutdown must not be requested when installer fails");+ Assert.Contains("Cannot spawn helper process", updates.LastError.Message);+ Assert.False(shutdownRequested, "Application shutdown must not be requested when helper fails to start");}[Fact]@@ -637,7 +627,14 @@ public class UpdateServiceTestsvar linkContainer = TempFolder();var symlinkPath = Path.Combine(linkContainer, "link-to-real");- File.CreateSymbolicLink(symlinkPath, realDir);+ try+ {+ File.CreateSymbolicLink(symlinkPath, realDir);+ }+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)+ {+ Assert.Skip("This machine doesn't let the test make a symbolic link.");+ }UpdateService.DeleteSecureWorkspace(symlinkPath);@@ -667,7 +664,10 @@ public class UpdateServiceTestspublic void VerifyInstalledVersion_detects_mismatch(){var folder = TempFolder();- File.WriteAllText(Path.Combine(folder, ".filee-version"), "1.0.0");+ var cli = Path.Combine(folder, "filee-cli");+ File.WriteAllText(cli, "#!/bin/sh\necho \"filee 1.0.0\"\n");+ if (OperatingSystem.IsLinux())+ File.SetUnixFileMode(cli, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute);Assert.True(UpdateService.VerifyInstalledVersion(folder, "1.0.0", out var actual));Assert.Equal("1.0.0", actual);@@ -680,47 +680,52 @@ public class UpdateServiceTestsAssert.Null(actual);}- [AvaloniaFact]- public async Task UpdateAsync_on_linux_fails_when_installed_version_does_not_match()+ [Fact]+ public void Tar_extraction_masks_mode_to_rwx_bits(){var tarBytes = CreateTarGz(writer =>{- AddFileEntry(writer, "Filee-9.9.9-linux-x64/Filee", "#!/bin/sh\nexit 0\n");- AddFileEntry(writer, "Filee-9.9.9-linux-x64/install.sh", "#!/bin/sh\nexit 0\n");- AddFileEntry(writer, "Filee-9.9.9-linux-x64/filee.png", "png data");+ var setuidMode = UnixFileMode.SetUser | UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute+ | UnixFileMode.GroupRead | UnixFileMode.GroupExecute | UnixFileMode.OtherRead | UnixFileMode.OtherExecute;+ var setgidMode = UnixFileMode.SetGroup | UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute+ | UnixFileMode.GroupRead | UnixFileMode.GroupExecute | UnixFileMode.OtherRead | UnixFileMode.OtherExecute;+ AddFileEntry(writer, "Filee-9.9.9-linux-x64/Filee", "#!/bin/sh\nexit 0\n", setuidMode);+ AddFileEntry(writer, "Filee-9.9.9-linux-x64/install.sh", "#!/bin/sh\nexit 0\n", setgidMode);});- var hash = Sha256(tarBytes);- var network = new FakeLinuxRelease(tarBytes, hash, "Filee-9.9.9-linux-x64.tar.gz", "9.9.9");+ var archiveFile = Path.Combine(TempFolder(), "payload.tar.gz");+ File.WriteAllBytes(archiveFile, tarBytes);- var mockInstallDir = TempFolder();- File.WriteAllText(Path.Combine(mockInstallDir, ".filee-version"), "1.0.0"); // Mismatch: expecting 9.9.9+ var destFolder = TempFolder();+ var payloadDir = UpdateService.ExtractLinuxArchive(archiveFile, destFolder);- var updates = new UpdateService(NullLogger<UpdateService>.Instance, network)+ if (OperatingSystem.IsLinux()){- InstallsItself = true,- TargetPlatform = "linux-x64",- LinuxInstallDirectoryOverride = mockInstallDir,- };- updates.UseRelease(- new UpdateService.ReleaseFile("Filee-9.9.9-linux-x64.tar.gz", Base + "Filee-9.9.9-linux-x64.tar.gz", tarBytes.Length),- new UpdateService.ReleaseFile("Filee-9.9.9-linux-x64-SHA256SUMS.txt", Base + "Filee-9.9.9-linux-x64-SHA256SUMS.txt", 100));+ var fileeMode = File.GetUnixFileMode(Path.Combine(payloadDir, "Filee"));+ var installMode = File.GetUnixFileMode(Path.Combine(payloadDir, "install.sh"));- var failedCount = 0;- updates.UpdateFailed += (_, _) => failedCount++;+ Assert.False(fileeMode.HasFlag(UnixFileMode.SetUser), "setuid bit must be stripped");+ Assert.False(fileeMode.HasFlag(UnixFileMode.SetGroup), "setgid bit must be stripped");+ Assert.False(fileeMode.HasFlag(UnixFileMode.StickyBit), "sticky bit must be stripped");- var shutdownRequested = false;- updates.RequestApplicationShutdown = () => shutdownRequested = true;+ Assert.False(installMode.HasFlag(UnixFileMode.SetUser), "setuid bit must be stripped");+ Assert.False(installMode.HasFlag(UnixFileMode.SetGroup), "setgid bit must be stripped");+ Assert.False(installMode.HasFlag(UnixFileMode.StickyBit), "sticky bit must be stripped");+ }+ }- updates.StartProcess = psi =>- Process.Start(new ProcessStartInfo("true") { UseShellExecute = false });+ [Fact]+ public void FindLinuxRecoveryInfo_handles_trailing_directory_separator()+ {+ var baseDir = TempFolder();+ var installDir = Path.Combine(baseDir, "application");+ Directory.CreateDirectory(installDir);- await updates.UpdateAsync();+ var backupDir = Path.Combine(baseDir, ".backup-123");+ Directory.CreateDirectory(backupDir);- Assert.Equal(UpdateStep.Failed, updates.Step);- Assert.Equal(1, failedCount);- Assert.NotNull(updates.LastError);- Assert.Contains("Update verification failed", updates.LastError.Message);- Assert.False(shutdownRequested, "Application shutdown must not be requested when version verification fails");+ var recovery = UpdateService.FindLinuxRecoveryInfo(installDir + Path.DirectorySeparatorChar);+ Assert.Contains(backupDir, recovery);+ Assert.Contains("To recover manually: mv", recovery);}private static byte[] CreateTarGz(Action<TarWriter> populate)diff --git a/tests/Filee.Platform.Tests/LinuxInstallerTests.cs b/tests/Filee.Platform.Tests/LinuxInstallerTests.csindex 5d49b342..ce70a361 100644--- a/tests/Filee.Platform.Tests/LinuxInstallerTests.cs+++ b/tests/Filee.Platform.Tests/LinuxInstallerTests.cs@@ -8,6 +8,7 @@ public sealed class LinuxInstallerTests : IDisposable{private readonly string _root = Path.Combine(Path.GetTempPath(), "filee-installer-test-" + Guid.NewGuid().ToString("N"));private readonly string _installScriptPath;+ private readonly string _shimBinDir;public LinuxInstallerTests(){@@ -20,13 +21,128 @@ public sealed class LinuxInstallerTests : IDisposabledir = Path.GetDirectoryName(dir) ?? throw new InvalidOperationException("Repository root not found.");}_installScriptPath = Path.Combine(dir, "installer", "linux", "install.sh");++ _shimBinDir = Path.Combine(_root, "shim-bin");+ Directory.CreateDirectory(_shimBinDir);+ if (OperatingSystem.IsLinux())+ {+ var shimPath = Path.Combine(_shimBinDir, "mv");+ File.WriteAllText(shimPath, @"#!/bin/sh+set -e++# Fault-injection shim for LinuxInstallerTests+REAL_MV=$(PATH=""/usr/bin:/bin"" command -v mv)++if [ ""${SHIM_FAIL_ACTIVATION:-0}"" = ""1"" ]; then+ case ""$1"" in+ *.staging-*)+ exit 1+ ;;+ esac+fi++if [ ""${SHIM_FAIL_ACTIVATION_OCCUPIED:-0}"" = ""1"" ]; then+ case ""$1"" in+ *.staging-*)+ mkdir -p ""$2""+ touch ""$2/conflict""+ chmod 555 ""$2""+ exit 1+ ;;+ esac+fi++if [ ""${SHIM_FAIL_POST_VALIDATION:-0}"" = ""1"" ]; then+ case ""$1"" in+ *.staging-*)+ ""$REAL_MV"" ""$@""+ res=$?+ rm -f ""$2/.filee-package""+ exit ""$res""+ ;;+ esac+fi++if [ ""${SHIM_FAIL_CLEANUP_FAILED_DIR:-0}"" = ""1"" ]; then+ case ""$1"" in+ *.staging-*)+ ""$REAL_MV"" ""$@""+ res=$?+ mkdir -p ""$2/locked-folder""+ touch ""$2/locked-folder/file""+ chmod 555 ""$2/locked-folder""+ rm -f ""$2/.filee-package""+ exit ""$res""+ ;;+ esac+fi++if [ ""${SHIM_FAIL_QUARANTINE:-0}"" = ""1"" ]; then+ case ""$1"" in+ *.staging-*)+ ""$REAL_MV"" ""$@""+ res=$?+ rm -f ""$2/.filee-package""+ exit ""$res""+ ;;+ esac+ case ""$2"" in+ *.failed-*)+ exit 1+ ;;+ esac+fi++if [ ""${SHIM_FAIL_FOREIGN_DESTINATION:-0}"" = ""1"" ]; then+ case ""$1"" in+ *.staging-*)+ ""$REAL_MV"" ""$@""+ rm -rf ""$2""+ mkdir -p ""$2""+ echo ""important-foreign-data"" > ""$2/important.txt""+ exit 1+ ;;+ esac+fi++if [ ""${SHIM_FAIL_ROLLBACK_OCCUPIED:-0}"" = ""1"" ]; then+ case ""$1"" in+ *.staging-*)+ ""$REAL_MV"" ""$@""+ rm -rf ""$2""+ mkdir -p ""$2""+ touch ""$2/conflict""+ chmod 555 ""$2""+ exit 1+ ;;+ esac+fi++if [ ""${SHIM_FAIL_ROLLBACK_ABSENT:-0}"" = ""1"" ]; then+ case ""$1"" in+ *.staging-*)+ ""$REAL_MV"" ""$@""+ parent_dir=$(dirname ""$2"")+ rm -rf ""$2""+ chmod 555 ""$parent_dir""+ exit 1+ ;;+ esac+fi++exec ""$REAL_MV"" ""$@""+");+ File.SetUnixFileMode(shimPath,+ UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute |+ UnixFileMode.GroupRead | UnixFileMode.GroupExecute |+ UnixFileMode.OtherRead | UnixFileMode.OtherExecute);+ }}[Fact]public void First_time_installation_succeeds_in_isolated_environment(){- if (!OperatingSystem.IsLinux())- return;+ Assert.SkipUnless(OperatingSystem.IsLinux(), "Requires Linux.");var env = CreateEnvironment();CreateMockPayload(env.SourceDir, "v1.0.0");@@ -58,8 +174,7 @@ public sealed class LinuxInstallerTests : IDisposable[Fact]public void First_time_installation_fails_if_already_installed(){- if (!OperatingSystem.IsLinux())- return;+ Assert.SkipUnless(OperatingSystem.IsLinux(), "Requires Linux.");var env = CreateEnvironment();CreateMockPayload(env.SourceDir, "v1.0.0");@@ -76,8 +191,7 @@ public sealed class LinuxInstallerTests : IDisposable[Fact]public void Upgrade_succeeds_and_replaces_binaries_while_preserving_engine_folder_and_settings(){- if (!OperatingSystem.IsLinux())- return;+ Assert.SkipUnless(OperatingSystem.IsLinux(), "Requires Linux.");var env = CreateEnvironment();CreateMockPayload(env.SourceDir, "v1.0.0");@@ -129,8 +243,7 @@ public sealed class LinuxInstallerTests : IDisposable[Fact]public void Upgrade_fails_if_not_already_installed(){- if (!OperatingSystem.IsLinux())- return;+ Assert.SkipUnless(OperatingSystem.IsLinux(), "Requires Linux.");var env = CreateEnvironment();CreateMockPayload(env.SourceDir, "v1.0.0");@@ -144,8 +257,7 @@ public sealed class LinuxInstallerTests : IDisposable[Fact]public void Upgrade_fails_if_marker_is_invalid_and_preserves_original_install(){- if (!OperatingSystem.IsLinux())- return;+ Assert.SkipUnless(OperatingSystem.IsLinux(), "Requires Linux.");var env = CreateEnvironment();CreateMockPayload(env.SourceDir, "v1.0.0");@@ -169,8 +281,7 @@ public sealed class LinuxInstallerTests : IDisposable[Fact]public void Upgrade_fails_if_payload_is_missing_executables_and_preserves_original_install(){- if (!OperatingSystem.IsLinux())- return;+ Assert.SkipUnless(OperatingSystem.IsLinux(), "Requires Linux.");var env = CreateEnvironment();CreateMockPayload(env.SourceDir, "v1.0.0");@@ -194,8 +305,7 @@ public sealed class LinuxInstallerTests : IDisposable[Fact]public void Upgrade_invokes_quit_on_running_filee_instance(){- if (!OperatingSystem.IsLinux())- return;+ Assert.SkipUnless(OperatingSystem.IsLinux(), "Requires Linux.");var env = CreateEnvironment();CreateMockPayload(env.SourceDir, "v1.0.0");@@ -221,8 +331,7 @@ public sealed class LinuxInstallerTests : IDisposable[Fact]public void Upgrade_rolls_back_if_activation_move_fails(){- if (!OperatingSystem.IsLinux())- return;+ Assert.SkipUnless(OperatingSystem.IsLinux(), "Requires Linux.");var env = CreateEnvironment();CreateMockPayload(env.SourceDir, "v1.0.0");@@ -233,9 +342,9 @@ public sealed class LinuxInstallerTests : IDisposablevar v2Source = Path.Combine(_root, "source-v2");CreateMockPayload(v2Source, "v2.0.0");- // Simulate failure during activation move: _FILEE_TEST_FAIL_ACTIVATION=1+ // Simulate failure during activation move using external mv shimvar (exitCode, output, error) = RunInstaller(v2Source, env.DataDir, env.HomeDir,- new Dictionary<string, string> { ["_FILEE_TEST_FAIL_ACTIVATION"] = "1" }, "--upgrade");+ new Dictionary<string, string> { ["SHIM_FAIL_ACTIVATION"] = "1" }, "--upgrade");Assert.NotEqual(0, exitCode);Assert.Contains("Restored the previous Filee installation", output + error);@@ -249,8 +358,7 @@ public sealed class LinuxInstallerTests : IDisposable[Fact]public void Upgrade_rolls_back_if_post_swap_validation_fails(){- if (!OperatingSystem.IsLinux())- return;+ Assert.SkipUnless(OperatingSystem.IsLinux(), "Requires Linux.");var env = CreateEnvironment();CreateMockPayload(env.SourceDir, "v1.0.0");@@ -261,9 +369,9 @@ public sealed class LinuxInstallerTests : IDisposablevar v2Source = Path.Combine(_root, "source-v2");CreateMockPayload(v2Source, "v2.0.0");- // Simulate failure during post-swap validation: _FILEE_TEST_FAIL_POST_VALIDATION=1+ // Simulate failure during post-swap validation using external mv shimvar (exitCode, output, error) = RunInstaller(v2Source, env.DataDir, env.HomeDir,- new Dictionary<string, string> { ["_FILEE_TEST_FAIL_POST_VALIDATION"] = "1" }, "--upgrade");+ new Dictionary<string, string> { ["SHIM_FAIL_POST_VALIDATION"] = "1" }, "--upgrade");Assert.NotEqual(0, exitCode);Assert.Contains("Activated installation failed post-swap validation", output + error);@@ -278,8 +386,7 @@ public sealed class LinuxInstallerTests : IDisposable[Fact]public void Upgrade_reports_critical_error_and_preserves_backup_if_rollback_destination_is_occupied(){- if (!OperatingSystem.IsLinux())- return;+ Assert.SkipUnless(OperatingSystem.IsLinux(), "Requires Linux.");var env = CreateEnvironment();CreateMockPayload(env.SourceDir, "v1.0.0");@@ -288,9 +395,9 @@ public sealed class LinuxInstallerTests : IDisposablevar v2Source = Path.Combine(_root, "source-v2");CreateMockPayload(v2Source, "v2.0.0");- // Simulate failure during rollback where destination is occupied: _FILEE_TEST_FAIL_ROLLBACK_OCCUPIED=1+ // Simulate failure during rollback where destination is occupied using external mv shimvar (exitCode, output, error) = RunInstaller(v2Source, env.DataDir, env.HomeDir,- new Dictionary<string, string> { ["_FILEE_TEST_FAIL_ROLLBACK_OCCUPIED"] = "1" }, "--upgrade");+ new Dictionary<string, string> { ["SHIM_FAIL_ROLLBACK_OCCUPIED"] = "1" }, "--upgrade");Assert.NotEqual(0, exitCode);Assert.Contains("CRITICAL: Update failed and automatic rollback could not complete", output + error);@@ -314,8 +421,7 @@ public sealed class LinuxInstallerTests : IDisposable[Fact]public void Upgrade_reports_critical_error_if_destination_occupied_during_activation(){- if (!OperatingSystem.IsLinux())- return;+ Assert.SkipUnless(OperatingSystem.IsLinux(), "Requires Linux.");var env = CreateEnvironment();CreateMockPayload(env.SourceDir, "v1.0.0");@@ -324,9 +430,9 @@ public sealed class LinuxInstallerTests : IDisposablevar v2Source = Path.Combine(_root, "source-v2");CreateMockPayload(v2Source, "v2.0.0");- // Simulate destination conflict during activation: _FILEE_TEST_FAIL_ACTIVATION_OCCUPIED=1+ // Simulate destination conflict during activation using external mv shimvar (exitCode, output, error) = RunInstaller(v2Source, env.DataDir, env.HomeDir,- new Dictionary<string, string> { ["_FILEE_TEST_FAIL_ACTIVATION_OCCUPIED"] = "1" }, "--upgrade");+ new Dictionary<string, string> { ["SHIM_FAIL_ACTIVATION_OCCUPIED"] = "1" }, "--upgrade");Assert.NotEqual(0, exitCode);Assert.Contains("CRITICAL: Update failed and automatic rollback could not complete", output + error);@@ -350,8 +456,7 @@ public sealed class LinuxInstallerTests : IDisposable[Fact]public void Upgrade_reports_critical_error_and_preserves_backup_if_rollback_destination_is_absent_but_move_fails(){- if (!OperatingSystem.IsLinux())- return;+ Assert.SkipUnless(OperatingSystem.IsLinux(), "Requires Linux.");var env = CreateEnvironment();CreateMockPayload(env.SourceDir, "v1.0.0");@@ -360,9 +465,9 @@ public sealed class LinuxInstallerTests : IDisposablevar v2Source = Path.Combine(_root, "source-v2");CreateMockPayload(v2Source, "v2.0.0");- // Simulate failure during rollback when install_dir is absent: _FILEE_TEST_FAIL_ROLLBACK_ABSENT=1+ // Simulate failure during rollback when install_dir is absent using external mv shimvar (exitCode, output, error) = RunInstaller(v2Source, env.DataDir, env.HomeDir,- new Dictionary<string, string> { ["_FILEE_TEST_FAIL_ROLLBACK_ABSENT"] = "1" }, "--upgrade");+ new Dictionary<string, string> { ["SHIM_FAIL_ROLLBACK_ABSENT"] = "1" }, "--upgrade");Assert.NotEqual(0, exitCode);Assert.Contains("CRITICAL: Update failed and automatic rollback could not complete", output + error);@@ -386,8 +491,7 @@ public sealed class LinuxInstallerTests : IDisposable[Fact]public void Upgrade_preserves_destination_and_backup_if_quarantine_fails(){- if (!OperatingSystem.IsLinux())- return;+ Assert.SkipUnless(OperatingSystem.IsLinux(), "Requires Linux.");var env = CreateEnvironment();CreateMockPayload(env.SourceDir, "v1.0.0");@@ -396,9 +500,9 @@ public sealed class LinuxInstallerTests : IDisposablevar v2Source = Path.Combine(_root, "source-v2");CreateMockPayload(v2Source, "v2.0.0");- // Simulate quarantine failure during rollback: _FILEE_TEST_FAIL_QUARANTINE=1+ // Simulate quarantine failure during rollback using external mv shimvar (exitCode, output, error) = RunInstaller(v2Source, env.DataDir, env.HomeDir,- new Dictionary<string, string> { ["_FILEE_TEST_FAIL_QUARANTINE"] = "1" }, "--upgrade");+ new Dictionary<string, string> { ["SHIM_FAIL_QUARANTINE"] = "1" }, "--upgrade");Assert.NotEqual(0, exitCode);Assert.Contains("CRITICAL: Update failed and automatic rollback could not complete", output + error);@@ -422,8 +526,7 @@ public sealed class LinuxInstallerTests : IDisposable[Fact]public void Upgrade_restores_backup_and_reports_quarantine_if_quarantine_cleanup_fails(){- if (!OperatingSystem.IsLinux())- return;+ Assert.SkipUnless(OperatingSystem.IsLinux(), "Requires Linux.");var env = CreateEnvironment();CreateMockPayload(env.SourceDir, "v1.0.0");@@ -432,9 +535,9 @@ public sealed class LinuxInstallerTests : IDisposablevar v2Source = Path.Combine(_root, "source-v2");CreateMockPayload(v2Source, "v2.0.0");- // Simulate quarantine cleanup failure: _FILEE_TEST_FAIL_CLEANUP_FAILED_DIR=1+ // Simulate quarantine cleanup failure using external mv shimvar (exitCode, output, error) = RunInstaller(v2Source, env.DataDir, env.HomeDir,- new Dictionary<string, string> { ["_FILEE_TEST_FAIL_CLEANUP_FAILED_DIR"] = "1" }, "--upgrade");+ new Dictionary<string, string> { ["SHIM_FAIL_CLEANUP_FAILED_DIR"] = "1" }, "--upgrade");Assert.NotEqual(0, exitCode);Assert.Contains("Update failed. Restored the previous Filee installation", output + error);@@ -460,8 +563,7 @@ public sealed class LinuxInstallerTests : IDisposable[Fact]public void Upgrade_preserves_preexisting_backup_and_failed_directories_from_earlier_runs(){- if (!OperatingSystem.IsLinux())- return;+ Assert.SkipUnless(OperatingSystem.IsLinux(), "Requires Linux.");var env = CreateEnvironment();CreateMockPayload(env.SourceDir, "v1.0.0");@@ -502,8 +604,7 @@ public sealed class LinuxInstallerTests : IDisposable[Fact]public void Upgrade_preserves_foreign_directory_if_destination_was_replaced_before_rollback(){- if (!OperatingSystem.IsLinux())- return;+ Assert.SkipUnless(OperatingSystem.IsLinux(), "Requires Linux.");var env = CreateEnvironment();CreateMockPayload(env.SourceDir, "v1.0.0");@@ -512,9 +613,9 @@ public sealed class LinuxInstallerTests : IDisposablevar v2Source = Path.Combine(_root, "source-v2");CreateMockPayload(v2Source, "v2.0.0");- // Simulate replacement of install_dir by a foreign directory before rollback: _FILEE_TEST_FAIL_FOREIGN_DESTINATION=1+ // Simulate replacement of install_dir by a foreign directory before rollback using external mv shimvar (exitCode, output, error) = RunInstaller(v2Source, env.DataDir, env.HomeDir,- new Dictionary<string, string> { ["_FILEE_TEST_FAIL_FOREIGN_DESTINATION"] = "1" }, "--upgrade");+ new Dictionary<string, string> { ["SHIM_FAIL_FOREIGN_DESTINATION"] = "1" }, "--upgrade");Assert.NotEqual(0, exitCode);Assert.Contains("CRITICAL: Update failed and automatic rollback could not complete", output + error);@@ -538,10 +639,9 @@ public sealed class LinuxInstallerTests : IDisposable}[Fact]- public void Test_hooks_are_ignored_in_normal_environment_even_if_environment_variable_is_set()+ public void Test_hook_environment_variables_have_no_effect_on_installer(){- if (!OperatingSystem.IsLinux())- return;+ Assert.SkipUnless(OperatingSystem.IsLinux(), "Requires Linux.");var env = CreateEnvironment();CreateMockPayload(env.SourceDir, "v1.0.0");@@ -550,30 +650,21 @@ public sealed class LinuxInstallerTests : IDisposablevar v2Source = Path.Combine(_root, "source-v2");CreateMockPayload(v2Source, "v2.0.0");- // Set failure hook variable, but do NOT pass _FILEE_TEST_HARNESS+ // Setting obsolete internal test hook variables has no effect because install.sh contains no test hooksvar (exitCode, output, error) = RunInstaller(v2Source, env.DataDir, env.HomeDir,- new Dictionary<string, string> { ["_FILEE_TEST_FAIL_ACTIVATION"] = "1" }, passTestHarness: false, "--upgrade");+ new Dictionary<string, string> { ["_FILEE_TEST_FAIL_ACTIVATION"] = "1", ["_FILEE_TEST_HARNESS"] = "com.filee.test.harness" }, "--upgrade");- // The upgrade MUST succeed because test hooks are locked down and ignored without harness tokenAssert.True(exitCode == 0, $"Upgrade failed unexpectedly. Output: {output}. Error: {error}");Assert.Contains("Upgraded Filee at", output);var installDir = Path.Combine(env.DataDir, "filee", "application");Assert.Equal("v2.0.0", File.ReadAllText(Path.Combine(installDir, "version.txt")).Trim());-- // Second check: set failure hook variable with an INVALID test harness token- var (exitCode2, output2, error2) = RunInstaller(v2Source, env.DataDir, env.HomeDir,- new Dictionary<string, string> { ["_FILEE_TEST_FAIL_ACTIVATION"] = "1", ["_FILEE_TEST_HARNESS"] = "bogus-token" }, passTestHarness: false, "--upgrade");-- Assert.True(exitCode2 == 0, $"Upgrade failed unexpectedly with bogus token. Output: {output2}. Error: {error2}");- Assert.Contains("Upgraded Filee at", output2);}[Fact]public void Installation_and_upgrade_succeed_with_spaces_and_special_characters_in_paths(){- if (!OperatingSystem.IsLinux())- return;+ Assert.SkipUnless(OperatingSystem.IsLinux(), "Requires Linux.");var id = Guid.NewGuid().ToString("N");var sourceDir = Path.Combine(_root, "source path with spaces " + id);@@ -604,23 +695,10 @@ public sealed class LinuxInstallerTests : IDisposableAssert.Equal("v2.0.0", File.ReadAllText(Path.Combine(installDir, "version.txt")).Trim());}- private (string SourceDir, string DataDir, string HomeDir) CreateEnvironment()- {- var id = Guid.NewGuid().ToString("N");- var sourceDir = Path.Combine(_root, "source-" + id);- var dataDir = Path.Combine(_root, "data-" + id);- var homeDir = Path.Combine(_root, "home-" + id);- Directory.CreateDirectory(sourceDir);- Directory.CreateDirectory(dataDir);- Directory.CreateDirectory(homeDir);- return (sourceDir, dataDir, homeDir);- }-[Fact]- public void Upgrade_with_in_app_update_env_var_skips_Filee_quit_and_restart()+ public void Upgrade_fails_if_running_filee_cannot_gracefully_shut_down(){- if (!OperatingSystem.IsLinux())- return;+ Assert.SkipUnless(OperatingSystem.IsLinux(), "Requires Linux.");var env = CreateEnvironment();CreateMockPayload(env.SourceDir, "v1.0.0");@@ -639,16 +717,23 @@ public sealed class LinuxInstallerTests : IDisposablevar v2Dir = Path.Combine(_root, "source-v2-" + Guid.NewGuid().ToString("N")[..8]);CreateMockPayload(v2Dir, "v2.0.0");- // 1. Without FILEE_IN_APP_UPDATE, upgrade calls Filee --quit, which fails with code 42+ // Upgrade calls Filee --quit, which fails with code 42var (failCode, failOut, failErr) = RunInstaller(v2Dir, env.DataDir, env.HomeDir, args: ["--upgrade"]);Assert.NotEqual(0, failCode);Assert.Contains("Could not gracefully shut down", failOut + failErr);+ Assert.Equal("v1.0.0", File.ReadAllText(Path.Combine(installDir, "version.txt")).Trim());+ }- // 2. With FILEE_IN_APP_UPDATE=1, upgrade skips Filee --quit and succeeds- var inAppEnv = new Dictionary<string, string> { ["FILEE_IN_APP_UPDATE"] = "1" };- var (succCode, succOut, succErr) = RunInstaller(v2Dir, env.DataDir, env.HomeDir, inAppEnv, "--upgrade", "--restart");- Assert.True(succCode == 0, $"Expected upgrade to succeed. Output: {succOut}. Error: {succErr}");- Assert.Equal("v2.0.0", File.ReadAllText(Path.Combine(installDir, "version.txt")).Trim());+ private (string SourceDir, string DataDir, string HomeDir) CreateEnvironment()+ {+ var id = Guid.NewGuid().ToString("N");+ var sourceDir = Path.Combine(_root, "source-" + id);+ var dataDir = Path.Combine(_root, "data-" + id);+ var homeDir = Path.Combine(_root, "home-" + id);+ Directory.CreateDirectory(sourceDir);+ Directory.CreateDirectory(dataDir);+ Directory.CreateDirectory(homeDir);+ return (sourceDir, dataDir, homeDir);}private void CreateMockPayload(string dir, string version)@@ -671,16 +756,12 @@ public sealed class LinuxInstallerTests : IDisposableFile.SetUnixFileMode(script, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute);}- private static (int ExitCode, string Output, string Error) RunInstaller(+ private (int ExitCode, string Output, string Error) RunInstaller(string sourceDir, string dataDir, string homeDir, params string[] args) =>- RunInstaller(sourceDir, dataDir, homeDir, null, passTestHarness: true, args);-- private static (int ExitCode, string Output, string Error) RunInstaller(- string sourceDir, string dataDir, string homeDir, IDictionary<string, string>? extraEnv, params string[] args) =>- RunInstaller(sourceDir, dataDir, homeDir, extraEnv, passTestHarness: true, args);+ RunInstaller(sourceDir, dataDir, homeDir, null, args);- private static (int ExitCode, string Output, string Error) RunInstaller(- string sourceDir, string dataDir, string homeDir, IDictionary<string, string>? extraEnv, bool passTestHarness, params string[] args)+ private (int ExitCode, string Output, string Error) RunInstaller(+ string sourceDir, string dataDir, string homeDir, IDictionary<string, string>? extraEnv, params string[] args){var script = Path.Combine(sourceDir, "install.sh");var psi = new ProcessStartInfo("/bin/sh")@@ -696,9 +777,7 @@ public sealed class LinuxInstallerTests : IDisposablepsi.Environment["XDG_DATA_HOME"] = dataDir;psi.Environment["HOME"] = homeDir;- psi.Environment["PATH"] = Environment.GetEnvironmentVariable("PATH") ?? "/bin:/usr/bin";- if (passTestHarness)- psi.Environment["_FILEE_TEST_HARNESS"] = "com.filee.test.harness";+ psi.Environment["PATH"] = $"{_shimBinDir}:{Environment.GetEnvironmentVariable("PATH") ?? "/bin:/usr/bin"}";if (extraEnv is not null){@@ -718,10 +797,14 @@ public sealed class LinuxInstallerTests : IDisposable{try{- // Reset write permissions on any created conflict folders so Directory.Delete succeeds- foreach (var dir in Directory.GetDirectories(_root, "*", SearchOption.AllDirectories))+ if (OperatingSystem.IsLinux() && Directory.Exists(_root)){- try { File.SetUnixFileMode(dir, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute); } catch { }+ var psi = new ProcessStartInfo("/bin/chmod", ["-R", "u+rwx", _root])+ {+ UseShellExecute = false,+ CreateNoWindow = true+ };+ Process.Start(psi)?.WaitForExit(5000);}if (Directory.Exists(_root))Directory.Delete(_root, recursive: true);