|
| 1 | +import Foundation |
| 2 | +import Security |
| 3 | +import Testing |
| 4 | +@testable import OpenClaw |
| 5 | + |
| 6 | +@MainActor |
| 7 | +struct AppStateIsolationTests { |
| 8 | + @Test |
| 9 | + func `preview constructor uses launch namespace and owned config`() async throws { |
| 10 | + // Fail before touching defaults when the bundle was launched without its resource owner. |
| 11 | + let profile = try #require(AppProfile.current.name) |
| 12 | + try #require(profile.hasPrefix("test-")) |
| 13 | + let suiteName = try #require(AppProfile.current.defaultsSuiteName) |
| 14 | + let fm = FileManager() |
| 15 | + let home = try #require(OpenClawEnv.path("HOME")) |
| 16 | + // Check the platform's actual default before any fixture or catalog writes. |
| 17 | + // A profile name alone cannot keep Security away from an operator's Keychain. |
| 18 | + var defaultKeychain: SecKeychain? |
| 19 | + try #require(SecKeychainCopyDefault(&defaultKeychain) == errSecSuccess) |
| 20 | + let keychain = try #require(defaultKeychain) |
| 21 | + var pathBytes = [CChar](repeating: 0, count: 4096) |
| 22 | + var pathLength = UInt32(pathBytes.count) |
| 23 | + try #require(SecKeychainGetPath(keychain, &pathLength, &pathBytes) == errSecSuccess) |
| 24 | + let keychainPath = try #require(String( |
| 25 | + bytes: pathBytes.prefix(Int(pathLength)).map { UInt8(bitPattern: $0) }, |
| 26 | + encoding: .utf8)) |
| 27 | + let keychainURL = URL(fileURLWithPath: keychainPath).resolvingSymlinksInPath() |
| 28 | + try #require(keychainURL.deletingLastPathComponent().path == |
| 29 | + URL(fileURLWithPath: home).appendingPathComponent("Library/Keychains").resolvingSymlinksInPath().path) |
| 30 | + let fixture = fm.temporaryDirectory.appendingPathComponent("app-state-\(UUID().uuidString)") |
| 31 | + try fm.createDirectory(at: fixture, withIntermediateDirectories: true) |
| 32 | + defer { try? fm.removeItem(at: fixture) } |
| 33 | + let configURL = fixture.appendingPathComponent("openclaw.json") |
| 34 | + let seededKeys = [ |
| 35 | + iconAnimationsEnabledKey, |
| 36 | + showDockIconKey, |
| 37 | + talkPhaseSoundsEnabledKey, |
| 38 | + talkShiftToStopEnabledKey, |
| 39 | + heartbeatsEnabledKey, |
| 40 | + iconOverrideKey, |
| 41 | + ] |
| 42 | + var defaults = Dictionary(uniqueKeysWithValues: seededKeys.map { ($0, nil as Any?) }) |
| 43 | + defaults[swabbleEnabledKey] = false |
| 44 | + defaults[talkEnabledKey] = false |
| 45 | + defaults[talkRealtimeRelayEnabledKey] = true |
| 46 | + |
| 47 | + let launchState = try await TestIsolation.withEnvValues([:]) { |
| 48 | + let home = try #require(OpenClawEnv.path("HOME")) |
| 49 | + #expect(OpenClawEnv.path("CFFIXED_USER_HOME") == home) |
| 50 | + let root = URL(fileURLWithPath: home).deletingLastPathComponent() |
| 51 | + #expect(fm.homeDirectoryForCurrentUser.resolvingSymlinksInPath().path == |
| 52 | + URL(fileURLWithPath: home).resolvingSymlinksInPath().path) |
| 53 | + // Foundation uses Darwin's per-user temp directory independently of TMPDIR. |
| 54 | + // Fixtures there remain test-owned on the disposable worker. |
| 55 | + let tmp = try #require(OpenClawEnv.path("TMPDIR")) |
| 56 | + #expect(URL(fileURLWithPath: tmp).resolvingSymlinksInPath().path == |
| 57 | + root.appendingPathComponent("tmp").resolvingSymlinksInPath().path) |
| 58 | + #expect(OpenClawPaths.stateDirURL == root.appendingPathComponent("state", isDirectory: true)) |
| 59 | + #expect(OpenClawPaths.configURL == OpenClawPaths.stateDirURL.appendingPathComponent("openclaw.json")) |
| 60 | + return OpenClawPaths.stateDirURL |
| 61 | + } |
| 62 | + |
| 63 | + let fixtureState = try await TestIsolation.withIsolatedState( |
| 64 | + env: ["OPENCLAW_CONFIG_PATH": configURL.path], |
| 65 | + defaults: defaults) |
| 66 | + { |
| 67 | + let preferences = try #require(UserDefaults(suiteName: suiteName)) |
| 68 | + // Other tests may already have constructed AppState. Remove only these keys |
| 69 | + // under the cooperative lock instead of assuming this test runs first. |
| 70 | + for key in seededKeys { |
| 71 | + #expect(preferences.object(forKey: key) == nil) |
| 72 | + } |
| 73 | + #expect(!fm.fileExists(atPath: configURL.path)) |
| 74 | + let absent = AppState(preview: true) |
| 75 | + #expect(absent.iconAnimationsEnabled) |
| 76 | + #expect(absent.showDockIcon) |
| 77 | + #expect(absent.talkPhaseSoundsEnabled) |
| 78 | + #expect(absent.talkShiftToStopEnabled) |
| 79 | + #expect(absent.heartbeatsEnabled) |
| 80 | + #expect(absent.iconOverride == .system) |
| 81 | + #expect(absent.talkRealtimeRelayEnabled) |
| 82 | + for key in seededKeys.dropLast() { |
| 83 | + #expect(preferences.object(forKey: key) as? Bool == true) |
| 84 | + } |
| 85 | + #expect(preferences.string(forKey: iconOverrideKey) == IconOverrideSelection.system.rawValue) |
| 86 | + #expect(!fm.fileExists(atPath: configURL.path)) |
| 87 | + |
| 88 | + let stateDirectory = OpenClawPaths.stateDirURL |
| 89 | + #expect(stateDirectory != launchState) |
| 90 | + #expect(stateDirectory.path.hasPrefix(fm.temporaryDirectory.path)) |
| 91 | + #expect(OpenClawConfigFile.saveDict([ |
| 92 | + "gateway": [ |
| 93 | + "mode": "remote", |
| 94 | + "remote": [ |
| 95 | + "transport": "direct", |
| 96 | + "url": "wss://fixture.example.invalid:9443", |
| 97 | + ], |
| 98 | + ], |
| 99 | + ])) |
| 100 | + preferences.set(false, forKey: showDockIconKey) |
| 101 | + let configured = AppState(preview: true) |
| 102 | + #expect(!configured.showDockIcon) |
| 103 | + #expect(configured.connectionMode == .remote) |
| 104 | + #expect(configured.remoteTransport == .direct) |
| 105 | + #expect(configured.remoteUrl == "wss://fixture.example.invalid:9443") |
| 106 | + #expect(AppProfile.current.name == profile) |
| 107 | + |
| 108 | + // Catalog reads commit legacy migration through SecItemAdd on a fresh Keychain. |
| 109 | + let catalog = try await MacGatewayProfileStore().catalogProfiles() |
| 110 | + #expect(catalog.count == 1) |
| 111 | + let migrated = try #require(catalog.first) |
| 112 | + #expect(migrated.profile.url.absoluteString == "wss://fixture.example.invalid:9443/") |
| 113 | + #expect(!migrated.canPromote) |
| 114 | + // A fresh store must read the committed registry, not the first actor's cache. |
| 115 | + #expect(try await MacGatewayProfileStore().catalogProfiles() == catalog) |
| 116 | + |
| 117 | + // Preview still reads config; malformed input must keep its snapshot and audit in owned paths. |
| 118 | + try Data("{ invalid fixture".utf8).write(to: configURL) |
| 119 | + _ = AppState(preview: true) |
| 120 | + let auditURL = stateDirectory.appendingPathComponent("logs/config-audit.jsonl") |
| 121 | + let audit = try String(contentsOf: auditURL, encoding: .utf8) |
| 122 | + #expect(audit.contains("config.write")) |
| 123 | + #expect(audit.contains("config.observe")) |
| 124 | + #expect(try fm.contentsOfDirectory(atPath: fixture.path).contains { |
| 125 | + $0.hasPrefix("openclaw.json.clobbered.") |
| 126 | + }) |
| 127 | + return stateDirectory |
| 128 | + } |
| 129 | + #expect(!fm.fileExists(atPath: fixtureState.path)) |
| 130 | + await TestIsolation.withEnvValues([:]) { |
| 131 | + #expect(OpenClawPaths.stateDirURL == launchState) |
| 132 | + #expect(fm.fileExists(atPath: launchState.path)) |
| 133 | + } |
| 134 | + } |
| 135 | + |
| 136 | + @Test |
| 137 | + func `config fixture cleans audit after throwing body`() async throws { |
| 138 | + enum FixtureError: Error { |
| 139 | + case expected |
| 140 | + } |
| 141 | + let fm = FileManager() |
| 142 | + let configPath = TestIsolation.tempConfigPath() |
| 143 | + defer { try? fm.removeItem(atPath: configPath) } |
| 144 | + var fixtureState: URL? |
| 145 | + do { |
| 146 | + try await TestIsolation.withEnvValues(["OPENCLAW_CONFIG_PATH": configPath]) { |
| 147 | + fixtureState = OpenClawPaths.stateDirURL |
| 148 | + #expect(OpenClawConfigFile.saveDict(["gateway": ["mode": "local"]])) |
| 149 | + await Task.yield() |
| 150 | + #expect(fm.fileExists(atPath: OpenClawPaths.stateDirURL |
| 151 | + .appendingPathComponent("logs/config-audit.jsonl").path)) |
| 152 | + throw FixtureError.expected |
| 153 | + } |
| 154 | + } catch FixtureError.expected {} |
| 155 | + let removed = try #require(fixtureState) |
| 156 | + #expect(!fm.fileExists(atPath: removed.path)) |
| 157 | + } |
| 158 | +} |
0 commit comments