import Darwin import Foundation import ParcelCore import Synchronization import Testing @testable import ParcelPlatform @Suite struct SetupStoreTests { private func temporaryDirectory() throws -> URL { let directory = FileManager.default.temporaryDirectory.appendingPathComponent( UUID().uuidString, isDirectory: true) try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) return directory } private func remove(_ directory: URL) { do { try FileManager.default.removeItem(at: directory) } catch { Issue.record("Failed to remove temporary setup storage: \(error)") } } private func catalog() throws -> SetupCatalog { let display = DisplayID(rawValue: "setup-display") let key = WorkspaceKey(display: display, space: SpaceID(rawValue: 5)) let ids = [WindowID(rawValue: 11), WindowID(rawValue: 22)] let windows = ids.map { id in ManagedWindow( id: id, app: AppID(pid: 456, bundleID: "app.\(id.rawValue)"), title: "Private document \(id.rawValue)") } let workspace = Workspace(key: key, layout: .side, ratio: .twoThirds, order: ids, focus: ids[1]) let memory = try WorkspaceMemory.capture( State( displays: [Display(id: display, frame: Rect(width: 1800, height: 1200))], activeSpaces: [display: key.space], workspaces: [key: workspace], windows: Dictionary(uniqueKeysWithValues: windows.map { ($0.id, $0) })), titleSalt: Data(repeating: 3, count: 32)) return try SetupCatalog(setups: [ SavedSetup( name: "Zebra", emoji: "\u{1F5A5}\u{FE0F}", shortcut: "ctrl-alt-1", hideOtherApps: true, memory: memory), SavedSetup(name: "Alpha", hideOtherApps: false, memory: WorkspaceMemory()), ]) } private struct Storage: Encodable { let version: Int let setups: [SavedSetup] } private func encoded(_ catalog: SetupCatalog) throws -> Data { try JSONEncoder().encode(Storage(version: 1, setups: catalog.setups)) } private func corruption(_ operation: () throws -> Void) throws -> SetupStoreCorruptionError { do { try operation() Issue.record("Expected a visible corruption error") throw TestFailure.missingCorruption } catch let error as SetupStoreCorruptionError { return error } } private func mode(_ url: URL) throws -> Int { let attributes = try FileManager.default.attributesOfItem(atPath: url.path) return try #require(attributes[.posixPermissions] as? NSNumber).intValue } private enum TestFailure: Error, Equatable { case synchronization, missingCorruption } @Test func defaultLocationAndVersionAreStableAndRuntimeRejectsProductionIO() throws { #expect(SetupStore.currentVersion == 1) #expect( SetupStore.defaultFileURL == FileManager.default.homeDirectoryForCurrentUser .appendingPathComponent("Library/Application Support/dev.vinnymac.parcel/setups.json")) let store = SetupStore(fileURL: SetupStore.defaultFileURL) #expect(throws: SetupStoreError.defaultStoreUnavailableInTests) { try store.load() } #expect(throws: SetupStoreError.defaultStoreUnavailableInTests) { try store.save(SetupCatalog()) } } @Test func missingParentLoadsEmptyWithoutCreatingStorage() throws { let directory = try temporaryDirectory() defer { remove(directory) } let store = SetupStore( fileURL: directory.appendingPathComponent("nested/setups.json"), synchronizeDirectory: { _ in throw TestFailure.synchronization }) #expect(try store.load() == SetupCatalog()) #expect(try store.load().setups.isEmpty) #expect(try FileManager.default.contentsOfDirectory(atPath: directory.path).isEmpty) } @Test func roundTripPreservesOrderMetadataAndHMACTitleDigestsInPrivateJSON() throws { let directory = try temporaryDirectory() defer { remove(directory) } let store = SetupStore(fileURL: directory.appendingPathComponent("private/setups.json")) let expected = try catalog() try store.save(expected) #expect(try store.load() == expected) #expect(try SetupStore(fileURL: store.fileURL).load().setups.map(\.name) == ["Zebra", "Alpha"]) let text = try String(contentsOf: store.fileURL, encoding: .utf8) #expect(!text.contains("Private document")) #expect(!text.contains("pid")) #expect(text.contains("titleDigest")) #expect(text.contains("titleSalt")) #expect(text.contains("\"version\" : 1")) let memory = expected.setups[0].memory let digest = try #require(try memory.titleDigest(for: "Private document 11")) #expect(text.contains(digest)) #expect(memory.records[0].windows[0].titleDigest == digest) let parent = store.fileURL.deletingLastPathComponent() #expect(try mode(parent) == 0o700) #expect(try mode(store.fileURL) == 0o600) #expect(try mode(store.fileURL.appendingPathExtension("lock")) == 0o600) #expect( Set(try FileManager.default.contentsOfDirectory(atPath: parent.path)) == [ "setups.json", "setups.json.lock", ]) try store.save(SetupCatalog(setups: expected.setups.reversed())) #expect(try store.load().setups.map(\.id) == expected.setups.reversed().map(\.id)) } @Test(arguments: ["not json", "", #"{"setups":[]}"#, #"{"version":1}"#, #"{"version":1,"setups":{}}"#]) func corruptionPreservesOriginalAndPrivateBackupAndRetriesNeverDuplicateEvidence(contents: String) throws { let directory = try temporaryDirectory() defer { remove(directory) } let store = SetupStore(fileURL: directory.appendingPathComponent("setups.json")) let original = Data(contents.utf8) try original.write(to: store.fileURL) let first = try corruption { _ = try store.load() } #expect(first.backupURL != store.fileURL) #expect(first.backupURL.deletingLastPathComponent() == directory) #expect(first.backupURL.lastPathComponent.hasSuffix(".unreadable.json")) #expect(first.underlyingError is DecodingError) #expect(try Data(contentsOf: first.backupURL) == original) #expect(try Data(contentsOf: store.fileURL) == original) #expect(try mode(first.backupURL) == 0o600) for _ in 0..<3 { let loaded = try corruption { _ = try store.load() } let saved = try corruption { try store.save(SetupCatalog()) } #expect(loaded.backupURL == first.backupURL) #expect(saved.backupURL == first.backupURL) } let fresh = try corruption { _ = try SetupStore(fileURL: store.fileURL).load() } #expect(fresh.backupURL == first.backupURL) #expect(try FileManager.default.contentsOfDirectory(atPath: directory.path).count == 3) #expect(try Data(contentsOf: store.fileURL) == original) } @Test func invalidMetadataMemoryAndDuplicateIdentitiesArePreservedAsCorruption() throws { let directory = try temporaryDirectory() defer { remove(directory) } let store = SetupStore(fileURL: directory.appendingPathComponent("setups.json")) let expected = try catalog() var invalidName = expected.setups[0] invalidName.name = " " var invalidMemory = expected.setups[0] invalidMemory.memory = WorkspaceMemory(titleSalt: Data(repeating: 1, count: 2)) for setups in [[invalidName], [invalidMemory], [expected.setups[0], expected.setups[0]]] { let data = try JSONEncoder().encode(Storage(version: 1, setups: setups)) try data.write(to: store.fileURL) let error = try corruption { _ = try store.load() } #expect(error.underlyingError is SavedSetupError || error.underlyingError is WorkspaceMemoryError) #expect(try Data(contentsOf: error.backupURL) == data) #expect(try Data(contentsOf: store.fileURL) == data) } #expect( try FileManager.default.contentsOfDirectory(atPath: directory.path).filter { $0.hasSuffix(".unreadable.json") }.count == 3) } @Test func saveWithoutLoadAlsoBacksUpAndBlocksCorruptData() throws { let directory = try temporaryDirectory() defer { remove(directory) } let store = SetupStore(fileURL: directory.appendingPathComponent("setups.json")) let original = Data("original corrupt bytes".utf8) try original.write(to: store.fileURL) let error = try corruption { try store.save(SetupCatalog()) } #expect(try Data(contentsOf: error.backupURL) == original) #expect(try Data(contentsOf: store.fileURL) == original) #expect(try corruption { try store.save(SetupCatalog()) }.backupURL == error.backupURL) } @Test func explicitRepairRebaselinesRecoveryButDoesNotDeleteEvidence() throws { let directory = try temporaryDirectory() defer { remove(directory) } let store = SetupStore(fileURL: directory.appendingPathComponent("setups.json")) let original = Data("broken".utf8) try original.write(to: store.fileURL) let error = try corruption { _ = try store.load() } let repaired = try catalog() try encoded(repaired).write(to: store.fileURL) #expect(throws: SetupStoreError.concurrentModification) { try store.save(SetupCatalog()) } #expect(try store.load() == repaired) try store.save(SetupCatalog()) #expect(try store.load().setups.isEmpty) #expect(try Data(contentsOf: error.backupURL) == original) } @Test(arguments: [0, 2, 99, -1]) func unknownVersionIsRejectedBeforePayloadDecodeAndCannotBeOverwritten(version: Int) throws { let directory = try temporaryDirectory() defer { remove(directory) } let store = SetupStore(fileURL: directory.appendingPathComponent("setups.json")) let original = Data("{\"version\":\(version),\"setups\":null}".utf8) try original.write(to: store.fileURL) #expect(throws: SetupStoreError.unsupportedVersion(version)) { try store.save(SetupCatalog()) } #expect(throws: SetupStoreError.unsupportedVersion(version)) { try store.load() } #expect(throws: SetupStoreError.unsupportedVersion(version)) { try store.save(SetupCatalog()) } #expect(try Data(contentsOf: store.fileURL) == original) #expect( Set(try FileManager.default.contentsOfDirectory(atPath: directory.path)) == [ "setups.json", "setups.json.lock", ]) } @Test func existingReadableDirectoryFileAndLockPermissionsAreTightenedOnLoad() throws { let directory = try temporaryDirectory() defer { remove(directory) } let store = SetupStore(fileURL: directory.appendingPathComponent("setups.json")) let expected = try catalog() try encoded(expected).write(to: store.fileURL) let lock = store.fileURL.appendingPathExtension("lock") try Data().write(to: lock) for (url, permission) in [(directory, 0o755), (store.fileURL, 0o644), (lock, 0o666)] { try FileManager.default.setAttributes([.posixPermissions: permission], ofItemAtPath: url.path) } #expect(try store.load() == expected) #expect(try mode(directory) == 0o700) #expect(try mode(store.fileURL) == 0o600) #expect(try mode(lock) == 0o600) try store.save(expected) #expect(try mode(store.fileURL) == 0o600) } @Test func unreadableIsNotMissingAndCannotBeReplaced() throws { let directory = try temporaryDirectory() defer { remove(directory) } let store = SetupStore(fileURL: directory.appendingPathComponent("setups.json")) try store.save(catalog()) let original = try Data(contentsOf: store.fileURL) try FileManager.default.setAttributes([.posixPermissions: 0], ofItemAtPath: store.fileURL.path) #expect(geteuid() != 0) #expect(throws: (any Error).self) { try store.load() } #expect(throws: (any Error).self) { try store.save(SetupCatalog()) } try FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: store.fileURL.path) #expect(try Data(contentsOf: store.fileURL) == original) } @Test func failedStagedWriteRetainsOriginalAndCleansTemporaryFile() throws { let directory = try temporaryDirectory() defer { remove(directory) } let file = directory.appendingPathComponent("setups.json") let expected = try catalog() try SetupStore(fileURL: file).save(expected) let original = try Data(contentsOf: file) let store = SetupStore(fileURL: file, synchronizeFile: { _ in throw TestFailure.synchronization }) #expect(throws: TestFailure.synchronization) { try store.save(SetupCatalog()) } #expect(try Data(contentsOf: file) == original) #expect(try store.load() == expected) #expect( Set(try FileManager.default.contentsOfDirectory(atPath: directory.path)) == [ "setups.json", "setups.json.lock", ]) } @Test func failedRenameRetainsOriginalAndCleansTemporaryFile() throws { let directory = try temporaryDirectory() defer { remove(directory) } let store = SetupStore(fileURL: directory.appendingPathComponent("setups.json")) try store.save(catalog()) let original = try Data(contentsOf: store.fileURL) try #require(Darwin.chflags(store.fileURL.path, UInt32(UF_IMMUTABLE)) == 0) defer { if Darwin.chflags(store.fileURL.path, 0) != 0 { Issue.record("Failed to clear setup test immutable flag: \(errno)") } } #expect(throws: (any Error).self) { try store.save(SetupCatalog()) } #expect(try Data(contentsOf: store.fileURL) == original) #expect( Set(try FileManager.default.contentsOfDirectory(atPath: directory.path)) == [ "setups.json", "setups.json.lock", ]) } @Test func parentSyncHoldsSidecarLockAndFailedSyncKeepsCommittedRevision() throws { let directory = try temporaryDirectory() defer { remove(directory) } let file = directory.appendingPathComponent("setups.json") let store = SetupStore( fileURL: file, synchronizeDirectory: { descriptor in var info = stat() #expect(Darwin.fstat(descriptor, &info) == 0) #expect(info.st_mode & S_IFMT == S_IFDIR) let lock = Darwin.open(file.path + ".lock", O_RDWR) try #require(lock >= 0) #expect(flock(lock, LOCK_EX | LOCK_NB) == -1) #expect(errno == EWOULDBLOCK) #expect(Darwin.close(lock) == 0) throw TestFailure.synchronization }) let expected = try catalog() #expect(throws: TestFailure.synchronization) { try store.save(expected) } #expect(try SetupStore(fileURL: file).load() == expected) #expect(throws: TestFailure.synchronization) { try store.save(SetupCatalog()) } #expect(try store.load().setups.isEmpty) } @Test func backupSyncFailureStillReportsPreservedPathAndRetriesRemainBlocked() throws { let directory = try temporaryDirectory() defer { remove(directory) } let store = SetupStore( fileURL: directory.appendingPathComponent("setups.json"), synchronizeDirectory: { _ in throw TestFailure.synchronization }) let original = Data("broken".utf8) try original.write(to: store.fileURL) let error = try corruption { _ = try store.load() } #expect(error.underlyingError as? TestFailure == .synchronization) #expect(try Data(contentsOf: error.backupURL) == original) #expect(try corruption { _ = try store.load() }.backupURL == error.backupURL) #expect(try corruption { try store.save(SetupCatalog()) }.backupURL == error.backupURL) #expect(try Data(contentsOf: store.fileURL) == original) #expect(try FileManager.default.contentsOfDirectory(atPath: directory.path).count == 3) } @Test func staleWriterManualEditsAndDeletionAreDetectedAndCopiesShareRevision() throws { let directory = try temporaryDirectory() defer { remove(directory) } let file = directory.appendingPathComponent("setups.json") let first = SetupStore(fileURL: file) let stale = SetupStore(fileURL: file) _ = try stale.load() let expected = try catalog() try first.save(expected) let original = try Data(contentsOf: file) #expect(throws: SetupStoreError.concurrentModification) { try stale.save(SetupCatalog()) } #expect(try Data(contentsOf: file) == original) _ = try stale.load() try stale.save(SetupCatalog()) #expect(throws: SetupStoreError.concurrentModification) { try first.save(expected) } let copy = stale try copy.save(expected) try stale.save(SetupCatalog()) try encoded(expected).write(to: file) #expect(throws: SetupStoreError.concurrentModification) { try copy.save(SetupCatalog()) } _ = try copy.load() try FileManager.default.removeItem(at: file) #expect(throws: SetupStoreError.concurrentModification) { try stale.save(SetupCatalog()) } #expect(!FileManager.default.fileExists(atPath: file.path)) } private enum WriteResult: Sendable { case saved(SetupCatalog) case conflict case unexpected(String) } @Test func simultaneousWritersSerializeWithExactlyOneStaleWriter() async throws { let directory = try temporaryDirectory() defer { remove(directory) } let file = directory.appendingPathComponent("setups.json") let first = SetupStore(fileURL: file) let second = SetupStore(fileURL: file) _ = try first.load() _ = try second.load() let catalogs = [try catalog(), try SetupCatalog()] let results = await withTaskGroup(of: WriteResult.self) { group in for (store, catalog) in zip([first, second], catalogs) { group.addTask { do { try store.save(catalog) return .saved(catalog) } catch SetupStoreError.concurrentModification { return .conflict } catch { return .unexpected(String(describing: error)) } } } var results: [WriteResult] = [] for await result in group { results.append(result) } return results } var conflicts = 0 var winners: [SetupCatalog] = [] for result in results { switch result { case .saved(let catalog): winners.append(catalog) case .conflict: conflicts += 1 case .unexpected(let error): Issue.record("Unexpected setup write failure: \(error)") } } #expect(conflicts == 1) #expect(winners.count == 1) #expect(try SetupStore(fileURL: file).load() == #require(winners.first)) } @Test func revisionIsRecheckedAfterStagingForNonCooperatingExternalWrites() throws { let directory = try temporaryDirectory() defer { remove(directory) } let file = directory.appendingPathComponent("setups.json") let external = try encoded(catalog()) let store = SetupStore( fileURL: file, synchronizeFile: { descriptor in #expect(Darwin.fsync(descriptor) == 0) try external.write(to: file) }) _ = try store.load() #expect(throws: SetupStoreError.concurrentModification) { try store.save(SetupCatalog()) } #expect(try Data(contentsOf: file) == external) #expect( Set(try FileManager.default.contentsOfDirectory(atPath: directory.path)) == [ "setups.json", "setups.json.lock", ]) } @Test func invalidCatalogFailsBeforeCreatingStorage() throws { let directory = try temporaryDirectory() defer { remove(directory) } let store = SetupStore(fileURL: directory.appendingPathComponent("nested/setups.json")) var invalid = try catalog() invalid.setups[0].name = " " #expect(throws: SavedSetupError.invalidName) { try store.save(invalid) } #expect(try FileManager.default.contentsOfDirectory(atPath: directory.path).isEmpty) } @Test func nonFileAndDirectoryURLsAreRejected() throws { let remote = try #require(URL(string: "https://example.com/setups.json")) let directory = try temporaryDirectory() defer { remove(directory) } for url in [remote, directory] { let store = SetupStore(fileURL: url) #expect(throws: SetupStoreError.invalidFileURL) { try store.load() } #expect(throws: SetupStoreError.invalidFileURL) { try store.save(SetupCatalog()) } } } @Test func symlinkSourceParentAndSidecarNeverFollowTheirTargets() throws { let directory = try temporaryDirectory() defer { remove(directory) } let target = directory.appendingPathComponent("target.json") let original = Data("untouched".utf8) try original.write(to: target) let source = directory.appendingPathComponent("setups.json") try FileManager.default.createSymbolicLink(at: source, withDestinationURL: target) let store = SetupStore(fileURL: source) #expect(throws: (any Error).self) { try store.load() } #expect(throws: (any Error).self) { try store.save(SetupCatalog()) } try FileManager.default.removeItem(at: source) try FileManager.default.removeItem(at: source.appendingPathExtension("lock")) try FileManager.default.createSymbolicLink( at: source.appendingPathExtension("lock"), withDestinationURL: target) #expect(throws: (any Error).self) { try store.load() } #expect(throws: (any Error).self) { try store.save(SetupCatalog()) } let realParent = directory.appendingPathComponent("real", isDirectory: true) try FileManager.default.createDirectory(at: realParent, withIntermediateDirectories: false) let linkParent = directory.appendingPathComponent("link", isDirectory: true) try FileManager.default.createSymbolicLink(at: linkParent, withDestinationURL: realParent) let linked = SetupStore(fileURL: linkParent.appendingPathComponent("setups.json")) #expect(throws: (any Error).self) { try linked.load() } #expect(throws: (any Error).self) { try linked.save(SetupCatalog()) } #expect(try FileManager.default.contentsOfDirectory(atPath: realParent.path).isEmpty) #expect(try Data(contentsOf: target) == original) } @Test func fileParentAndNonRegularSourceRemainUntouched() throws { let directory = try temporaryDirectory() defer { remove(directory) } let blocker = directory.appendingPathComponent("blocker") let original = Data("untouched".utf8) try original.write(to: blocker) let blocked = SetupStore(fileURL: blocker.appendingPathComponent("setups.json")) #expect(throws: (any Error).self) { try blocked.load() } #expect(throws: (any Error).self) { try blocked.save(SetupCatalog()) } #expect(try Data(contentsOf: blocker) == original) let fifo = directory.appendingPathComponent("setups.json") try #require(Darwin.mkfifo(fifo.path, 0o600) == 0) let store = SetupStore(fileURL: fifo) #expect(throws: (any Error).self) { try store.load() } #expect(throws: (any Error).self) { try store.save(SetupCatalog()) } var info = stat() #expect(Darwin.lstat(fifo.path, &info) == 0) #expect(info.st_mode & S_IFMT == S_IFIFO) } }