| 1 | using Cage.Windows; |
| 2 | |
| 3 | if (args is ["smoke-wait", var smokeRelease]) |
| 4 | { |
| 5 | using var deadline = new CancellationTokenSource(TimeSpan.FromSeconds(10)); |
| 6 | while (!File.Exists(smokeRelease)) await Task.Delay(20, deadline.Token); |
| 7 | return; |
| 8 | } |
| 9 | |
| 10 | if (args is ["app-update", "check" or "download"]) |
| 11 | { |
| 12 | File.AppendAllText(Path.Combine(Backend.Root, "retry-invocations"), "x"); |
| 13 | Console.WriteLine(System.Text.Json.JsonSerializer.Serialize(new { phase = "failed", message = "limited", retryable = true, retryAt = Environment.GetEnvironmentVariable("CAGE_UPDATE_RETRY_AT") })); |
| 14 | Environment.Exit(1); |
| 15 | } |
| 16 | |
| 17 | |
| 18 | |
| 19 | if (args is ["prepare-update", "--json", "--stop"]) |
| 20 | { |
| 21 | File.WriteAllText(Path.Combine(AppContext.BaseDirectory, "controller-invoked"), Environment.ProcessId.ToString()); |
| 22 | File.WriteAllText(Path.Combine(AppContext.BaseDirectory, "profile-invoked"), Environment.GetEnvironmentVariable("CLAUDE_CAGE_CONFIG") ?? "missing"); |
| 23 | if (File.Exists(Path.Combine(AppContext.BaseDirectory, "broken-backend"))) |
| 24 | { |
| 25 | Console.WriteLine("{\"status\":\"failed\"}"); Environment.Exit(7); |
| 26 | } |
| 27 | Console.WriteLine(File.Exists(Path.Combine(AppContext.BaseDirectory, "running-environment")) |
| 28 | ? "{\"status\":\"stop_required\"}" : "{\"status\":\"prepared\"}"); |
| 29 | return; |
| 30 | } |
| 31 | |
| 32 | #if WINDOWS |
| 33 | NativeInputTests.Run(); |
| 34 | #endif |
| 35 | |
| 36 | var assertions = 0; |
| 37 | void Check(bool condition, string message) { assertions++; if (!condition) throw new Exception(message); } |
| 38 | void Reject(Action action, string message) |
| 39 | { |
| 40 | assertions++; |
| 41 | try { action(); } catch (InvalidDataException) { return; } |
| 42 | throw new Exception(message); |
| 43 | } |
| 44 | foreach (var (work, dpi) in new[] { |
| 45 | (new System.Drawing.Rectangle(0, 0, 3840, 2080), 96), |
| 46 | (new System.Drawing.Rectangle(0, 0, 3840, 2080), 192), |
| 47 | (new System.Drawing.Rectangle(0, 0, 1920, 1040), 144), |
| 48 | (new System.Drawing.Rectangle(0, 0, 1366, 728), 96), |
| 49 | (new System.Drawing.Rectangle(-1920, 0, 1920, 1040), 96), |
| 50 | (new System.Drawing.Rectangle(0, 0, 1280, 680), 192), |
| 51 | }) |
| 52 | { |
| 53 | var bounds = WindowLayout.Bounds(work, dpi, null); |
| 54 | Check(work.Contains(bounds), "initial window extends beyond the monitor work area"); |
| 55 | Check(bounds.Width >= WindowLayout.Minimum(work, dpi).Width, "initial window is below its DPI-aware minimum"); |
| 56 | var restored = WindowLayout.Bounds(work, dpi, new WindowPlacement(5000, 3000, 5000, 4000, 96, false)); |
| 57 | Check(work.Contains(restored), "saved window is inaccessible after a monitor or DPI change"); |
| 58 | } |
| 59 | Check(WindowLayout.Bounds(new(0, 0, 3840, 2080), 96, null).Width > 2500, "4K window stayed at a fixed 1280 pixels"); |
| 60 | Check(WindowLayout.Bounds(new(0, 0, 3840, 2080), 192, new(100, 100, 1000, 700, 96, false)).Width == 2000, |
| 61 | "restoring a user size did not account for the new monitor DPI"); |
| 62 | Console.WriteLine($"Windows window layout: {assertions} assertions passed."); |
| 63 | assertions = 0; |
| 64 | Check(UpdatePolicy.IsWorkbench("http://localhost:4321/", 4321), "expected local origin rejected"); |
| 65 | foreach (var origin in new[] { "https://localhost:4321/", "http://localhost:4322/", "http://localhost.evil:4321/", "http://user@localhost:4321/", "http://127.0.0.1:4321/", "file:///C:/workbench.html" }) |
| 66 | Check(!UpdatePolicy.IsWorkbench(origin, 4321), "foreign native bridge origin accepted: " + origin); |
| 67 | Check(UpdatePolicy.Entry("http://localhost:4321/#token").Port == 4321, "entry URL rejected"); |
| 68 | Reject(() => UpdatePolicy.Entry("http://localhost:4321/"), "entry without token accepted"); |
| 69 | Check(UpdatePolicy.IsNewer("0.1.0-alpha.10", "0.1.0-alpha.9"), "numeric prerelease ordering"); |
| 70 | Check(UpdatePolicy.IsNewer("0.1.0", "0.1.0-alpha.10"), "stable release ordering"); |
| 71 | Check(UpdatePolicy.IsNewer("1.0.0-alpha.beta", "1.0.0-alpha.10"), "text prerelease ordering"); |
| 72 | Check(!UpdatePolicy.IsNewer("0.1.0-alpha.01", "0.1.0-alpha.0"), "leading zero accepted"); |
| 73 | Check(!UpdatePolicy.IsNewer("0.1.0-alpha.1", "0.1.0-alpha.1"), "same version accepted"); |
| 74 | Check(!UpdatePolicy.IsNewer("0.1.0-alpha.1", "0.1.0"), "downgrade accepted"); |
| 75 | Check(!UpdatePolicy.IsNewer("v0.2.0", "0.1.0"), "noncanonical version accepted"); |
| 76 | Check(!UpdatePolicy.IsNewer("0.2.0+metadata", "0.1.0"), "unmatched backend version accepted"); |
| 77 | var root = Path.GetFullPath(Path.Combine(Path.GetTempPath(), "cage-update-policy-tests")); |
| 78 | var good = Path.Combine(root, "download-abc", "Cage-setup.exe"); |
| 79 | Check(UpdatePolicy.DownloadPath(good, root) == good, "private download rejected"); |
| 80 | foreach (var path in new[] { Path.Combine(root + "-other", "download-abc", "Cage-setup.exe"), Path.Combine(root, "verified-abc", "Cage-setup.exe"), Path.Combine(root, "download-abc", "nested", "Cage-setup.exe"), Path.Combine(root, "download-abc", "Cage.exe") }) |
| 81 | Reject(() => UpdatePolicy.DownloadPath(path, root), "untrusted download path accepted: " + path); |
| 82 | Console.WriteLine($"Windows update/bridge policy: {assertions} assertions passed."); |
| 83 | |
| 84 | var integration = Path.Combine(OperatingSystem.IsMacOS() ? "/private/tmp" : Path.GetTempPath(), "cage-recovery-" + Guid.NewGuid()); |
| 85 | Directory.CreateDirectory(integration); |
| 86 | var savedProfile = Environment.GetEnvironmentVariable("CLAUDE_CAGE_CONFIG"); |
| 87 | try |
| 88 | { |
| 89 | var selectedProfile = Path.Combine(integration, "selected profile", "config.json"); |
| 90 | Environment.SetEnvironmentVariable("CLAUDE_CAGE_CONFIG", Path.GetRelativePath(Environment.CurrentDirectory, selectedProfile)); |
| 91 | var backup = Path.Combine(integration, "old application"); |
| 92 | var candidate = Path.Combine(integration, "new application"); |
| 93 | void InstallFixture(string app, bool broken) |
| 94 | { |
| 95 | var resources = Path.Combine(app, "resources"); Directory.CreateDirectory(resources); |
| 96 | foreach (var file in Directory.EnumerateFiles(AppContext.BaseDirectory)) |
| 97 | File.Copy(file, Path.Combine(resources, Path.GetFileName(file))); |
| 98 | var controller = Path.Combine(resources, "cage.exe"); |
| 99 | File.Copy(Environment.ProcessPath!, controller, true); |
| 100 | if (!OperatingSystem.IsWindows()) File.SetUnixFileMode(controller, File.GetUnixFileMode(Environment.ProcessPath!)); |
| 101 | if (broken) File.WriteAllText(Path.Combine(resources, "broken-backend"), "cannot start"); |
| 102 | } |
| 103 | InstallFixture(backup, false); InstallFixture(candidate, true); |
| 104 | var snapshotSource = Path.Combine(integration, "snapshot source"); |
| 105 | var snapshotTarget = Path.Combine(integration, "snapshot target"); |
| 106 | Directory.CreateDirectory(Path.Combine(snapshotSource, "my-project")); |
| 107 | File.WriteAllText(Path.Combine(snapshotSource, "program.txt"), "program"); |
| 108 | File.WriteAllText(Path.Combine(snapshotSource, "my-project", "work.txt"), "personal data"); |
| 109 | File.WriteAllText(Path.Combine(snapshotSource, "Cage.install-files.json"), System.Text.Json.JsonSerializer.Serialize(new { |
| 110 | version = 1, files = new[] { new { path = "program.txt", sha256 = new string('a', 64) } }, |
| 111 | })); |
| 112 | var copyTree = typeof(UpdateInstaller).GetMethod("CopyTree", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static)!; |
| 113 | copyTree.Invoke(null, [snapshotSource, snapshotTarget]); |
| 114 | Check(File.ReadAllText(Path.Combine(snapshotTarget, "program.txt")) == "program", "update snapshot missed a declared program file"); |
| 115 | Check(!Directory.Exists(Path.Combine(snapshotTarget, "my-project")), "update snapshot copied live user data into the program rollback snapshot"); |
| 116 | Check(File.ReadAllText(Path.Combine(snapshotSource, "my-project", "work.txt")) == "personal data", "snapshot changed personal data"); |
| 117 | var nestedSnapshot = Path.Combine(snapshotSource, "updates", "backup"); |
| 118 | var rejectedNestedSnapshot = false; |
| 119 | try { copyTree.Invoke(null, [snapshotSource, nestedSnapshot]); } |
| 120 | catch (System.Reflection.TargetInvocationException error) when (error.InnerException is InvalidDataException) { rejectedNestedSnapshot = true; } |
| 121 | Check(rejectedNestedSnapshot, "snapshot recursively copied its own output"); |
| 122 | Check(!Directory.Exists(nestedSnapshot), "overlapping snapshot destination was created before validation"); |
| 123 | var ensureComplete = typeof(UpdateInstaller).GetMethod("EnsureInstallationComplete", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static)!; |
| 124 | ensureComplete.Invoke(null, [snapshotSource]); |
| 125 | var recoveryReceipt = snapshotSource + ".cage-installation.json"; |
| 126 | File.WriteAllText(recoveryReceipt, System.Text.Json.JsonSerializer.Serialize(new { stagePath = candidate, backupPath = backup })); |
| 127 | string? pendingRecovery = null; |
| 128 | try { ensureComplete.Invoke(null, [snapshotSource]); } |
| 129 | catch (System.Reflection.TargetInvocationException error) when (error.InnerException is IOException) { pendingRecovery = error.InnerException.Message; } |
| 130 | Check(pendingRecovery != null, "updater accepted a partially restored installation"); |
| 131 | Check(pendingRecovery!.Contains(candidate) && pendingRecovery.Contains(backup), "recovery error omitted the preserved directories"); |
| 132 | Check(File.Exists(recoveryReceipt), "recovery validation removed the persistent receipt"); |
| 133 | File.Delete(recoveryReceipt); |
| 134 | var rejectedMissingInstallation = false; |
| 135 | try { ensureComplete.Invoke(null, [Path.Combine(integration, "missing installation")]); } |
| 136 | catch (System.Reflection.TargetInvocationException error) when (error.InnerException is IOException) { rejectedMissingInstallation = true; } |
| 137 | Check(rejectedMissingInstallation, "updater accepted a missing installation and could restore a program-only snapshot"); |
| 138 | if (!OperatingSystem.IsWindows()) |
| 139 | { |
| 140 | File.Delete(Path.Combine(snapshotSource, "Cage.install-files.json")); |
| 141 | Directory.CreateSymbolicLink(Path.Combine(snapshotSource, "external-link"), Path.Combine(snapshotSource, "my-project")); |
| 142 | var legacySnapshot = Path.Combine(integration, "legacy snapshot"); |
| 143 | copyTree.Invoke(null, [snapshotSource, legacySnapshot]); |
| 144 | Check(File.ReadAllText(Path.Combine(legacySnapshot, "my-project", "work.txt")) == "personal data", "legacy snapshot missed a regular file"); |
| 145 | Check(!Directory.Exists(Path.Combine(legacySnapshot, "external-link")), "legacy snapshot followed a user link"); |
| 146 | } |
| 147 | await UpdateRecovery.PrepareRollback(backup); |
| 148 | Check(File.Exists(Path.Combine(backup, "resources", "controller-invoked")), "recovery did not execute the old backend"); |
| 149 | Check(!File.Exists(Path.Combine(candidate, "resources", "controller-invoked")), "recovery executed the broken candidate backend"); |
| 150 | Check(File.ReadAllText(Path.Combine(backup, "resources", "profile-invoked")) == selectedProfile, "recovery child switched away from the original relative profile"); |
| 151 | File.WriteAllText(Path.Combine(backup, "resources", "running-environment"), "still running"); |
| 152 | var rejected = false; |
| 153 | try { await UpdateRecovery.PrepareRollback(backup); } catch (IOException) { rejected = true; } |
| 154 | Check(rejected, "recovery continued without a prepared response from the old backend"); |
| 155 | |
| 156 | var garbage = Path.Combine(integration, "locked backup"); Directory.CreateDirectory(garbage); |
| 157 | var lockedFile = Path.Combine(garbage, "old.dll"); File.WriteAllText(lockedFile, "old version"); |
| 158 | var download = Path.Combine(integration, "download"); Directory.CreateDirectory(download); |
| 159 | var marker = Path.Combine(integration, "ack.json"); File.WriteAllText(marker, "confirmed"); |
| 160 | var liveApp = Path.Combine(candidate, "Cage.exe"); File.WriteAllText(liveApp, "healthy new application"); |
| 161 | FileStream? locked = null; |
| 162 | if (OperatingSystem.IsWindows()) locked = new FileStream(lockedFile, FileMode.Open, FileAccess.Read, FileShare.Read); |
| 163 | else File.SetUnixFileMode(garbage, UnixFileMode.UserRead | UnixFileMode.UserExecute); |
| 164 | try |
| 165 | { |
| 166 | UpdateRecovery.CleanupAfterSuccess(garbage, download, marker); |
| 167 | Check(File.ReadAllText(liveApp) == "healthy new application", "cleanup changed the confirmed new application"); |
| 168 | Check(File.Exists(lockedFile), "fixture did not cause the intended cleanup failure"); |
| 169 | Check(!Directory.Exists(download) && !File.Exists(marker), "one cleanup failure prevented independent cleanup"); |
| 170 | } |
| 171 | finally |
| 172 | { |
| 173 | locked?.Dispose(); |
| 174 | if (!OperatingSystem.IsWindows()) File.SetUnixFileMode(garbage, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute); |
| 175 | } |
| 176 | Console.WriteLine($"Windows snapshot/recovery integration: {assertions - 22} assertions passed; actual child process and filesystem failures exercised."); |
| 177 | |
| 178 | |
| 179 | var nativeResources = Path.Combine(AppContext.BaseDirectory, "resources"); |
| 180 | if (Directory.Exists(nativeResources)) throw new IOException("retry fixture requires an unused test resources directory"); |
| 181 | Directory.CreateDirectory(nativeResources); |
| 182 | var savedRetry = Environment.GetEnvironmentVariable("CAGE_UPDATE_RETRY_AT"); |
| 183 | try |
| 184 | { |
| 185 | foreach (var file in Directory.EnumerateFiles(AppContext.BaseDirectory)) File.Copy(file, Path.Combine(nativeResources, Path.GetFileName(file))); |
| 186 | var executable = Path.Combine(nativeResources, "cage.exe"); |
| 187 | File.Copy(Environment.ProcessPath!, executable, true); |
| 188 | if (!OperatingSystem.IsWindows()) File.SetUnixFileMode(executable, File.GetUnixFileMode(Environment.ProcessPath!)); |
| 189 | var release = Path.Combine(integration, "smoke-release"); |
| 190 | using (var owned = System.Diagnostics.Process.Start(Backend.StartInfo(executable, "smoke-wait", release))!) |
| 191 | { |
| 192 | var record = Path.Combine(Backend.Root, "control.json"); |
| 193 | Directory.CreateDirectory(Backend.Root); |
| 194 | var controllers = new List<System.Diagnostics.Process>(); |
| 195 | try |
| 196 | { |
| 197 | File.WriteAllText(record, System.Text.Json.JsonSerializer.Serialize(new { pid = Environment.ProcessId })); |
| 198 | var foreignRejected = false; |
| 199 | try { Backend.CaptureSmokeControllers(); } catch (IOException) { foreignRejected = true; } |
| 200 | Check(foreignRejected, "smoke captured a controller outside its application executable"); |
| 201 | File.WriteAllText(record, System.Text.Json.JsonSerializer.Serialize(new { pid = owned.Id })); |
| 202 | controllers = Backend.CaptureSmokeControllers(); |
| 203 | Check(controllers.Count == 1 && !controllers[0].HasExited, "smoke did not pin its live controller"); |
| 204 | var exit = controllers[0].WaitForExitAsync(); |
| 205 | Check(!exit.IsCompleted, "smoke considered a still-running controller stopped"); |
| 206 | File.WriteAllText(release, "release owned child"); |
| 207 | await exit.WaitAsync(TimeSpan.FromSeconds(5)); |
| 208 | Check(controllers[0].HasExited, "smoke did not observe actual controller exit"); |
| 209 | } |
| 210 | finally |
| 211 | { |
| 212 | File.WriteAllText(release, "release owned child"); |
| 213 | if (!owned.WaitForExit(5000)) { owned.Kill(); owned.WaitForExit(); } |
| 214 | foreach (var controller in controllers) controller.Dispose(); |
| 215 | File.Delete(record); |
| 216 | } |
| 217 | } |
| 218 | Console.WriteLine("Windows smoke shutdown: actual controller handle pinned, foreign executable rejected, process exit observed."); |
| 219 | var retryAt = DateTimeOffset.UtcNow.AddHours(1).ToString("yyyy-MM-dd'T'HH:mm:ss'Z'"); |
| 220 | Directory.CreateDirectory(Backend.Root); |
| 221 | Environment.SetEnvironmentVariable("CAGE_UPDATE_RETRY_AT", retryAt); |
| 222 | var completion = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); |
| 223 | var failures = 0; |
| 224 | using var updater = new AppUpdater(state => { if (state.GetValueOrDefault("phase") as string == "failed" && Interlocked.Increment(ref failures) == 2) completion.TrySetResult(); }, () => throw new Exception("unexpected installation"), () => {}); |
| 225 | updater.Handle("check"); |
| 226 | await completion.Task.WaitAsync(TimeSpan.FromSeconds(5)); |
| 227 | Check(updater.Handle("status").GetValueOrDefault("retryAt") as string == retryAt, "process-exit path lost retry deadline"); |
| 228 | updater.Handle("check"); updater.Handle("install"); |
| 229 | await Task.Delay(100); |
| 230 | Check(File.ReadAllText(Path.Combine(Backend.Root, "retry-invocations")) == "x", "native check/install bypassed server cooldown"); |
| 231 | Console.WriteLine("Windows updater protocol: real subprocess preserved deadline; early check/install blocked."); |
| 232 | } |
| 233 | finally |
| 234 | { |
| 235 | Environment.SetEnvironmentVariable("CAGE_UPDATE_RETRY_AT", savedRetry); |
| 236 | Directory.Delete(nativeResources, true); |
| 237 | } |
| 238 | } |
| 239 | finally { |
| 240 | Environment.SetEnvironmentVariable("CLAUDE_CAGE_CONFIG", savedProfile); |
| 241 | Directory.Delete(integration, true); |
| 242 | } |