import Foundation import ParcelConfig import Testing @testable import ParcelRealityTests @Suite struct SetupRealityTests { private let applicationURL = URL(fileURLWithPath: "/System/Applications/Notes.app") private let launchDate = Date(timeIntervalSinceReferenceDate: 123_456_789.1234567) private let pid: Int32 = 30170 @Test func freshReturnedNotesLaunchPreservesExactLiveBirthIdentity() throws { let receipt = try claim(launch()) #expect(receipt.pid == pid) #expect(receipt.app == .notes) #expect(receipt.launchDate == launchDate) #expect(receipt.preexistingPIDs == [30150, 30159]) #expect(receipt.discardStrategy == .forceTerminateWithoutSaving) try receipt.validateDiscardIdentity( pid: pid, bundleID: RealApp.notes.bundleID, bundleURL: applicationURL, launchDate: launchDate, isTerminated: false) } @Test(arguments: [Int32(-1), 0, 30150, 30159]) func invalidOrPreviouslyObservedPIDsNeverBecomeOwned(_ processID: Int32) { #expect(throws: RealityError.self) { try claim(launch(pid: processID)) } } @Test func formerlyOwnedNotesPIDIsRejectedEvenWhenMissingFromWireBaseline() { #expect(throws: RealityError.self) { try claim(launch(), baseline: [pid]) } } @Test func receiptCannotClaimAnExistingAppOrAForeignRequestedBundle() { #expect(throws: RealityError.self) { try claim(launch(requestedBundleID: RealApp.textEdit.bundleID)) } #expect(throws: RealityError.self) { try claim(launch(bundleID: RealApp.textEdit.bundleID)) } #expect(throws: RealityError.self) { try claim(launch(bundleID: nil)) } #expect(throws: RealityError.self) { try claim(launch(isTerminated: true)) } } @Test( arguments: [ URL(fileURLWithPath: "/Applications/Notes.app"), URL(string: "https://example.org/Notes.app")!, ]) func receiptRejectsDifferentOrNonlocalApplicationPaths(_ url: URL) { #expect(throws: RealityError.self) { try claim(launch(requestedURL: url)) } #expect(throws: RealityError.self) { try claim(launch(bundleURL: url)) } } @Test func missingReturnedBundlePathCannotProveOwnership() { #expect(throws: RealityError.self) { try claim(launch(bundleURL: nil)) } } @Test func canonicalRequestedAndReturnedApplicationPathsAreAccepted() throws { let alternate = URL(fileURLWithPath: "/System/Applications/../Applications/Notes.app") let receipt = try claim(launch(requestedURL: alternate, bundleURL: alternate)) #expect(receipt.applicationURL == applicationURL) } @Test func missingOrChangedLiveLaunchDateRejectsPIDReuse() { #expect(throws: RealityError.self) { try claim(launch(), liveDate: nil) } #expect(throws: RealityError.self) { try claim(launch(), liveDate: launchDate.addingTimeInterval(1)) } } @Test func missingOrNonfiniteWireLaunchDateCannotAuthorizeOwnership() { for timestamp: Double? in [nil, .nan, .infinity, -.infinity] { #expect(throws: RealityError.self) { try claim(launch(timestamp: timestamp)) } } } @Test func launchMustFallInsideTheActualSetupOpenRequestInterval() { let receipt = launch() #expect(throws: RealityError.self) { try receipt.notesReceipt( applicationURL: applicationURL, preexistingPIDs: [], requestedAt: launchDate.addingTimeInterval(1), respondedAt: launchDate.addingTimeInterval(2), liveLaunchDate: launchDate) } #expect(throws: RealityError.self) { try receipt.notesReceipt( applicationURL: applicationURL, preexistingPIDs: [], requestedAt: launchDate.addingTimeInterval(-2), respondedAt: launchDate.addingTimeInterval(-1), liveLaunchDate: launchDate) } #expect(throws: RealityError.self) { try receipt.notesReceipt( applicationURL: applicationURL, preexistingPIDs: [], requestedAt: launchDate.addingTimeInterval(1), respondedAt: launchDate.addingTimeInterval(-1), liveLaunchDate: launchDate) } } @Test func setupOpenRequiresExactlyOneActualNotesLaunchReceipt() throws { let wire = try JSONEncoder().encode([launch()]) let launches = String(decoding: wire, as: UTF8.self) let source = "{\"accepted\":true,\"launches\":\(launches)}" let receipt = try JSONDecoder().decode(SetupOpenReceipt.self, from: Data(source.utf8)) #expect(try receipt.notesLaunch().pid == pid) #expect(throws: RealityError.self) { try SetupOpenReceipt(accepted: true, launches: []).notesLaunch() } #expect(throws: RealityError.self) { try SetupOpenReceipt(accepted: false, launches: [launch()]).notesLaunch() } #expect(throws: RealityError.self) { try SetupOpenReceipt(accepted: true, launches: [launch(), launch()]).notesLaunch() } #expect(throws: RealityError.self) { try SetupOpenReceipt(accepted: true, launches: [launch(requestedBundleID: RealApp.textEdit.bundleID)]) .notesLaunch() } } @Test func missingLaunchProvenanceDoesNotFallBackToProcessDiscovery() { #expect(throws: DecodingError.self) { try JSONDecoder().decode(SetupOpenReceipt.self, from: Data(#"{"accepted":true}"#.utf8)) } } @Test(arguments: [false, true]) func persistedHideSettingMustExactlyMatchTheScenario(_ hideOtherApps: Bool) throws { let source = "{\"version\":1,\"setups\":[{\"name\":\"owned-columns\",\"hideOtherApps\":\(hideOtherApps)}]}" try SetupRealitySafety.requireHideSetting( Data(source.utf8), name: "owned-columns", hideOtherApps: hideOtherApps) #expect(throws: RealityError.self) { try SetupRealitySafety.requireHideSetting( Data(source.utf8), name: "owned-columns", hideOtherApps: !hideOtherApps) } } @Test( arguments: [ #"{"version":1,"setups":[{"name":"owned-columns","hideOtherApps":true}]}"#, #"{"version":1,"setups":[{"name":"owned-columns"}]}"#, #"{"version":1,"setups":[{"name":"other","hideOtherApps":false}]}"#, #"{"version":1,"setups":[]}"#, #"{"version":2,"setups":[{"name":"owned-columns","hideOtherApps":false}]}"#, #"{"version":1,"setups":[{"name":"owned-columns","hideOtherApps":false},{"name":"other","hideOtherApps":false}]}"#, ]) func unsafeMissingOrUnexpectedCatalogNeverAllowsSetupOpen(_ source: String) { #expect(throws: (any Error).self) { try SetupRealitySafety.requireHideSetting(Data(source.utf8), name: "owned-columns", hideOtherApps: false) } } @Test func restoredFramesRequireEachExactOwnedIdentityAndItsSavedPosition() throws { let textEdit = OwnedWindow(app: .textEdit, pid: 10, id: 100) let notes = OwnedWindow(app: .notes, pid: 20, id: 200) let left = ScreenRect(x: 16, y: 40, width: 500, height: 800) let right = ScreenRect(x: 528, y: 40, width: 500, height: 800) let rows = [row(textEdit, left), row(notes, right)] #expect(try SetupRealitySafety.restoredFrames(rows, textEdit: textEdit, notes: notes, saved: [left, right])) #expect(try !SetupRealitySafety.restoredFrames(rows, textEdit: textEdit, notes: notes, saved: [right, left])) #expect(try !SetupRealitySafety.restoredFrames(rows, textEdit: textEdit, notes: notes, saved: [left])) #expect( try !SetupRealitySafety.restoredFrames( Array(rows.prefix(1)), textEdit: textEdit, notes: notes, saved: [left, right])) #expect( try !SetupRealitySafety.restoredFrames( [rows[0], row(OwnedWindow(app: .notes, pid: 30, id: notes.id), right)], textEdit: textEdit, notes: notes, saved: [left, right])) #expect( try !SetupRealitySafety.restoredFrames( [rows[0], row(notes, right, onscreen: false)], textEdit: textEdit, notes: notes, saved: [left, right])) } @Test func foregroundFocusDoesNotRequireGlobalFrontmostCGOrder() { let textEdit = OwnedWindow(app: .textEdit, pid: 10, id: 100) let notes = OwnedWindow(app: .notes, pid: 20, id: 200) let frame = ScreenRect(x: 16, y: 54, width: 734, height: 854) let rows = [row(notes, frame), row(OwnedWindow(app: .textEdit, pid: 30, id: 300), frame), row(textEdit, frame)] #expect(SetupRealitySafety.focusedWindow(rows, window: textEdit, foregroundPID: textEdit.pid)) #expect(!SetupRealitySafety.focusedWindow(rows, window: notes, foregroundPID: textEdit.pid)) } @Test(arguments: [Int32?.none, 20, 30]) func CGOrderCannotSubstituteForExactForegroundApplication(_ foregroundPID: Int32?) { let textEdit = OwnedWindow(app: .textEdit, pid: 10, id: 100) let frame = ScreenRect(x: 16, y: 54, width: 734, height: 854) #expect( !SetupRealitySafety.focusedWindow([row(textEdit, frame)], window: textEdit, foregroundPID: foregroundPID)) } @Test func foregroundFocusRejectsWrongWindowOrReusedCGIdentity() { let textEdit = OwnedWindow(app: .textEdit, pid: 10, id: 100) let other = OwnedWindow(app: .textEdit, pid: textEdit.pid, id: 101) let frame = ScreenRect(x: 16, y: 54, width: 734, height: 854) #expect( !SetupRealitySafety.focusedWindow( [row(other, frame), row(textEdit, frame)], window: textEdit, foregroundPID: textEdit.pid)) #expect( !SetupRealitySafety.focusedWindow( [row(OwnedWindow(app: .textEdit, pid: 20, id: textEdit.id), frame)], window: textEdit, foregroundPID: textEdit.pid)) #expect(!SetupRealitySafety.focusedWindow([], window: textEdit, foregroundPID: textEdit.pid)) } @Test func foregroundFocusRequiresAnOnscreenLayerZeroWindow() { let textEdit = OwnedWindow(app: .textEdit, pid: 10, id: 100) let frame = ScreenRect(x: 16, y: 54, width: 734, height: 854) let overlay = RealWindow(id: 101, pid: textEdit.pid, frame: frame, layer: 3, onscreen: true, alpha: 1) #expect( SetupRealitySafety.focusedWindow( [overlay, row(textEdit, frame)], window: textEdit, foregroundPID: textEdit.pid)) #expect( !SetupRealitySafety.focusedWindow( [row(textEdit, frame, onscreen: false)], window: textEdit, foregroundPID: textEdit.pid)) #expect( !SetupRealitySafety.focusedWindow( [RealWindow(id: textEdit.id, pid: textEdit.pid, frame: frame, layer: 3, onscreen: true, alpha: 1)], window: textEdit, foregroundPID: textEdit.pid)) } @Test(arguments: ["setups", "setups-hide"]) func bothSetupModesAreRegisteredExactlyOnce(_ name: String) { #expect(RealityScenario.all.filter { $0.name == name }.count == 1) } @Test func throwawayCalculatorIsExplicitlyIgnoredInsteadOfCapturedAsDefaultFloating() throws { let source = "version = 1\n" + SetupRealitySafety.calculatorIgnoreRule let result = ConfigValidator.validate(try TOMLParser.parse(source)) #expect(result.diagnostics.isEmpty) let configuration = try #require(result.configuration) #expect(configuration.rules == [RuleConfiguration(bundleID: RealApp.calculator.bundleID, action: .ignore)]) } @Test func setupApplicationsMustExcludeTheHideTargetAndEveryUnownedApp() throws { let owned = [RealApp.textEdit.bundleID, RealApp.notes.bundleID] try SetupRealitySafety.requireOwnedApplications(catalog(applications: owned), name: "owned-columns") for applications in [ [], [RealApp.textEdit.bundleID], owned + [RealApp.calculator.bundleID], owned + ["dev.unowned"], ] { #expect(throws: RealityError.self) { try SetupRealitySafety.requireOwnedApplications( catalog(applications: applications), name: "owned-columns") } } #expect(throws: RealityError.self) { try SetupRealitySafety.requireOwnedApplications(catalog(applications: owned), name: "another-setup") } #expect(throws: RealityError.self) { try SetupRealitySafety.requireOwnedApplications( Data(#"{"version":1,"setups":[{"name":"owned-columns","hideOtherApps":true}]}"#.utf8), name: "owned-columns") } } @Test func hideAllowlistIncludesTheExactOwnedPIDAndBirthTimestamp() throws { let window = OwnedWindow(app: .calculator, pid: pid, id: 300) let identity = try SetupHideIdentity(receipt: calculatorLaunch(), window: window) #expect(identity.pid == pid) #expect(identity.launchDate == launchDate.timeIntervalSince1970) let wire = try JSONEncoder().encode([identity]) #expect(try JSONDecoder().decode([SetupHideIdentity].self, from: wire) == [identity]) #expect(String(decoding: try JSONEncoder().encode([SetupHideIdentity]()), as: UTF8.self) == "[]") } @Test(arguments: [nil, Date(timeIntervalSince1970: .infinity), Date(timeIntervalSince1970: .nan)]) func hideAllowlistRejectsMissingOrNonfiniteBirthIdentity(_ date: Date?) { #expect(throws: RealityError.self) { try SetupHideIdentity( receipt: calculatorLaunch(date: date), window: OwnedWindow(app: .calculator, pid: pid, id: 300)) } } @Test func hideAllowlistNeverUsesAnUnownedReceiptOrAnUnrelatedWindow() { let window = OwnedWindow(app: .calculator, pid: pid, id: 300) #expect(throws: RealityError.self) { try SetupHideIdentity(receipt: calculatorLaunch(preexistingPIDs: [pid]), window: window) } #expect(throws: RealityError.self) { try SetupHideIdentity(receipt: calculatorLaunch(isTerminated: true), window: window) } for other in [ OwnedWindow(app: .calculator, pid: pid + 1, id: window.id), OwnedWindow(app: .calculator, pid: pid, id: 0), OwnedWindow(app: .notes, pid: pid, id: window.id), ] { #expect(throws: RealityError.self) { try SetupHideIdentity(receipt: calculatorLaunch(), window: other) } } #expect(throws: RealityError.self) { try SetupHideIdentity(receipt: claim(launch()), window: OwnedWindow(app: .notes, pid: pid, id: 300)) } } @Test func ownedVisibilityAuthorizationRejectsPIDReuseBeforeCleanup() throws { let receipt = calculatorLaunch() try receipt.validateDiscardIdentity( pid: pid, bundleID: RealApp.calculator.bundleID, bundleURL: receipt.applicationURL, launchDate: launchDate, isTerminated: false) #expect(throws: RealityError.self) { try receipt.validateDiscardIdentity( pid: pid, bundleID: RealApp.calculator.bundleID, bundleURL: receipt.applicationURL, launchDate: launchDate.addingTimeInterval(1), isTerminated: false) } } @Test func hideReadbackRequiresBothHiddenPropertyAndNoVisibleOwnedCGWindows() { let window = OwnedWindow(app: .calculator, pid: pid, id: 300) let frame = ScreenRect(x: 40, y: 40, width: 300, height: 400) let visible = row(window, frame) #expect(SetupOwnedVisibility.hiddenReadback([], window: window, hidden: true)) #expect(!SetupOwnedVisibility.hiddenReadback([], window: window, hidden: false)) #expect(!SetupOwnedVisibility.hiddenReadback([visible], window: window, hidden: true)) #expect( SetupOwnedVisibility.hiddenReadback([row(window, frame, onscreen: false)], window: window, hidden: true)) let anotherOwnedWindow = row(OwnedWindow(app: .calculator, pid: pid, id: 301), frame) #expect(!SetupOwnedVisibility.hiddenReadback([anotherOwnedWindow], window: window, hidden: true)) let unrelated = row(OwnedWindow(app: .notes, pid: pid + 1, id: window.id), frame) #expect(SetupOwnedVisibility.hiddenReadback([unrelated], window: window, hidden: true)) } @Test func visibilityRestorationRequiresExactCGIdentityAndStartingFrame() { let window = OwnedWindow(app: .calculator, pid: pid, id: 300) let frame = ScreenRect(x: 40, y: 40, width: 300, height: 400) #expect( SetupOwnedVisibility.visibleReadback( [row(window, frame)], window: window, hidden: false, startingFrame: frame)) for rows in [ [], [row(window, frame, onscreen: false)], [row(OwnedWindow(app: .calculator, pid: pid + 1, id: window.id), frame)], [row(OwnedWindow(app: .calculator, pid: pid, id: window.id + 1), frame)], [row(window, ScreenRect(x: 400, y: 400, width: 300, height: 400))], ] { #expect(!SetupOwnedVisibility.visibleReadback(rows, window: window, hidden: false, startingFrame: frame)) } #expect( !SetupOwnedVisibility.visibleReadback( [row(window, frame)], window: window, hidden: true, startingFrame: frame)) } private func calculatorLaunch( date: Date? = Date(timeIntervalSinceReferenceDate: 123_456_789.1234567), preexistingPIDs: [Int32] = [], isTerminated: Bool = false ) -> RealAppLaunchReceipt { let url = URL(fileURLWithPath: "/System/Applications/Calculator.app") return RealAppLaunchReceipt( app: .calculator, applicationURL: url, preexistingPIDs: preexistingPIDs, pid: pid, bundleID: RealApp.calculator.bundleID, bundleURL: url, isTerminated: isTerminated, launchDate: date) } private func catalog(applications: [String]) -> Data { let windows = applications.map { "{\"bundleID\":\"\($0)\"}" }.joined(separator: ",") return Data( "{\"version\":1,\"setups\":[{\"name\":\"owned-columns\",\"hideOtherApps\":true,\"memory\":{\"records\":[{\"windows\":[\(windows)]}]}}]}" .utf8) } private func launch( pid: Int32 = 30170, requestedBundleID: String = RealApp.notes.bundleID, requestedURL: URL = URL(fileURLWithPath: "/System/Applications/Notes.app"), bundleID: String? = RealApp.notes.bundleID, bundleURL: URL? = URL(fileURLWithPath: "/System/Applications/Notes.app"), timestamp: Double? = Date(timeIntervalSinceReferenceDate: 123_456_789.1234567).timeIntervalSince1970, isTerminated: Bool = false ) -> SetupLaunchReceipt { SetupLaunchReceipt( requestedBundleID: requestedBundleID, applicationURL: requestedURL, preexistingPIDs: [30159], pid: pid, bundleID: bundleID, bundleURL: bundleURL, launchDate: timestamp, isTerminated: isTerminated) } private func claim( _ receipt: SetupLaunchReceipt, baseline: Set = [30150], liveDate: Date? = Date(timeIntervalSinceReferenceDate: 123_456_789.1234567) ) throws -> RealAppLaunchReceipt { try receipt.notesReceipt( applicationURL: applicationURL, preexistingPIDs: baseline, requestedAt: launchDate.addingTimeInterval(-1), respondedAt: launchDate.addingTimeInterval(1), liveLaunchDate: liveDate) } private func row(_ window: OwnedWindow, _ frame: ScreenRect, onscreen: Bool = true) -> RealWindow { RealWindow(id: window.id, pid: window.pid, frame: frame, layer: 0, onscreen: onscreen, alpha: 1) } }