SPB Git

Repository Public License

ServicesTests.swift 35.2 KB 524 lines swift

1import Foundation2import NavigatorCore3import Persistence4import Testing5@testable import PrivacyEngine67private let utc = TimeZone(identifier: "UTC")!8private let smallList = ShieldList(blocked: [9    BlockedDomain(domain: "tracker.example", category: .trackers), BlockedDomain(domain: "ads.example", category: .ads),10])1112@Suite struct ShieldServiceTests {13    private func service(_ fixture: Fixture) -> ShieldService {14        ShieldService(database: fixture.database, builtIn: smallList, timeZone: utc, now: { fixture.clock.now })15    }1617    @Test func settingsAreStoredAndCleaned() async throws {18        let fixture = try await Fixture.make()19        let shield = service(fixture)20        #expect(try await shield.settings() == ShieldSettings())21        var settings = ShieldSettings(blockAds: false)22        settings.disabledSites = ["B.example", "a.example", "a.example", "garbage value"]23        try await shield.update(settings)24        #expect(try await shield.settings().disabledSites == ["a.example", "b.example"])25        #expect(try await ShieldService(database: fixture.database, builtIn: smallList).settings().blockAds == false)26    }2728    @Test func shieldCanBeTurnedOffPerSite() async throws {29        let fixture = try await Fixture.make()30        let shield = service(fixture)31        try await shield.setShield(enabled: false, onSite: "News.Example", profile: fixture.profile.id)32        #expect(try await !shield.isActive(onSite: "news.example", profile: fixture.profile.id))33        #expect(try await !shield.isActive(onSite: "live.news.example", profile: fixture.profile.id))   // subdomains follow34        #expect(try await shield.isActive(onSite: "other.example", profile: fixture.profile.id))35        let compilation = try await shield.compile(profile: fixture.profile.id)36        #expect(compilation.lists.allSatisfy { $0.json.contains("*news.example") })37        try await shield.setShield(enabled: true, onSite: "news.example", profile: fixture.profile.id)38        #expect(try await shield.settings().disabledSites.isEmpty)39        await #expect(throws: ShieldError.invalidSite) { try await shield.setShield(enabled: false, onSite: "not a host", profile: fixture.profile.id) }40        await #expect(throws: ShieldError.unknownProfile) { try await shield.setShield(enabled: false, onSite: "x.example", profile: ProfileID()) }41        try await shield.allowHTTP(onSite: "legacy.example", profile: fixture.profile.id)42        #expect(try await shield.settings().httpAllowedSites == ["legacy.example"])43    }4445    @Test func userListsAreImportedWithDiagnostics() async throws {46        let fixture = try await Fixture.make()47        let shield = service(fixture)48        let result = try await shield.importList(named: "  Mine ", text: "custom.example\n||broken/path\n@@||ads.example^")49        let list = try #require(result.list)50        #expect(list.name == "Mine" && result.acceptedLines == 2 && result.diagnostics.map(\.line) == [2])51        #expect(try await shield.blockedDomains() == ["tracker.example", "custom.example"])   // ads.example was unblocked52        #expect(try await shield.isListed(host: "cdn.custom.example"))53        #expect(try await !shield.isListed(host: "ads.example"))5455        try await shield.setUserList(list.id, enabled: false)56        #expect(try await shield.blockedDomains() == ["tracker.example", "ads.example"])57        try await shield.removeUserList(list.id)58        #expect(try await shield.userLists().isEmpty)5960        let nothing = try await shield.importList(named: "Bad", text: "||only/unsupported\n/regex/")61        #expect(nothing.list == nil && nothing.diagnostics.count == 2)62        #expect(try await shield.userLists().isEmpty)63        var settings = try await shield.settings()64        settings.blockTrackers = false65        try await shield.update(settings)66        #expect(try await shield.blockedDomains() == ["ads.example"])67    }6869    @Test func exactEventsAreCountedPerSiteAndDay() async throws {70        let fixture = try await Fixture.make()71        let shield = service(fixture)72        let profile = fixture.profile.id73        await shield.record(.popupBlocked, site: "news.example", profile: profile)74        await shield.record(.popupBlocked, site: "news.example", profile: profile)75        await shield.record(.httpsUpgraded, site: "shop.example", profile: profile)76        fixture.clock.advance(86_400)77        await shield.record(.popupBlocked, site: "shop.example", profile: profile)78        await shield.record(.popupBlocked, site: "::not a host::", profile: profile)7980        // Readable before and after the flush, with the same result.81        for _ in 0..<2 {82            #expect(try await shield.counters(profile: profile, days: 7) == ShieldCounters(popupsBlocked: 4, httpsUpgrades: 1))83            #expect(try await shield.counters(profile: profile, site: "news.example", days: 7) == ShieldCounters(popupsBlocked: 2))84            #expect(try await shield.counters(profile: profile, days: 1) == ShieldCounters(popupsBlocked: 2))85            let daily = try await shield.daily(profile: profile, days: 3)86            #expect(daily.map(\.day) == ["2026-11-24", "2026-11-25", "2026-11-26"])87            #expect(daily.map(\.counters.popupsBlocked) == [0, 2, 2])88            let top = try await shield.topSites(profile: profile, days: 7, limit: 2)89            #expect(top.map(\.site) == ["news.example", "shop.example"])90            try await shield.flushStatistics()91        }92        #expect(try await fixture.database.settings.isSet("shield.stats.\(profile.string).2026-11-25"))93        #expect(try await shield.daily(profile: profile, site: "bad host", days: 3).isEmpty)94        // Another profile sees nothing.95        let other = Profile(name: "Work")96        try await fixture.database.profiles.save(other)97        #expect(try await shield.counters(profile: other.id, days: 30).isZero)98    }99100    @Test func pageReportsCountOnlyListedThirdPartyHosts() async throws {101        let fixture = try await Fixture.make()102        let shield = service(fixture)103        let profile = fixture.profile.id104        let report = ShieldPageReport(failedHosts: [105            "cdn.tracker.example": 3, "ads.example": 2, "innocent.example": 50, "not a host": 9, "tracker.example": 100_000, "ADS.example": -4,106        ])107        // 3 + 2 + min(100 000, 500); the unlisted and invalid hosts and the negative count are ignored.108        #expect(try await shield.ingest(report, site: "news.example", profile: profile) == 505)109        #expect(try await shield.counters(profile: profile).likelyBlockedRequests == 505)110        // A listed host failing on its own site was not blocked by a third-party rule.111        #expect(try await shield.ingest(ShieldPageReport(failedHosts: ["cdn.tracker.example": 3]), site: "www.tracker.example", profile: profile) == 0)112        // Shield off for the site: nothing can have been blocked there.113        try await shield.setShield(enabled: false, onSite: "news.example", profile: profile)114        #expect(try await shield.ingest(report, site: "news.example", profile: profile) == 0)115        let flood = ShieldPageReport(failedHosts: Dictionary(uniqueKeysWithValues: (0..<1_000).map { ("h\($0).tracker.example", 1) }))116        #expect(try await shield.ingest(flood, site: "blog.example", profile: profile) == ShieldPageReport.maximumHosts)117        let decoded = try JSONDecoder().decode(ShieldPageReport.self, from: Data(#"{"failedHosts":{"ads.example":1}}"#.utf8))118        #expect(decoded.failedHosts == ["ads.example": 1])119    }120121    @Test func statisticsAreFlushedAutomaticallyClearedAndPruned() async throws {122        let fixture = try await Fixture.make()123        let shield = service(fixture)124        let profile = fixture.profile.id125        for _ in 0..<25 { await shield.record(.popupBlocked, site: "news.example", profile: profile) }126        #expect(try await fixture.database.settings.value(ShieldKeys.statistics(profile: profile, day: "2026-11-25"))["news.example"]?.popupsBlocked == 25)127128        fixture.clock.advance(2 * 86_400)129        await shield.record(.popupBlocked, site: "later.example", profile: profile)130        try await shield.flushStatistics()131        // Clear the first day only.132        let firstDay = DateInterval(start: Date(timeIntervalSince1970: 1_795_564_800), duration: 86_400)133        #expect(try await shield.clearStatistics(profile: profile, range: firstDay) == 1)134        #expect(try await shield.counters(profile: profile, days: 7) == ShieldCounters(popupsBlocked: 1))135        #expect(try await shield.clearStatistics(profile: ProfileID()) == 0)136137        fixture.clock.advance(Double(ShieldService.statisticsRetentionDays + 1) * 86_400)138        await shield.record(.httpsUpgraded, site: "today.example", profile: profile)139        try await shield.flushStatistics()140        #expect(try await shield.pruneStatistics() == 1)141        #expect(try await shield.counters(profile: profile, days: 400) == ShieldCounters(httpsUpgrades: 1))142        #expect(try await shield.clearStatistics() == 1)143    }144145    @Test func tooManySitesFallIntoOneBucket() async throws {146        let fixture = try await Fixture.make()147        let shield = service(fixture)148        for index in 0..<(ShieldService.maximumSitesPerDay + 30) {149            await shield.record(.popupBlocked, site: "site\(index).example", profile: fixture.profile.id)150        }151        try await shield.flushStatistics()152        let stored = try await fixture.database.settings.value(ShieldKeys.statistics(profile: fixture.profile.id, day: "2026-11-25"))153        #expect(stored.count == ShieldService.maximumSitesPerDay + 1)154        #expect(stored[ShieldService.otherSitesBucket]?.popupsBlocked == 30)155        #expect(stored.values.reduce(0) { $0 + $1.popupsBlocked } == ShieldService.maximumSitesPerDay + 30)156    }157}158159@Suite struct PermissionServiceTests {160    private func service(_ fixture: Fixture) -> PermissionService {161        PermissionService(database: fixture.database, now: { fixture.clock.now })162    }163164    @Test func defaultsPerKind() async throws {165        let fixture = try await Fixture.make()166        let permissions = service(fixture)167        for kind in PermissionKind.allCases {168            let expected: PermissionDecision.Verdict = kind == .popups || kind == .autoplay ? .deny : .ask169            #expect(await permissions.verdict(for: kind, origin: https, profileID: fixture.profile.id) == expected)170            #expect(PermissionService.builtInDefaults[kind] != nil)171        }172        try await permissions.setDefaultVerdict(.allow, for: .popups)173        try await permissions.setDefaultVerdict(.deny, for: .notifications)174        #expect(await permissions.verdict(for: .popups, origin: https, profileID: fixture.profile.id) == .allow)175        #expect(await permissions.verdict(for: .notifications, origin: https, profileID: fixture.profile.id) == .deny)176        try await permissions.setDefaultVerdict(nil, for: .popups)177        #expect(await permissions.defaultVerdict(for: .popups) == .deny)178        await #expect(throws: PermissionError.defaultNotAllowed) { try await permissions.setDefaultVerdict(.allow, for: .camera) }179    }180181    @Test func alwaysIsStoredPerProfileOriginAndKind() async throws {182        let fixture = try await Fixture.make()183        let permissions = service(fixture)184        let profile = fixture.profile.id185        try await permissions.decide(.allow, for: .camera, origin: https, profile: profile, duration: .always)186        #expect(await permissions.verdict(for: .camera, origin: https, profileID: profile) == .allow)187        #expect(await permissions.verdict(for: .microphone, origin: https, profileID: profile) == .ask)188        #expect(await permissions.verdict(for: .camera, origin: WebOrigin(scheme: "https", host: "example.com", port: 8443), profileID: profile) == .ask)189        #expect(await permissions.verdict(for: .camera, origin: WebOrigin(scheme: "https", host: "sub.example.com"), profileID: profile) == .ask)190        let other = Profile(name: "Work")191        try await fixture.database.profiles.save(other)192        #expect(await permissions.verdict(for: .camera, origin: https, profileID: other.id) == .ask)193        // A new service on the same database still knows it; ten years later too.194        fixture.clock.advance(10 * 365 * 86_400)195        #expect(await service(fixture).verdict(for: .camera, origin: https, profileID: profile) == .allow)196    }197198    @Test func twentyFourHoursExpire() async throws {199        let fixture = try await Fixture.make()200        let permissions = service(fixture)201        let profile = fixture.profile.id202        try await permissions.decide(.allow, for: .location, origin: https, profile: profile, duration: .day)203        let panel = await permissions.sitePermissions(origin: https, profile: profile)204        let row = try #require(panel.first { $0.kind == .location })205        #expect(row.source == .stored && row.expiresAt == fixture.clock.now.addingTimeInterval(86_400))206        fixture.clock.advance(86_399)207        #expect(await permissions.verdict(for: .location, origin: https, profileID: profile) == .allow)208        fixture.clock.advance(2)209        #expect(await permissions.verdict(for: .location, origin: https, profileID: profile) == .ask)210        #expect(try await permissions.purgeExpired() == 1)211        #expect(try await fixture.database.permissions.decisions(profile: profile).isEmpty)212    }213214    @Test func onceIsNotRememberedAndSessionStaysInMemory() async throws {215        let fixture = try await Fixture.make()216        let permissions = service(fixture)217        let profile = fixture.profile.id218        try await permissions.decide(.allow, for: .microphone, origin: https, profile: profile, duration: .once)219        #expect(await permissions.verdict(for: .microphone, origin: https, profileID: profile) == .ask)220221        try await permissions.decide(.allow, for: .microphone, origin: https, profile: profile, duration: .always)222        try await permissions.decide(.deny, for: .microphone, origin: https, profile: profile, duration: .session)223        #expect(await permissions.verdict(for: .microphone, origin: https, profileID: profile) == .deny)224        #expect(try await fixture.database.permissions.decisions(profile: profile).isEmpty)   // the session answer replaced "always"225        let row = try #require(await permissions.sitePermissions(origin: https, profile: profile).first { $0.kind == .microphone })226        #expect(row.source == .session)227        await permissions.endSession()228        #expect(await permissions.verdict(for: .microphone, origin: https, profileID: profile) == .ask)229    }230231    @Test func sensitiveKindsAreDeniedOnInsecureOrigins() async throws {232        let fixture = try await Fixture.make()233        let permissions = service(fixture)234        let profile = fixture.profile.id235        let insecure = WebOrigin(scheme: "http", host: "example.com")236        await #expect(throws: PermissionError.insecureOrigin) {237            try await permissions.decide(.allow, for: .camera, origin: insecure, profile: profile, duration: .always)238        }239        #expect(await permissions.verdict(for: .camera, origin: insecure, profileID: profile) == .deny)240        // Even a decision written by an older build or a sync merge is not honoured.241        try await fixture.database.permissions.set(PermissionDecision(profileID: profile, origin: insecure, kind: .microphone, verdict: .allow))242        #expect(await permissions.verdict(for: .microphone, origin: insecure, profileID: profile) == .deny)243        #expect(await permissions.sitePermissions(origin: insecure, profile: profile).first { $0.kind == .microphone }?.source == .policy)244        // Pop-ups are not a secure-context matter; loopback is a secure context.245        try await permissions.decide(.allow, for: .popups, origin: insecure, profile: profile, duration: .always)246        #expect(await permissions.verdict(for: .popups, origin: insecure, profileID: profile) == .allow)247        #expect(PermissionService.isSecureContext(WebOrigin(scheme: "http", host: "localhost", port: 3000)))248        #expect(PermissionService.isSecureContext(WebOrigin(scheme: "http", host: "app.localhost")))249        #expect(!PermissionService.isSecureContext(WebOrigin(scheme: "http", host: "localhost.evil.com")))250    }251252    @Test func theProviderContractRemembersAndRevokes() async throws {253        let fixture = try await Fixture.make()254        let permissions = service(fixture)255        let provider: any PermissionProvider = permissions256        let profile = fixture.profile.id257        let other = WebOrigin(scheme: "https", host: "other.example")258        await provider.record(.deny, for: .notifications, origin: https, profileID: profile)259        await provider.record(.allow, for: .clipboard, origin: https, profileID: profile)260        await provider.record(.allow, for: .popups, origin: other, profileID: profile)261        try await permissions.decide(.allow, for: .autoplay, origin: other, profile: profile, duration: .session)262        #expect(await provider.verdict(for: .notifications, origin: https, profileID: profile) == .deny)263264        let sites = try await permissions.decidedSites(profile: profile)265        #expect(sites.map(\.origin) == [https, other])266        #expect(sites[0].permissions.map(\.kind) == [.notifications, .clipboard])267        #expect(sites[1].permissions.map(\.source) == [.stored, .session])268269        try await permissions.revoke(.notifications, origin: https, profile: profile)270        #expect(await provider.verdict(for: .notifications, origin: https, profileID: profile) == .ask)271        try await permissions.decide(.ask, for: .clipboard, origin: https, profile: profile, duration: .always)   // "ask" = forget272        #expect(try await permissions.decidedSites(profile: profile).map(\.origin) == [other])273        #expect(try await permissions.revokeAll(origin: other, profile: profile) == 2)274        await provider.record(.allow, for: .popups, origin: https, profileID: profile)275        #expect(try await permissions.revokeAll(profile: profile) == 1)276        #expect(try await permissions.decidedSites(profile: profile).isEmpty)277        // Recording for a profile that does not exist fails safe: nothing stored, the answer stays "ask".278        await provider.record(.allow, for: .camera, origin: https, profileID: ProfileID())279        #expect(try await tableCounts(fixture.database)["permissions"] == 0)280    }281}282283@Suite struct GhostSessionTests {284    @Test func aPrivateSessionLivesInMemoryAndCanBeUsedLikeAWindow() async throws {285        let fixture = try await Fixture.make()286        let manager = GhostSessionManager(database: fixture.database, now: { fixture.clock.now })287        let session = await manager.begin()288        #expect(session.profile.isGhost && session.space.profileID == session.profile.id)289        #expect(fixture.database.ghosts.contains(session.profile.id.raw) && fixture.database.ghosts.contains(session.space.id.raw))290        #expect(await manager.isGhost(session.profile.id))291292        let window = try await session.openWindow()293        #expect(fixture.database.ghosts.contains(window.id.raw))294        let a = try await session.openTab(in: window.id, url: URL(string: "https://private.example/a"), title: "A")295        let b = try await session.openTab(in: window.id, url: nil, parent: a.id)296        let c = try await session.openTab(in: window.id, url: nil, parent: b.id, select: false)297        #expect(await session.tabs(in: window.id).map(\.id) == [a.id, b.id, c.id])298        #expect(await session.window(window.id)?.selectedTabID == b.id)299        try await session.touch(a.id, url: URL(string: "https://private.example/b"), title: "B")300        try await session.reorderTabs(in: window.id, [c.id, a.id, b.id])301        #expect(await session.tabs(in: window.id).map(\.id) == [c.id, a.id, b.id])302        var pinned = try #require(await session.tab(b.id))303        pinned.isPinned = true304        pinned.groupID = TabGroupID()305        try await session.update(pinned)306        #expect(await session.tabs(in: window.id).first?.id == b.id)307        #expect(await session.tab(b.id)?.groupID == nil)308309        let after = try await session.closeTab(b.id)310        #expect(after.selectedTabID == c.id)                          // the neighbour in display order311        #expect(await session.tab(c.id)?.parentID == a.id)            // adopted by the grandparent312        await #expect(throws: GhostError.tabNotFound) { try await session.closeTab(b.id) }313314        let second = try await session.openWindow()315        try await session.openTab(in: second.id, url: nil)316        #expect(try await session.closeWindow(second.id).count == 1)317        #expect(fixture.database.ghosts.contains(second.id.raw))      // still refused as ghost until the session ends318319        let teardown = try #require(await manager.end(session.profile.id))320        #expect(teardown.dataStoreIdentifier == session.profile.dataStoreIdentifier && teardown.tabIDs.count == 2)321        let remainingTabs = await session.tabCount, stillActive = await session.isActive322        #expect(remainingTabs == 0 && !stillActive)323        for raw in [session.profile.id.raw, session.space.id.raw, window.id.raw, second.id.raw] { #expect(!fixture.database.ghosts.contains(raw)) }324        await #expect(throws: GhostError.sessionEnded) { try await session.openWindow() }325        #expect(await manager.end(session.profile.id) == nil)326        #expect(await manager.activeSessions.isEmpty)327    }328329    @Test func twoPrivateSessionsDoNotShareAnything() async throws {330        let fixture = try await Fixture.make()331        let manager = GhostSessionManager(database: fixture.database)332        let first = await manager.begin(), second = await manager.begin()333        #expect(first.profile.id != second.profile.id && first.profile.dataStoreIdentifier != second.profile.dataStoreIdentifier)334        #expect(await manager.endAll().count == 2)335    }336337    /// The central promise: using the services in a private context writes zero rows.338    @Test func usingEveryServiceInAGhostContextWritesNothing() async throws {339        let fixture = try await Fixture.make()340        let permissions = PermissionService(database: fixture.database, now: { fixture.clock.now })341        let shield = ShieldService(database: fixture.database, builtIn: smallList, timeZone: utc, now: { fixture.clock.now })342        let manager = GhostSessionManager(database: fixture.database, now: { fixture.clock.now })343        // Settings rows that exist before the private session (Shield settings are global).344        try await shield.update(ShieldSettings())345        let before = try await tableCounts(fixture.database)346347        let session = await manager.begin()348        let ghost = session.profile.id349        let window = try await session.openWindow()350        let tab = try await session.openTab(in: window.id, url: URL(string: "https://secret.example/"), title: "Secret")351        try await session.touch(tab.id, url: URL(string: "https://secret.example/page"), title: "Secret page")352353        // Permissions: every duration.354        let origin = WebOrigin(scheme: "https", host: "secret.example")355        for (kind, duration) in zip([PermissionKind.camera, .microphone, .location, .popups], PermissionDuration.allCases) {356            try await permissions.decide(.allow, for: kind, origin: origin, profile: ghost, duration: duration)357        }358        await permissions.record(.deny, for: .notifications, origin: origin, profileID: ghost)359        #expect(await permissions.verdict(for: .microphone, origin: origin, profileID: ghost) == .allow)360        #expect(await permissions.verdict(for: .popups, origin: origin, profileID: ghost) == .allow)       // "always" = until the session ends361        #expect(await permissions.verdict(for: .camera, origin: origin, profileID: ghost) == .ask)         // "once"362        #expect(try await permissions.decidedSites(profile: ghost).first?.permissions.count == 4)363        try await permissions.revoke(.location, origin: origin, profile: ghost)364        _ = try await permissions.purgeExpired()365366        // Shield: per-site switch, exact events, page reports, flushes.367        try await shield.setShield(enabled: false, onSite: "secret.example", profile: ghost)368        try await shield.allowHTTP(onSite: "secret-http.example", profile: ghost)369        #expect(try await !shield.isActive(onSite: "secret.example", profile: ghost))370        #expect(try await shield.isActive(onSite: "secret.example", profile: fixture.profile.id))          // not for normal profiles371        #expect(try await shield.compile(profile: ghost).lists.allSatisfy { $0.json.contains("*secret.example") })372        for _ in 0..<40 { await shield.record(.popupBlocked, site: "other-secret.example", profile: ghost) }373        await shield.record(.httpsUpgraded, site: "other-secret.example", profile: ghost)374        _ = try await shield.ingest(ShieldPageReport(failedHosts: ["tracker.example": 4]), site: "other-secret.example", profile: ghost)375        #expect(try await shield.counters(profile: ghost) == ShieldCounters(popupsBlocked: 40, httpsUpgrades: 1, likelyBlockedRequests: 4))376        try await shield.flushStatistics()377378        // The stores themselves refuse anything that belongs to the session.379        await #expect(throws: PersistenceError.self) { try await fixture.database.profiles.save(session.profile) }380        await #expect(throws: PersistenceError.self) { try await fixture.database.spaces.save(session.space) }381        await #expect(throws: PersistenceError.self) { try await fixture.database.windows.save(window) }382        await #expect(throws: PersistenceError.self) { try await fixture.database.tabs.save(tab) }383        await #expect(throws: PersistenceError.self) {384            try await fixture.database.history.recordVisit(NavigationEntry(profileID: ghost, url: URL(string: "https://secret.example/")!))385        }386        await #expect(throws: PersistenceError.self) {387            try await fixture.database.downloads.save(Download(profileID: ghost, sourceURL: URL(string: "https://secret.example/f.zip")!, filename: "f.zip"))388        }389        await #expect(throws: PersistenceError.self) {390            try await fixture.database.bookmarks.save(Bookmark(profileID: ghost, title: "x", url: URL(string: "https://secret.example/")))391        }392393        #expect(try await tableCounts(fixture.database) == before)394        let dump = try await fixture.database.lifecycle.exportJSON()395        #expect(!String(decoding: dump, as: UTF8.self).contains("secret"))396397        // Ending the session drops the in-memory state, and a late event cannot be stored as a normal profile's.398        await manager.end(ghost, permissions: permissions, shield: shield)399        #expect(await permissions.verdict(for: .microphone, origin: origin, profileID: ghost) == .ask)400        #expect(try await shield.counters(profile: ghost).isZero)401        await shield.record(.popupBlocked, site: "late-secret.example", profile: ghost)402        await permissions.record(.allow, for: .popups, origin: origin, profileID: ghost)403        try await shield.flushStatistics()404        await #expect(throws: ShieldError.unknownProfile) { try await shield.setShield(enabled: false, onSite: "late-secret.example", profile: ghost) }405        #expect(try await tableCounts(fixture.database) == before)406    }407408    @Test func policyFlagsAndTextsSayWhatPrivateBrowsingDoesNotHide() {409        #expect(!GhostPolicy.recordsHistory && !GhostPolicy.indexesMemory && !GhostPolicy.syncs && !GhostPolicy.persistsProfile410                && !GhostPolicy.persistsWindowsAndTabs && !GhostPolicy.persistsPermissions && !GhostPolicy.persistsDownloadList411                && !GhostPolicy.persistsShieldStatistics && !GhostPolicy.usesPersistentWebsiteData)412        #expect(Set(PrivacyText.allCases.map(\.rawValue)).count == PrivacyText.allCases.count)413        #expect(PrivacyText.allCases.allSatisfy { !$0.english.isEmpty && $0.rawValue.hasPrefix("privacy.") })414        let limits = PrivacyText.ghostLimitations.map(\.english).joined(separator: " ").lowercased()415        for word in ["internet provider", "network", "employer", "sites you visit", "ip address", "download", "bookmarks", "device"] {416            #expect(limits.contains(word), "missing: \(word)")417        }418        #expect(PrivacyText.ghostDownloadKept.english.contains("file itself stays"))419        #expect(!PrivacyText.ghostWhatItDoes.english.lowercased().contains("anonymous"))420    }421}422423@Suite struct DataControlsTests {424    private func populated() async throws -> (Fixture, DataControls, PermissionService, ShieldService) {425        let fixture = try await Fixture.make()426        let permissions = PermissionService(database: fixture.database, now: { fixture.clock.now })427        let shield = ShieldService(database: fixture.database, builtIn: smallList, timeZone: utc, now: { fixture.clock.now })428        let controls = DataControls(database: fixture.database, permissions: permissions, shield: shield, now: { fixture.clock.now })429        let profile = fixture.profile.id, now = fixture.clock.now430        for (index, age) in ([10, 1_800, 7_200, 3 * 86_400, 40 * 86_400] as [TimeInterval]).enumerated() {431            try await fixture.database.history.recordVisit(NavigationEntry(profileID: profile, url: URL(string: "https://site\(index).example/")!,432                                                                           visitedAt: now.addingTimeInterval(-age)))433        }434        try await fixture.database.bookmarks.save(Bookmark(profileID: profile, title: "B", url: URL(string: "https://example.com")))435        try await fixture.database.downloads.save(Download(profileID: profile, sourceURL: URL(string: "https://example.com/f")!, filename: "f",436                                                           state: .finished, startedAt: now.addingTimeInterval(-60)))437        try await permissions.decide(.allow, for: .camera, origin: https, profile: profile, duration: .always)438        try await permissions.decide(.allow, for: .popups, origin: https, profile: profile, duration: .session)439        await shield.record(.popupBlocked, site: "site0.example", profile: profile)440        try await shield.flushStatistics()441        return (fixture, controls, permissions, shield)442    }443444    @Test func timeRangesEndNow() {445        let now = Date(timeIntervalSince1970: 1_000_000)446        #expect(DataTimeRange.lastHour.interval(now: now) == DateInterval(start: now.addingTimeInterval(-3_600), end: now.addingTimeInterval(1)))447        #expect(DataTimeRange.last4Weeks.interval(now: now)?.start == now.addingTimeInterval(-28 * 86_400))448        #expect(DataTimeRange.allTime.interval(now: now) == nil)449        let custom = DateInterval(start: now, duration: 5)450        #expect(DataTimeRange.custom(custom).interval(now: .distantPast) == custom)451        #expect(BrowsingDataCategory.allCases.filter(\.isWebsiteData) == [.cookiesAndSiteData, .cache])452    }453454    @Test func clearingHistoryForTheLastHourKeepsOlderVisitsAndClearsMatchingShieldStatistics() async throws {455        let (fixture, controls, _, shield) = try await populated()456        let report = try await controls.clear(DataClearRequest(categories: [.history], range: .lastHour))457        #expect(report.deleted == [.history: 2] && report.websiteData == nil)458        #expect(try await fixture.database.history.visitCount() == 3)459        #expect(try await shield.counters(profile: fixture.profile.id, days: 30).isZero)   // they named a visited site460        #expect(try await fixture.database.bookmarks.all(profile: fixture.profile.id).count == 1)461    }462463    @Test func categoriesMapToTheRightDataAndWebsiteDataIsDelegated() async throws {464        let (fixture, controls, permissions, _) = try await populated()465        let profile = fixture.profile.id466        let report = try await controls.clear(DataClearRequest(categories: [.downloadList, .permissions, .cookiesAndSiteData, .cache, .shieldStatistics],467                                                               range: .last7Days, profileID: profile))468        #expect(report.deleted == [.downloadList: 1, .permissions: 1, .shieldStatistics: 1] && report.totalRows == 3)469        #expect(report.websiteData == WebsiteDataInstruction(profileIDs: [profile], cookiesAndSiteData: true, cache: true,470                                                             modifiedSince: fixture.clock.now.addingTimeInterval(-7 * 86_400)))471        #expect(await permissions.verdict(for: .camera, origin: https, profileID: profile) == .ask)472        #expect(await permissions.verdict(for: .popups, origin: https, profileID: profile) == .deny)   // session decision dropped too473        #expect(try await fixture.database.history.visitCount() == 5)474475        let cacheOnly = try await controls.clear(DataClearRequest(categories: [.cache]))476        #expect(cacheOnly.deleted.isEmpty)477        #expect(cacheOnly.websiteData == WebsiteDataInstruction(profileIDs: [], cookiesAndSiteData: false, cache: true, modifiedSince: nil))478    }479480    @Test func clearingIsScopedToAProfile() async throws {481        let (fixture, controls, _, _) = try await populated()482        let other = Profile(name: "Work")483        try await fixture.database.profiles.save(other)484        try await fixture.database.history.recordVisit(NavigationEntry(profileID: other.id, url: URL(string: "https://work.example/")!, visitedAt: fixture.clock.now))485        let report = try await controls.clear(DataClearRequest(categories: [.history, .bookmarks], profileID: fixture.profile.id))486        #expect(report.deleted == [.history: 5, .bookmarks: 1])487        #expect(try await fixture.database.history.visitCount(profile: other.id) == 1)488    }489490    @Test func retentionIsStoredAndApplied() async throws {491        let (fixture, controls, permissions, _) = try await populated()492        #expect(try await controls.historyRetentionDays() == 0)493        #expect(try await controls.applyRetention() == 0)494        #expect(try await controls.setHistoryRetention(days: 30) == 1)   // the 40-day-old visit495        #expect(try await controls.historyRetentionDays() == 30)496        #expect(try await fixture.database.history.visitCount() == 4)497        try await permissions.decide(.allow, for: .location, origin: https, profile: fixture.profile.id, duration: .day)498        fixture.clock.advance(2 * 86_400)499        #expect(try await controls.applyRetention() == 0)500        #expect(try await fixture.database.permissions.decisions(profile: fixture.profile.id).map(\.kind) == [.camera])501        #expect(try await controls.setHistoryRetention(days: -3) == 0)502        #expect(try await controls.historyRetentionDays() == 0)503    }504505    @Test func exportContainsTheDataAndClearEverythingRemovesIt() async throws {506        let (fixture, controls, permissions, _) = try await populated()507        let bundle = try DataLifecycle.decodeBundle(try await controls.exportJSON())508        #expect(bundle.history.count == 5 && bundle.bookmarks.count == 1 && bundle.permissions.count == 1 && bundle.profiles.count == 1)509        let file = FileManager.default.temporaryDirectory.appending(path: "orix-export-\(UUID().uuidString).json")510        defer { try? FileManager.default.removeItem(at: file) }511        try await controls.export(to: file, profile: fixture.profile.id)512        #expect(try DataLifecycle.decodeBundle(Data(contentsOf: file)).history.count == 5)513514        let report = try await controls.clearEverything()515        #expect(report.deleted[.history] == 5 && report.deleted[.bookmarks] == 1)516        #expect(report.websiteData == WebsiteDataInstruction(profileIDs: [], cookiesAndSiteData: true, cache: true, modifiedSince: nil))517        let counts = try await tableCounts(fixture.database)518        for table in ["profiles", "spaces", "tabs", "windows", "history_urls", "history_visits", "bookmarks", "downloads", "permissions", "settings"] {519            #expect(counts[table] == 0, "\(table) not empty")520        }521        #expect(await permissions.verdict(for: .popups, origin: https, profileID: fixture.profile.id) == .deny)522    }523}524
Files main
Menu

Theme