SPB Git

Repository Public License

GhostAndLifecycleTests.swift 27.4 KB 457 lines swift

1import Foundation2import NavigatorCore3import Testing4@testable import Persistence56@Suite struct GhostTests {7    /// Asserts that `body` throws `ghostWriteRejected`.8    private func expectGhostRejection(_ what: String, _ body: () async throws -> Void) async {9        do {10            try await body()11            Issue.record("\(what): a ghost write was accepted")12        } catch let error as PersistenceError {13            if case .ghostWriteRejected = error { return }14            Issue.record("\(what): expected ghostWriteRejected, got \(error)")15        } catch {16            Issue.record("\(what): unexpected error \(error)")17        }18    }1920    @Test func everyWritePathRejectsGhostData() async throws {21        let fixture = try await Fixture.make()22        let database = fixture.database23        let ghost = Profile(name: "Ghost", kind: .ghost, createdAt: day())24        let ghostSpace = OrbitSpace(profileID: ghost.id, name: "Private", createdAt: day(), updatedAt: day())25        let ghostWindow = BrowserWindow(spaceID: ghostSpace.id)26        let ghostTab = Tab(windowID: ghostWindow.id, spaceID: ghostSpace.id, url: url("https://secret.example/"),27                           title: "Secret", createdAt: day(), lastActiveAt: day())28        let ghostGroup = TabGroup(spaceID: ghostSpace.id, name: "Secret group")29        // The app declares what it created for the ghost session.30        database.ghosts.declare(profile: ghost.id, spaces: [ghostSpace.id], windows: [ghostWindow.id])31        let secretURL = url("https://secret.example/page")32        let origin = WebOrigin(scheme: "https", host: "secret.example")3334        await expectGhostRejection("profile") { try await database.profiles.save(ghost) }35        await expectGhostRejection("space") { try await database.spaces.save(ghostSpace) }36        await expectGhostRejection("window") { try await database.windows.save(ghostWindow) }37        await expectGhostRejection("tab") { try await database.tabs.save(ghostTab) }38        await expectGhostRejection("tab group") { try await database.tabGroups.save(ghostGroup) }39        await expectGhostRejection("session window") { try await database.session.apply([.saveWindow(ghostWindow)]) }40        await expectGhostRejection("session tab") { try await database.session.apply([.saveTab(ghostTab)]) }41        await expectGhostRejection("session group") { try await database.session.apply([.saveGroup(ghostGroup)]) }42        await expectGhostRejection("session replace") {43            try await database.session.replaceOpenState(windows: [ghostWindow], tabs: [ghostTab], groups: [ghostGroup])44        }45        await expectGhostRejection("history") {46            try await database.history.recordVisit(NavigationEntry(profileID: ghost.id, url: secretURL, title: "Secret"))47        }48        await expectGhostRejection("history in a ghost space") {49            try await database.history.recordVisit(NavigationEntry(profileID: fixture.profile.id, spaceID: ghostSpace.id, url: secretURL))50        }51        await expectGhostRejection("bookmark save") {52            try await database.bookmarks.save(Bookmark(profileID: ghost.id, title: "Secret", url: secretURL))53        }54        await expectGhostRejection("bookmark append") {55            try await database.bookmarks.append(Bookmark(profileID: ghost.id, title: "Secret", url: secretURL))56        }57        await expectGhostRejection("bookmark import") {58            try await database.bookmarks.importHTML(BookmarkTests.safariSample, profile: ghost.id)59        }60        await expectGhostRejection("download") {61            try await database.downloads.save(Download(profileID: ghost.id, sourceURL: secretURL, filename: "secret.pdf"))62        }63        await expectGhostRejection("permission") {64            try await database.permissions.set(PermissionDecision(profileID: ghost.id, origin: origin, kind: .camera, verdict: .allow))65        }66        await expectGhostRejection("archive") {67            try await database.archives.save(Archive(profileID: ghost.id, url: secretURL, title: "Secret", format: .pdf,68                                                     relativePath: "secret.pdf", byteSize: 1, contentHash: "h", isComplete: true))69        }70        await expectGhostRejection("snapshot") {71            try await database.snapshots.save(PageSnapshot(profileID: ghost.id, url: secretURL, title: "Secret", text: "secret text"))72        }73        await expectGhostRejection("note") { try await database.notes.save(Note(spaceID: ghostSpace.id, body: "secret note")) }74        await expectGhostRejection("canvas") { try await database.canvases.save(CanvasDocument(spaceID: ghostSpace.id, title: "secret board")) }75        await expectGhostRejection("agent run") {76            try await database.agentRuns.save(AgentRun(spaceID: ghostSpace.id, goal: "secret goal", providerID: "p", model: "m"))77        }78        // Moving or reopening a regular tab into a ghost window is refused too.79        let window = try await fixture.window()80        let tab = fixture.tab(in: window)81        try await database.tabs.save(tab)82        await expectGhostRejection("move into ghost window") { try await database.tabs.move(tab.id, to: ghostWindow.id, order: 0) }8384        // Nothing reached the file: no table contains a trace of the ghost session.85        let dump = try await database.sqlite.read { connection -> String in86            var text = ""87            let tables = try connection.query("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'history_fts%'")88                .map { try $0.get("name", as: String.self) }89            for table in tables {90                for row in try connection.query("SELECT * FROM \(table)") {91                    for value in row.values {92                        if case .text(let string) = value { text += string + "\n" }93                    }94                }95            }96            return text97        }98        #expect(!dump.lowercased().contains("secret"))99        #expect(!dump.contains(ghost.id.string))100        #expect(!dump.contains(ghostSpace.id.string))101        #expect(try await database.profiles.all() == [fixture.profile])102        #expect(try await database.history.visitCount() == 0)103        #expect(try await database.history.search("secret", profile: fixture.profile.id).isEmpty)104    }105106    /// Without any declaration the guarantee still holds: a ghost profile is never stored, so nothing that107    /// needs a stored owner can be written for it. Saving the profile once also teaches the registry.108    @Test func undeclaredGhostDataIsRejectedThroughOwnership() async throws {109        let fixture = try await Fixture.make()110        let database = fixture.database111        let ghost = Profile(name: "Ghost", kind: .ghost)112        let ghostSpace = OrbitSpace(profileID: ghost.id, name: "Private")113        let ghostWindow = BrowserWindow(spaceID: ghostSpace.id)114115        await #expect(throws: PersistenceError.ownerNotPersisted(owner: "profile", id: ghost.id.string)) {116            try await database.spaces.save(ghostSpace)117        }118        await #expect(throws: PersistenceError.ownerNotPersisted(owner: "space", id: ghostSpace.id.string)) {119            try await database.windows.save(ghostWindow)120        }121        await #expect(throws: PersistenceError.ownerNotPersisted(owner: "window", id: ghostWindow.id.string)) {122            try await database.tabs.save(Tab(windowID: ghostWindow.id, spaceID: ghostSpace.id))123        }124        await #expect(throws: PersistenceError.ownerNotPersisted(owner: "profile", id: ghost.id.string)) {125            try await database.history.recordVisit(NavigationEntry(profileID: ghost.id, url: url("https://secret.example/")))126        }127        await #expect(throws: PersistenceError.ownerNotPersisted(owner: "space", id: ghostSpace.id.string)) {128            try await database.notes.save(Note(spaceID: ghostSpace.id, body: "secret"))129        }130131        await #expect(throws: PersistenceError.ghostWriteRejected(entity: "profile \(ghost.id)")) {132            try await database.profiles.save(ghost)133        }134        #expect(database.ghosts.contains(ghost.id.raw))135        await #expect(throws: PersistenceError.ghostWriteRejected(entity: "profile \(ghost.id)")) {136            try await database.spaces.save(ghostSpace)137        }138        // Even raw SQL cannot insert a ghost profile: the schema refuses the kind.139        await #expect(throws: SQLiteError.self) {140            try await database.sqlite.write {141                try $0.execute("""142                INSERT INTO profiles (id, name, kind, data_store_identifier, tint, created_at)143                VALUES (?, 'Ghost', 'ghost', ?, 'silver', 0)144                """, [ghost.id, UUID()])145            }146        }147        database.ghosts.forget(profile: ghost.id)148        #expect(!database.ghosts.contains(ghost.id.raw))149    }150}151152@Suite struct DataLifecycleTests {153    /// Two profiles with a bit of everything.154    private func populate() async throws -> (Fixture, Profile, OrbitSpace) {155        let fixture = try await Fixture.make()156        let database = fixture.database157        // Created later than the fixture's profile, so "ordered by creation" is deterministic.158        let other = Profile(name: "Work", createdAt: day(1))159        try await database.profiles.save(other)160        let otherSpace = OrbitSpace(profileID: other.id, name: "Work space", createdAt: day(), updatedAt: day())161        try await database.spaces.save(otherSpace)162163        for (profile, space) in [(fixture.profile, fixture.space), (other, otherSpace)] {164            let window = BrowserWindow(spaceID: space.id)165            try await database.windows.save(window)166            var open = Tab(windowID: window.id, spaceID: space.id, url: url("https://open.example/"), title: "Open",167                           sessionState: Data([1, 2, 3]), createdAt: day(), lastActiveAt: day(5))168            open.order = 0169            let closed = Tab(windowID: window.id, spaceID: space.id, url: url("https://closed.example/"), title: "Closed",170                             order: 1, createdAt: day(), lastActiveAt: day(1), closedAt: day(2))171            try await database.tabs.save([open, closed])172            try await database.tabGroups.save(TabGroup(spaceID: space.id, name: "Group"))173            try await database.history.recordVisits([174                NavigationEntry(profileID: profile.id, url: url("https://old.example/"), title: "Old", visitedAt: day(1)),175                NavigationEntry(profileID: profile.id, url: url("https://mid.example/"), title: "Mid", visitedAt: day(5)),176                NavigationEntry(profileID: profile.id, url: url("https://new.example/"), title: "New", visitedAt: day(9)),177            ])178            try await database.bookmarks.append(Bookmark(profileID: profile.id, title: "B", url: url("https://b.example/"), tags: ["t"],179                                                         createdAt: day(1), updatedAt: day(1)))180            try await database.downloads.save(Download(profileID: profile.id, sourceURL: url("https://d.example/f.zip"), filename: "f.zip",181                                                       state: .paused, resumeData: Data([4, 5, 6]), startedAt: day(5)))182            try await database.permissions.set(PermissionDecision(profileID: profile.id, origin: WebOrigin(scheme: "https", host: "p.example"),183                                                                  kind: .location, verdict: .allow, decidedAt: day(5)))184            try await database.archives.save(Archive(profileID: profile.id, url: url("https://a.example/"), title: "A", format: .pdf,185                                                     relativePath: "\(profile.name)/a.pdf", byteSize: 10, contentHash: "h",186                                                     isComplete: true, capturedAt: day(5)))187            try await database.snapshots.save(PageSnapshot(profileID: profile.id, url: url("https://a.example/"), title: "A", text: "text", takenAt: day(5)))188            try await database.notes.save(Note(spaceID: space.id, body: "note of \(profile.name)", createdAt: day(5), updatedAt: day(5)))189            try await database.canvases.save(CanvasDocument(spaceID: space.id, title: "canvas", createdAt: day(5), updatedAt: day(5)))190            try await database.agentRuns.save(AgentRun(spaceID: space.id, goal: "goal", providerID: "p", model: "m", startedAt: day(5)))191        }192        try await database.notes.save(Note(body: "global note", createdAt: day(5), updatedAt: day(5)))193        try await database.workflows.save(Workflow(name: "W", source: "open x", createdAt: day(5), updatedAt: day(5)))194        try await database.settings.set(SettingKey<String>("search.engine", default: ""), to: "kagi", at: day(5))195        try await database.sync.recordChange(entity: .bookmark, entityID: "b", deviceID: "mac", at: day(5))196        return (fixture, other, otherSpace)197    }198199    @Test func selectiveDeletionByTypeProfileAndRange() async throws {200        let (fixture, other, otherSpace) = try await populate()201        let database = fixture.database202        let lifecycle = database.lifecycle203        let me = fixture.profile.id204205        // One type, one profile, one time range.206        var report = try await lifecycle.delete(DeletionRequest(types: [.history], profileID: me,207                                                                range: DateInterval(start: day(4), end: day(10))))208        #expect(report.deleted == [.history: 2])209        #expect(try await database.history.visits(profile: me).map(\.title) == ["Old"])210        #expect(try await database.history.visitCount(profile: other.id) == 3)211        #expect(try await database.history.search("mid", profile: me).isEmpty)212213        // Several types for one profile; global types are skipped for a profile-scoped request.214        report = try await lifecycle.delete(DeletionRequest(types: [.bookmarks, .downloads, .permissions, .archives, .snapshots,215                                                                    .notes, .canvases, .agentRuns, .workflows, .settings, .syncRecords],216                                                            profileID: me))217        #expect(report.deleted == [.bookmarks: 1, .downloads: 1, .permissions: 1, .archives: 1, .snapshots: 1,218                                   .notes: 1, .canvases: 1, .agentRuns: 1])219        #expect(report.archiveFiles == [ArchiveFileReference(profileID: me, relativePath: "Personal/a.pdf")])220        #expect(report.total == 8)221        #expect(try await database.bookmarks.all(profile: me).isEmpty)222        #expect(try await database.bookmarks.all(profile: other.id).count == 1)223        #expect(try await database.bookmarks.tags(profile: other.id).count == 1)224        #expect(try await database.notes.notes().map(\.body).sorted() == ["global note", "note of Work"])225        #expect(try await database.workflows.all().count == 1)226        #expect(try await database.settings.allRaw().count == 1)227        #expect(try await database.sync.changes(since: 0).count == 1)228229        // Recently closed only: open tabs stay.230        report = try await lifecycle.delete(DeletionRequest(types: [.recentlyClosed]))231        #expect(report.deleted == [.recentlyClosed: 2])232        #expect(try await database.tabs.recentlyClosed().isEmpty)233        #expect(try await database.session.restore().tabCount == 2)234235        // A range that matches nothing deletes nothing.236        report = try await lifecycle.delete(DeletionRequest(types: Set(UserDataType.allCases), range: DateInterval(start: day(100), end: day(200))))237        #expect(report.total == 0)238239        // Whole session of one profile.240        report = try await lifecycle.delete(DeletionRequest(types: [.session], profileID: other.id))241        #expect(report.deleted == [.session: 3])   // tab, window, group242        #expect(try await database.session.restore().windows.map(\.spaceID) == [fixture.space.id])243        #expect(try await database.tabGroups.groups(space: otherSpace.id).isEmpty)244245        // Everything, all profiles, in a range: day 5 only.246        report = try await lifecycle.delete(DeletionRequest(types: [.history, .workflows, .settings, .syncRecords, .notes],247                                                            range: DateInterval(start: day(5), end: day(6))))248        #expect(report.deleted == [.history: 1, .workflows: 1, .settings: 1, .syncRecords: 1, .notes: 2])249        #expect(try await database.history.visits(profile: other.id).map(\.title) == ["New", "Old"])250    }251252    @Test func deletingAProfileRemovesEverythingItOwns() async throws {253        let (fixture, other, _) = try await populate()254        let database = fixture.database255        let report = try await database.lifecycle.deleteProfile(other.id)256        #expect(report.archiveFiles == [ArchiveFileReference(profileID: other.id, relativePath: "Work/a.pdf")])257        #expect(report.deleted[.history] == 3)258        #expect(report.deleted[.notes] == 1)259260        #expect(try await database.profiles.all() == [fixture.profile])261        let leftovers = try await database.sqlite.read { connection -> [String: Int] in262            var counts: [String: Int] = [:]263            for table in ["spaces", "windows", "tabs", "tab_groups", "history_urls", "history_visits", "bookmarks", "bookmark_tags",264                          "downloads", "permissions", "archives", "page_snapshots", "notes", "canvas_documents", "agent_runs"] {265                counts[table] = try connection.scalar("SELECT count(*) FROM \(table)", as: Int.self) ?? -1266            }267            return counts268        }269        // Exactly what the remaining profile has (plus the note that belongs to no space).270        #expect(leftovers == ["spaces": 1, "windows": 1, "tabs": 2, "tab_groups": 1, "history_urls": 3, "history_visits": 3,271                              "bookmarks": 1, "bookmark_tags": 1, "downloads": 1, "permissions": 1, "archives": 1,272                              "page_snapshots": 1, "notes": 2, "canvas_documents": 1, "agent_runs": 1])273        // Global data is not part of a profile.274        #expect(try await database.workflows.all().count == 1)275        #expect(try await database.settings.allRaw().count == 1)276    }277278    @Test func deleteEverythingLeavesAnEmptyUsableDatabase() async throws {279        let scratch = try ScratchDirectory()280        let database = try await NavigatorDatabase(url: scratch.databaseURL)281        let fixture = try await Fixture.make(in: database)282        let marker = "UNIQUEMARKERSTRING"283        try await database.history.recordVisits((0..<300).map {284            fixture.visit("https://\(marker.lowercased())\($0).example.com/", title: "\(marker) page \($0)", at: second(Double($0)))285        })286        try await database.notes.save(Note(body: "\(marker) in a note"))287        try await database.settings.set(SettingKey<String>("k", default: ""), to: marker)288        let record = try await database.sync.recordChange(entity: .note, entityID: "n", deviceID: "mac")289        _ = try await database.session.beginSession()290291        let report = try await database.lifecycle.deleteEverything()292        #expect(report.deleted[.history] == 300)293294        let counts = try await database.sqlite.read { connection -> Int in295            var total = 0296            for table in try connection.query("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' AND name NOT LIKE 'history_fts_%' AND name NOT IN ('schema_migrations', 'app_state')") {297                total += try connection.scalar("SELECT count(*) FROM \(try table.get("name", as: String.self))", as: Int.self) ?? 0298            }299            return total300        }301        #expect(counts == 0)302        #expect(try await database.profiles.all().isEmpty)303        // The sync counter never goes backwards, even after a wipe.304        #expect(try await database.sync.recordChange(entity: .note, entityID: "n2", deviceID: "mac").version == record.version + 1)305        #expect(try await database.session.isMarkedClean())306        #expect(try await database.checkIntegrity(full: true).isEmpty)307        try await database.sync.purgeTombstones(olderThan: .distantFuture)308        try await database.lifecycle.delete(DeletionRequest(types: [.syncRecords]))309        try await database.lifecycle.compact()310        await database.close()311312        // After the wipe and compaction the text is gone from the files, not just from the tables.313        for file in NavigatorDatabase.fileURLs(for: scratch.databaseURL) {314            guard let bytes = try? Data(contentsOf: file) else { continue }315            #expect(bytes.range(of: Data(marker.utf8)) == nil, "marker still present in \(file.lastPathComponent)")316            #expect(bytes.range(of: Data(marker.lowercased().utf8)) == nil, "marker still present in \(file.lastPathComponent)")317        }318319        // The database works again from scratch.320        let reopened = try await NavigatorDatabase(url: scratch.databaseURL)321        _ = try await Fixture.make(in: reopened)322        #expect(try await reopened.profiles.all().count == 1)323        await reopened.close()324    }325326    @Test func historyRetention() async throws {327        let fixture = try await Fixture.make()328        let database = fixture.database329        let now = day(100)330        try await database.history.recordVisits([331            fixture.visit("https://a.example/", title: "A", at: day(5)),332            fixture.visit("https://a.example/", title: "A", at: day(99)),333            fixture.visit("https://b.example/", title: "B", at: day(69)),334            fixture.visit("https://c.example/", title: "C", at: day(71)),335        ])336        // 0 = keep forever.337        #expect(try await database.lifecycle.applyHistoryRetention(days: 0, now: now) == 0)338        #expect(try await database.lifecycle.applyStoredRetentionPolicy(now: now) == 0)339        #expect(try await database.history.visitCount() == 4)340341        // 30 days: the cutoff is day 70.342        try await database.settings.set(PersistenceSettings.historyRetentionDays, to: 30)343        #expect(try await database.lifecycle.applyStoredRetentionPolicy(now: now) == 2)344        #expect(try await database.history.visits(profile: fixture.profile.id).map(\.title) == ["A", "C"])345        #expect(try await database.history.page(for: url("https://a.example/"), profile: fixture.profile.id)?.visitCount == 1)346        #expect(try await database.history.search("b", profile: fixture.profile.id).isEmpty)347        // Idempotent.348        #expect(try await database.lifecycle.applyStoredRetentionPolicy(now: now) == 0)349        #expect(try await database.lifecycle.applyHistoryRetention(days: 1, now: now) == 1)350    }351352    @Test func exportBundleContainsUserDataButNoBlobsOrSecrets() async throws {353        let (fixture, other, _) = try await populate()354        let database = fixture.database355        let secrets = InMemorySecretStore()356        try await secrets.setSecret("sk-test-THIS-MUST-NOT-LEAK", for: "provider.anthropic.apiKey")357358        let data = try await database.lifecycle.exportJSON(now: day(20))359        let text = String(decoding: data, as: UTF8.self)360        #expect(!text.contains("sk-test-THIS-MUST-NOT-LEAK"))361        #expect(!text.lowercased().contains("cookie"))362        #expect(!text.contains("sessionState"))363        #expect(!text.contains("resumeData"))364        #expect(text.contains("\"exportedAt\" : \"2026-06-17T20:26:40Z\""))   // ISO 8601, human readable365366        let bundle = try DataLifecycle.decodeBundle(data)367        #expect(bundle.formatVersion == UserDataBundle.currentFormatVersion)368        #expect(bundle.schemaVersion == Schema.latestVersion)369        #expect(bundle.profiles.map(\.name) == ["Personal", "Work"])370        #expect(bundle.spaces.count == 2)371        #expect(bundle.windows.count == 2)372        #expect(bundle.tabs.count == 4)373        #expect(bundle.tabs.allSatisfy { $0.sessionState == nil })374        #expect(bundle.tabGroups.count == 2)375        #expect(bundle.history.count == 6)376        #expect(bundle.bookmarks.count == 2)377        #expect(bundle.bookmarks.allSatisfy { $0.tags == ["t"] })378        #expect(bundle.downloads.count == 2)379        #expect(bundle.downloads.allSatisfy { $0.resumeData == nil })380        #expect(bundle.permissions.count == 2)381        #expect(bundle.archives.count == 2)382        #expect(bundle.snapshots.count == 2)383        #expect(bundle.notes.count == 3)384        #expect(bundle.canvases.count == 2)385        #expect(bundle.agentRuns.count == 2)386        #expect(bundle.workflows.count == 1)387        #expect(bundle.settings == ["search.engine": "\"kagi\""])388        // Exporting does not strip anything from the database itself.389        #expect(try await database.downloads.downloads(profile: other.id).first?.resumeData == Data([4, 5, 6]))390391        // One profile only: nothing of the other profile, no global data.392        let mine = try await database.lifecycle.exportBundle(profile: other.id)393        #expect(mine.profiles.map(\.name) == ["Work"])394        #expect(mine.history.count == 3)395        #expect(mine.history.allSatisfy { $0.profileID == other.id })396        #expect(mine.notes.map(\.body) == ["note of Work"])397        #expect(mine.tabs.count == 2)398        #expect(mine.workflows.isEmpty)399        #expect(mine.settings.isEmpty)400401        // To a file.402        let scratch = try ScratchDirectory()403        let file = scratch.url.appending(path: "export.json")404        try await database.lifecycle.exportJSON(to: file, now: day(20))405        #expect(try Data(contentsOf: file) == data)406    }407}408409@Suite struct SecretStoreTests {410    private func exercise(_ store: any SecretStore) async throws {411        try await store.removeAllSecrets()412        #expect(try await store.secretKeys().isEmpty)413        #expect(try await store.secret(for: "missing") == nil)414        try await store.setSecret("sk-first", for: "provider.a")415        try await store.setSecret(Data([0, 1, 2, 255]), for: "provider.b")416        #expect(try await store.secretString(for: "provider.a") == "sk-first")417        #expect(try await store.secret(for: "provider.b") == Data([0, 1, 2, 255]))418        #expect(try await store.secretKeys() == ["provider.a", "provider.b"])419        // Replace, remove, remove again.420        try await store.setSecret("sk-second", for: "provider.a")421        #expect(try await store.secretString(for: "provider.a") == "sk-second")422        try await store.removeSecret(for: "provider.a")423        try await store.removeSecret(for: "provider.a")424        #expect(try await store.secret(for: "provider.a") == nil)425        #expect(try await store.secretKeys() == ["provider.b"])426        try await store.setSecret("x", for: "provider.c")427        try await store.removeAllSecrets()428        #expect(try await store.secretKeys().isEmpty)429    }430431    @Test func inMemoryStore() async throws {432        try await exercise(InMemorySecretStore())433    }434435    @Test func errorsNeverCarryTheSecret() {436        let error = SecretStoreError(operation: "write", status: -34018)437        #expect(error.description == "Secret store write failed (OSStatus -34018)")438    }439440    /// Talks to the real login keychain, so it only runs on request:441    /// `ORIX_KEYCHAIN_TESTS=1 swift test --filter PersistenceTests`.442    @Test(.enabled(if: ProcessInfo.processInfo.environment["ORIX_KEYCHAIN_TESTS"] == "1"))443    func keychainStore() async throws {444        let service = "dev.orixlab.navigator.tests.\(UUID().uuidString)"445        // An unsigned test binary has no application identifier, so the data-protection keychain is refused;446        // the legacy keychain exercises the same code path apart from one query key.447        let store = KeychainSecretStore(service: service, useDataProtectionKeychain: false)448        try await exercise(store)449        // Two services do not see each other's items.450        let other = KeychainSecretStore(service: service + ".other", useDataProtectionKeychain: false)451        try await store.setSecret("only-here", for: "k")452        #expect(try await other.secret(for: "k") == nil)453        try await store.removeAllSecrets()454        try await other.removeAllSecrets()455    }456}457
Files main
Menu

Theme