跳到主要内容

Claude Cage · 面向 Claude 的隔离开发环境,支持桌面工作台、多账号、远程部署与移动端连接。上游 Lee-xeo/Claude-Cage 完整源码镜像,非灵栈原创;主许可 MIT,第三方组件遵循各自许可。来源:https://github.com/Lee-xeo/Claude-Cage 。手动同步,不附带 Release 安装包。

浏览文件

UpdatesTests.swift

208 行 · 14.6 KB历史下载
1import Cocoa
2
3@main
4enum UpdatesTests {
5 static func expect(_ condition: @autoclosure () -> Bool, _ message: String) throws {
6 if !condition() { throw CageUpdateError("TEST FAILED: " + message) }
7 }
8 static func rejects(_ message: String, _ body: () throws -> Void) throws {
9 var rejected = false
10 do { try body() } catch { rejected = true }
11 try expect(rejected, message)
12 }
13 static func main() throws {
14 try expect(CageUpdateVersion.isNewer("0.2.0-alpha.10", than: "0.2.0-alpha.9"), "numeric prerelease ordering")
15 try expect(CageUpdateVersion.isNewer("0.2.0", than: "0.2.0-alpha.10"), "stable promotion")
16 for invalid in ["0.2.0-alpha.01", "../0.3.0", "1.0", "1.0.0/../../"] {
17 try expect(!CageUpdateVersion.isNewer(invalid, than: "0.1.0"), "invalid version rejected")
18 }
19 try expect(!CageUpdateVersion.isNewer("0.2.0", than: "0.2.0"), "same version rejected")
20 try expect(!CageUpdateVersion.isNewer("0.1.0", than: "0.2.0"), "downgrade rejected")
21
22 let root = FileManager.default.temporaryDirectory.appendingPathComponent("cage-updates-test-" + UUID().uuidString)
23 try CageUpdateFiles.privateDirectory(root)
24 defer { try? FileManager.default.removeItem(at: root) }
25 do {
26 let saved = ProcessInfo.processInfo.environment["CLAUDE_CAGE_CONFIG"]
27 let directory = FileManager.default.currentDirectoryPath
28 defer {
29 _ = FileManager.default.changeCurrentDirectoryPath(directory)
30 if let saved { setenv("CLAUDE_CAGE_CONFIG", saved, 1) } else { unsetenv("CLAUDE_CAGE_CONFIG") }
31 }
32 setenv("CLAUDE_CAGE_CONFIG", "", 1)
33 try expect(CageProfile.configURL() == FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent(".claude-cage/config.json"), "empty profile agrees with backend default")
34 try expect(FileManager.default.changeCurrentDirectoryPath(root.path), "enter isolated launch directory")
35 let launchDirectory = FileManager.default.currentDirectoryPath
36 setenv("CLAUDE_CAGE_CONFIG", "selected profile/config.json", 1)
37 CageProfile.pinEnvironment()
38 let pinned = CageProfile.configURL()
39 try expect(pinned.path == launchDirectory + "/selected profile/config.json", "relative profile pinned at launch")
40 try expect(FileManager.default.changeCurrentDirectoryPath(directory), "simulate helper working directory")
41 try expect(CageProfile.configURL() == pinned, "helper keeps original profile after cwd changes")
42 let inherited = try CageUpdateFiles.run("/bin/sh", ["-c", "printf '%s' \"$CLAUDE_CAGE_CONFIG\""])
43 try expect(String(data: inherited, encoding: .utf8) == pinned.path, "actual child process inherits absolute profile")
44 }
45 let personalFiles = [
46 "account.json", "favorites.json", "projects.json", "appearance.json", "workbench.json",
47 "state/lima/persistent/disk", "webview/data/Local Storage/leveldb/000001.log",
48 "workspace/project.txt"
49 ]
50 let profile = root.appendingPathComponent("profile")
51 var personalData: [String: Data] = [:]
52 for name in personalFiles {
53 let file = profile.appendingPathComponent(name)
54 try CageUpdateFiles.privateDirectory(file.deletingLastPathComponent())
55 let bytes = Data("Keep \(name): 历史、收藏和登录状态\n\0".utf8)
56 try CageUpdateFiles.write(bytes, to: file)
57 personalData[name] = bytes
58 }
59 func verifyPersonalData() throws {
60 for (name, expected) in personalData {
61 let actual = try Data(contentsOf: profile.appendingPathComponent(name))
62 try expect(actual == expected, "application replacement or rollback changed personal data: \(name)")
63 }
64 }
65 // Exercise the production lipo invocation against a real Mach-O binary.
66 // lipo consumes every argument after -verify_arch as an architecture.
67 try CageUpdateFiles.verifyArchitecture(URL(fileURLWithPath: CommandLine.arguments[0]))
68 let hashFile = root.appendingPathComponent("content")
69 try CageUpdateFiles.write(Data("abc".utf8), to: hashFile)
70 try rejects("non-Mach-O executable refused") { try CageUpdateFiles.verifyArchitecture(hashFile) }
71 let hash = try CageUpdateFiles.digest(hashFile)
72 try expect(hash == "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad", "stream digest")
73 let permissions = try FileManager.default.attributesOfItem(atPath: hashFile.path)
74 try expect((permissions[.posixPermissions] as? NSNumber)?.intValue == 0o600, "private file mode")
75 let escaped = root.appendingPathComponent("escaped.app")
76 try CageUpdateFiles.privateDirectory(escaped)
77 try FileManager.default.createSymbolicLink(at: escaped.appendingPathComponent("outside"), withDestinationURL: hashFile)
78 try rejects("app symlink escape") { try CageUpdateFiles.validateTree(escaped) }
79
80 let old = root.appendingPathComponent("Cage.app"), next = root.appendingPathComponent("next.app"), backup = root.appendingPathComponent("backup.app")
81 for location in [old, next, backup] { try CageUpdateFiles.privateDirectory(location) }
82 try Data("old".utf8).write(to: old.appendingPathComponent("marker"))
83 try Data("old".utf8).write(to: backup.appendingPathComponent("marker"))
84 try Data("new".utf8).write(to: next.appendingPathComponent("marker"))
85 try CageUpdateFiles.replaceAndVerify(target: old, candidate: next, backup: backup, manager: .default) {
86 let marker = try String(contentsOf: $0.appendingPathComponent("marker"), encoding: .utf8)
87 try expect(marker == "new", "new content reaches final install path")
88 }
89 try verifyPersonalData()
90 try CageUpdateFiles.restore(backup: backup, target: old, manager: .default)
91 try verifyPersonalData()
92 let restored = try String(contentsOf: old.appendingPathComponent("marker"), encoding: .utf8)
93 try expect(restored == "old", "launch failure can restore original")
94 try CageUpdateFiles.privateDirectory(next)
95 try Data("invalid".utf8).write(to: next.appendingPathComponent("marker"))
96 try rejects("post-install validation must roll back") {
97 try CageUpdateFiles.replaceAndVerify(target: old, candidate: next, backup: backup, manager: .default) { _ in throw CageUpdateError("verification failed") }
98 }
99 let rollback = try String(contentsOf: old.appendingPathComponent("marker"), encoding: .utf8)
100 try expect(rollback == "old", "failed validation leaves original installed")
101 try verifyPersonalData()
102 try CageUpdateFiles.privateDirectory(next)
103 try Data("invalid-after-replace".utf8).write(to: next.appendingPathComponent("marker"))
104 var replaced = false
105 try rejects("post-install and rollback failure must remain a changed transaction") {
106 try CageUpdateFiles.replaceAndVerify(target: old, candidate: next, backup: backup, manager: .default,
107 onReplace: { replaced = true }, restoreOriginal: { throw CageUpdateError("injected restore I/O failure") }) { _ in
108 throw CageUpdateError("injected validation failure")
109 }
110 }
111 try expect(replaced, "replacement must be recorded before validation or rollback can fail")
112 let failedTarget = try String(contentsOf: old.appendingPathComponent("marker"), encoding: .utf8)
113 let retainedBackup = try String(contentsOf: backup.appendingPathComponent("marker"), encoding: .utf8)
114 try expect(failedTarget == "invalid-after-replace" && retainedBackup == "old", "double failure must retain the original backup and report the changed target")
115 try CageUpdateFiles.restore(backup: backup, target: old, manager: .default)
116 try verifyPersonalData()
117 try rejects("unsigned application refused") { _ = try CageUpdateFiles.signingInfo(old, bundle: true) }
118
119 // A real child that ignores SIGTERM must not keep cancellation pending.
120 let running = root.appendingPathComponent("validation-running")
121 let task = CageUpdateValidation()
122 DispatchQueue.global().async {
123 defer { task.finish() }
124 _ = try? CageUpdateFiles.run("/bin/sh", ["-c", "trap '' TERM; touch \"$1\"; exec /bin/sleep 30", "validation", running.path], validation: task)
125 }
126 let startedDeadline = Date().addingTimeInterval(5)
127 while !FileManager.default.fileExists(atPath: running.path) && Date() < startedDeadline { Thread.sleep(forTimeInterval: 0.01) }
128 try expect(FileManager.default.fileExists(atPath: running.path), "real validation child started")
129 let cancelledAt = Date()
130 task.cancel(); task.wait()
131 try expect(Date().timeIntervalSince(cancelledAt) < 5, "unresponsive verification process is killed and joined")
132
133 // Mount only this test's own tiny image. Cancellation inside the real
134 // mount scope must still execute hdiutil detach before completion.
135 let contents = root.appendingPathComponent("image-source")
136 try CageUpdateFiles.privateDirectory(contents)
137 try Data("fixture".utf8).write(to: contents.appendingPathComponent("marker"))
138 let archive = root.appendingPathComponent("fixture.dmg")
139 _ = try CageUpdateFiles.run("/usr/bin/hdiutil", ["create", "-size", "20m", "-fs", "HFS+", "-volname", "CageUpdateQA", "-srcfolder", contents.path, archive.path])
140 let mountTask = CageUpdateValidation()
141 try rejects("cancelled mounted verification") {
142 try CageUpdateFiles.withMountedImage(archive: archive, directory: root.appendingPathComponent("verification"), validation: mountTask) { mount in
143 try expect(FileManager.default.fileExists(atPath: mount.appendingPathComponent("marker").path), "test image mounted")
144 mountTask.cancel()
145 try mountTask.checkCancellation()
146 }
147 }
148 mountTask.finish(); mountTask.wait()
149 let mounts = try CageUpdateFiles.run("/usr/bin/hdiutil", ["info", "-plist"])
150 let info = try PropertyListSerialization.propertyList(from: mounts, format: nil) as? [String: Any]
151 let images = info?["images"] as? [[String: Any]] ?? []
152 try expect(!images.contains(where: { $0["image-path"] as? String == archive.path }), "cancellation detached its own image")
153
154 // A just-installed instance can be rolled back natively until the
155 // trusted workbench explicitly confirms its API initialization.
156 let savedEnvironment = ProcessInfo.processInfo.environment
157 let confirmation = UUID().uuidString
158 setenv("CAGE_UPDATE_CONFIRMATION", confirmation, 1)
159 setenv("CLAUDE_CAGE_CONFIG", root.appendingPathComponent("profile/config.json").path, 1)
160 defer {
161 for key in ["CAGE_UPDATE_CONFIRMATION", "CLAUDE_CAGE_CONFIG"] {
162 if let value = savedEnvironment[key] { setenv(key, value, 1) } else { unsetenv(key) }
163 }
164 }
165 let updater = CageAppUpdater(bundleURL: old, onChange: { _ in }, quit: {}, reconnect: {})
166 try expect(updater.awaitingInitialWorkbench, "newly installed uninitialized window permits native rollback termination")
167 updater.markLaunchReady()
168 try expect(!updater.awaitingInitialWorkbench, "initialized workbench keeps ordinary quit confirmation")
169 try expect(FileManager.default.fileExists(atPath: root.appendingPathComponent("profile/updates/launch-\(confirmation).json").path), "explicit workbench readiness writes installer acknowledgement")
170
171 let probeBundle = root.appendingPathComponent("retry-protocol.app")
172 let resources = probeBundle.appendingPathComponent("Contents/Resources")
173 try CageUpdateFiles.privateDirectory(resources)
174 let countFile = root.appendingPathComponent("retry-invocations")
175 let retryAt = ISO8601DateFormatter().string(from: Date().addingTimeInterval(3600))
176 let script = "#!/bin/sh\nprintf x >> '\(countFile.path)'\nprintf '%s\\n' '{\"phase\":\"failed\",\"message\":\"limited\",\"retryable\":true,\"retryAt\":\"\(retryAt)\"}'\nexit 1\n"
177 let probe = resources.appendingPathComponent("cage")
178 try Data(script.utf8).write(to: probe)
179 try FileManager.default.setAttributes([.posixPermissions: 0o700], ofItemAtPath: probe.path)
180 var received: [String: Any] = [:]
181 let limited = CageAppUpdater(bundleURL: probeBundle, onChange: { received = $0 }, quit: {}, reconnect: {})
182 _ = limited.handle("check")
183 let deadline = Date().addingTimeInterval(5)
184 while received["phase"] as? String != "failed" && Date() < deadline { _ = RunLoop.current.run(mode: .default, before: Date().addingTimeInterval(0.01)) }
185 // Drain the process-exit callback as well as the streamed failed state.
186 _ = RunLoop.current.run(mode: .default, before: Date().addingTimeInterval(0.1))
187 try expect(limited.handle("status")["retryAt"] as? String == retryAt, "native process-exit handling retained server retry deadline")
188 _ = limited.handle("check"); _ = limited.handle("install")
189 let invocationData = try Data(contentsOf: countFile)
190 try expect(String(data: invocationData, encoding: .utf8) == "x", "native menu or install bypassed cooldown")
191 print("PASS: native update failure retained retry deadline and blocked early check/install")
192
193 if CommandLine.arguments.count == 2 {
194 let signed = URL(fileURLWithPath: CommandLine.arguments[1])
195 let team = try CageUpdateFiles.signingInfo(signed, bundle: true)
196 let version = Bundle(url: signed)?.object(forInfoDictionaryKey: "CageVersion") as? String ?? ""
197 try CageUpdateFiles.verifyApp(signed, version: version, team: team, gatekeeper: false)
198 try rejects("different publisher refused") { _ = try CageUpdateFiles.signingInfo(signed, bundle: true, expectedTeam: "AAAAAAAAAA") }
199 let tampered = root.appendingPathComponent("tampered.app")
200 try FileManager.default.copyItem(at: signed, to: tampered)
201 let plist = tampered.appendingPathComponent("Contents/Info.plist")
202 try Data("tampered".utf8).write(to: plist)
203 try rejects("real signature tampering refused") { _ = try CageUpdateFiles.signingInfo(tampered, bundle: true, expectedTeam: team) }
204 print("PASS: real App architecture and Developer ID signature, wrong publisher, and tampered App checks")
205 }
206 print("PASS: absolute profile inheritance, personal data preservation, versions, containment, replacement/double-failure rollback, process cancellation, and temporary image cleanup")
207 }
208}