DomainDigTests/HistoryStoreTests.swift

362 lines · 17726 bytes

  1import XCTest
  2@testable import DomainDig
  3
  4/// Review Focus #2: a history store at its tier cap must not drop or duplicate
  5/// rows across a save, an auto-prune or a backup import, and a restore must
  6/// round-trip every field the UI reads. Pro+ at 2000 snapshots is the worst
  7/// case, not the 250 the store caps at today.
  8///
  9/// These run against the store as it is. W5 moves the substrate underneath
 10/// `DomainDataPortabilityService`'s API, and this is the gate that says the
 11/// move lost nothing — so it comes before the switch, not after.
 12final class HistoryStoreTests: XCTestCase {
 13
 14    /// The Pro+ retention tier D1 settled on, and the size every assertion here
 15    /// is about.
 16    private static let proPlusCap = 2000
 17
 18    private var suiteName = ""
 19    private var scratch = UserDefaults.standard
 20
 21    /// History lives in files now, so a scratch `UserDefaults` is no longer
 22    /// enough to keep a test out of the real store — it needs its own
 23    /// directory too.
 24    private var historyLocation = HistoryFileStore.Location.default
 25
 26    override func setUpWithError() throws {
 27        try super.setUpWithError()
 28        suiteName = "net.cleberg.DomainDig.tests.\(UUID().uuidString)"
 29        scratch = try XCTUnwrap(UserDefaults(suiteName: suiteName))
 30        historyLocation = Self.scratchLocation()
 31    }
 32
 33    override func tearDown() {
 34        UserDefaults.standard.removePersistentDomain(forName: suiteName)
 35        HistoryFileStore.removeAll(at: historyLocation)
 36        super.tearDown()
 37    }
 38
 39    private static func scratchLocation() -> HistoryFileStore.Location {
 40        HistoryFileStore.Location(
 41            root: URL(fileURLWithPath: NSTemporaryDirectory())
 42                .appendingPathComponent("DomainDigTestHistory-\(UUID().uuidString)", isDirectory: true)
 43        )
 44    }
 45
 46    private func entries(_ count: Int) -> [HistoryEntry] {
 47        (0..<count).map { SnapshotFixture.historyEntry(index: $0) }
 48    }
 49
 50    // MARK: Round trip at the cap
 51
 52    func testTwoThousandEntriesSurviveASaveAndLoad() {
 53        let saved = entries(Self.proPlusCap)
 54
 55        DomainDataPortabilityService.saveHistoryEntries(saved, defaults: scratch, historyLocation: historyLocation)
 56        let loaded = DomainDataPortabilityService.loadHistoryEntries(defaults: scratch, historyLocation: historyLocation)
 57
 58        XCTAssertEqual(loaded.count, Self.proPlusCap, "the store dropped or added rows")
 59        XCTAssertEqual(Set(loaded.map(\.id)), Set(saved.map(\.id)), "the store changed which rows exist")
 60    }
 61
 62    /// The store sorts on load, newest first. Every reader downstream — the
 63    /// history list, the dashboard's recent activity, the diff view's
 64    /// "previous snapshot" — takes that for granted.
 65    func testTheStoreReturnsRowsNewestFirst() {
 66        DomainDataPortabilityService.saveHistoryEntries(entries(Self.proPlusCap), defaults: scratch, historyLocation: historyLocation)
 67
 68        let loaded = DomainDataPortabilityService.loadHistoryEntries(defaults: scratch, historyLocation: historyLocation)
 69
 70        XCTAssertEqual(loaded.map(\.timestamp), loaded.map(\.timestamp).sorted(by: >))
 71        XCTAssertEqual(loaded.first?.snapshotIndex, Self.proPlusCap - 1)
 72        XCTAssertEqual(loaded.last?.snapshotIndex, 0)
 73    }
 74
 75    func testNoRowIsDuplicatedAcrossRepeatedSaves() {
 76        let saved = entries(Self.proPlusCap)
 77
 78        DomainDataPortabilityService.saveHistoryEntries(saved, defaults: scratch, historyLocation: historyLocation)
 79        let once = DomainDataPortabilityService.loadHistoryEntries(defaults: scratch, historyLocation: historyLocation)
 80        DomainDataPortabilityService.saveHistoryEntries(once, defaults: scratch, historyLocation: historyLocation)
 81        let twice = DomainDataPortabilityService.loadHistoryEntries(defaults: scratch, historyLocation: historyLocation)
 82
 83        XCTAssertEqual(twice.count, Self.proPlusCap)
 84        XCTAssertEqual(Set(twice.map(\.id)).count, Self.proPlusCap, "a row was duplicated")
 85        XCTAssertEqual(twice.map(\.id), once.map(\.id), "a second save reordered the store")
 86    }
 87
 88    /// Every field the UI reads, on an entry that has all of them set. A
 89    /// substrate change that silently lost one section would still pass a
 90    /// count assertion.
 91    func testEveryPopulatedFieldSurvivesTheRoundTrip() throws {
 92        let original = SnapshotFixture.historyEntry(index: 7)
 93
 94        DomainDataPortabilityService.saveHistoryEntries([original], defaults: scratch, historyLocation: historyLocation)
 95        let restored = try XCTUnwrap(
 96            DomainDataPortabilityService.loadHistoryEntries(defaults: scratch, historyLocation: historyLocation).first
 97        )
 98
 99        XCTAssertEqual(restored.id, original.id)
100        XCTAssertEqual(restored.domain, original.domain)
101        XCTAssertEqual(restored.timestamp, original.timestamp)
102        XCTAssertEqual(restored.trackedDomainID, original.trackedDomainID)
103        XCTAssertEqual(restored.note, original.note)
104
105        XCTAssertEqual(restored.dnsSections.count, original.dnsSections.count)
106        XCTAssertEqual(restored.dnsSections.map(\.recordType), original.dnsSections.map(\.recordType))
107        XCTAssertEqual(
108            restored.dnsSections.flatMap { $0.records.map(\.value) },
109            original.dnsSections.flatMap { $0.records.map(\.value) }
110        )
111
112        XCTAssertEqual(restored.sslInfo?.commonName, original.sslInfo?.commonName)
113        XCTAssertEqual(restored.sslInfo?.issuer, original.sslInfo?.issuer)
114        XCTAssertEqual(restored.sslInfo?.daysUntilExpiry, original.sslInfo?.daysUntilExpiry)
115        XCTAssertEqual(restored.sslInfo?.subjectAltNames, original.sslInfo?.subjectAltNames)
116
117        XCTAssertEqual(restored.httpHeaders.map(\.name), original.httpHeaders.map(\.name))
118        XCTAssertEqual(restored.httpHeaders.map(\.value), original.httpHeaders.map(\.value))
119        XCTAssertEqual(restored.reachabilityResults.map(\.port), original.reachabilityResults.map(\.port))
120        XCTAssertEqual(restored.reachabilityResults.map(\.latencyMs), original.reachabilityResults.map(\.latencyMs))
121
122        XCTAssertEqual(restored.ipGeolocation?.ip, original.ipGeolocation?.ip)
123        XCTAssertEqual(restored.ipGeolocation?.countryName, original.ipGeolocation?.countryName)
124        XCTAssertEqual(restored.ipGeolocation?.org, original.ipGeolocation?.org)
125
126        XCTAssertEqual(restored.ptrRecord, original.ptrRecord)
127        XCTAssertEqual(restored.redirectChain.map(\.url), original.redirectChain.map(\.url))
128        XCTAssertEqual(restored.redirectChain.map(\.isFinal), original.redirectChain.map(\.isFinal))
129        XCTAssertEqual(restored.subdomains.map(\.hostname), original.subdomains.map(\.hostname))
130        XCTAssertEqual(restored.hstsPreloaded, original.hstsPreloaded)
131
132        XCTAssertEqual(restored.priorProviders, original.priorProviders)
133        XCTAssertEqual(restored.riskSignals.map(\.id), original.riskSignals.map(\.id))
134        XCTAssertEqual(restored.riskSignals.map(\.severity), original.riskSignals.map(\.severity))
135
136        XCTAssertEqual(restored.dataSources, original.dataSources)
137        XCTAssertEqual(restored.resolverDisplayName, original.resolverDisplayName)
138        XCTAssertEqual(restored.resolverURLString, original.resolverURLString)
139        XCTAssertEqual(restored.totalLookupDurationMs, original.totalLookupDurationMs)
140
141        XCTAssertEqual(restored.primaryIP, original.primaryIP)
142        XCTAssertEqual(restored.finalRedirectURL, original.finalRedirectURL)
143        XCTAssertEqual(restored.tlsStatusSummary, original.tlsStatusSummary)
144        XCTAssertEqual(restored.snapshotIndex, original.snapshotIndex)
145        XCTAssertEqual(restored.changeCount, original.changeCount)
146    }
147
148    // MARK: Backup and restore at the cap
149
150    func testABackupAtTheCapRestoresEveryRow() throws {
151        let saved = entries(Self.proPlusCap)
152        DomainDataPortabilityService.saveHistoryEntries(saved, defaults: scratch, historyLocation: historyLocation)
153
154        let backup = try DomainDataPortabilityService.backupData(defaults: scratch, historyLocation: historyLocation)
155
156        let restoreName = "net.cleberg.DomainDig.tests.\(UUID().uuidString)"
157        defer { UserDefaults.standard.removePersistentDomain(forName: restoreName) }
158        let restoreStore = try XCTUnwrap(UserDefaults(suiteName: restoreName))
159        let restoreLocation = Self.scratchLocation()
160        defer { HistoryFileStore.removeAll(at: restoreLocation) }
161
162        let preview = try DomainDataPortabilityService.prepareImport(
163            data: backup,
164            fileName: "backup.json",
165            mode: .replace,
166            defaults: restoreStore,
167            historyLocation: restoreLocation
168        )
169        _ = try DomainDataPortabilityService.applyImport(
170            preview,
171            mode: .replace,
172            defaults: restoreStore,
173            historyLocation: restoreLocation
174        )
175
176        let restored = DomainDataPortabilityService.loadHistoryEntries(
177            defaults: restoreStore,
178            historyLocation: restoreLocation
179        )
180        XCTAssertEqual(restored.count, Self.proPlusCap, "the backup round trip changed the row count")
181        XCTAssertEqual(Set(restored.map(\.id)), Set(saved.map(\.id)), "the backup round trip changed which rows exist")
182    }
183
184    /// A merge import of a backup of the same store must not double every row.
185    func testMergingABackupOfTheSameStoreDoesNotDuplicateRows() throws {
186        let saved = entries(500)
187        DomainDataPortabilityService.saveHistoryEntries(saved, defaults: scratch, historyLocation: historyLocation)
188
189        let backup = try DomainDataPortabilityService.backupData(defaults: scratch, historyLocation: historyLocation)
190        let preview = try DomainDataPortabilityService.prepareImport(
191            data: backup,
192            fileName: "backup.json",
193            mode: .merge,
194            defaults: scratch,
195            historyLocation: historyLocation
196        )
197        _ = try DomainDataPortabilityService.applyImport(preview, mode: .merge, defaults: scratch, historyLocation: historyLocation)
198
199        let merged = DomainDataPortabilityService.loadHistoryEntries(defaults: scratch, historyLocation: historyLocation)
200        XCTAssertEqual(merged.count, 500, "merging a backup of the same store duplicated rows")
201        XCTAssertEqual(Set(merged.map(\.id)).count, 500)
202    }
203
204    // MARK: The v2 migration off UserDefaults
205
206    /// An install that predates the file store has its history in one
207    /// `UserDefaults` blob. The migration must move every row and then clear
208    /// the key, not before.
209    func testTheMigrationMovesHistoryOutOfUserDefaults() throws {
210        let saved = entries(250)
211        let blob = try JSONEncoder().encode(saved)
212        scratch.set(blob, forKey: DomainDataPortabilityService.legacyHistoryBlobKey)
213        scratch.set(1, forKey: DataMigrationService.storeSchemaVersionKey)
214
215        DataMigrationService.migrateIfNeeded(defaults: scratch, historyLocation: historyLocation)
216
217        XCTAssertNil(
218            scratch.data(forKey: DomainDataPortabilityService.legacyHistoryBlobKey),
219            "the legacy blob survived the migration"
220        )
221        let moved = DomainDataPortabilityService.loadHistoryEntries(
222            defaults: scratch,
223            historyLocation: historyLocation
224        )
225        XCTAssertEqual(Set(moved.map(\.id)), Set(saved.map(\.id)))
226    }
227
228    func testTheMigrationIsSafeOnAnEmptyStore() {
229        scratch.set(1, forKey: DataMigrationService.storeSchemaVersionKey)
230
231        DataMigrationService.migrateIfNeeded(defaults: scratch, historyLocation: historyLocation)
232
233        XCTAssertEqual(DataMigrationService.storeSchemaVersion(defaults: scratch), DataMigrationService.currentStoreSchemaVersion)
234    }
235
236    /// Running it twice must not resurrect or duplicate anything.
237    func testTheMigrationIsIdempotent() throws {
238        let saved = entries(50)
239        scratch.set(try JSONEncoder().encode(saved), forKey: DomainDataPortabilityService.legacyHistoryBlobKey)
240        scratch.set(1, forKey: DataMigrationService.storeSchemaVersionKey)
241
242        DataMigrationService.migrateIfNeeded(defaults: scratch, historyLocation: historyLocation)
243        DataMigrationService.migrateIfNeeded(defaults: scratch, historyLocation: historyLocation)
244
245        let moved = DomainDataPortabilityService.loadHistoryEntries(defaults: scratch, historyLocation: historyLocation)
246        XCTAssertEqual(moved.count, 50)
247    }
248
249    // MARK: Per-entry writes
250
251    /// The reason for the directory: appending one snapshot must not rewrite
252    /// the rest. Measured at the Pro+ cap, 23 ms against 656 ms.
253    func testAppendingOneSnapshotLeavesTheOthersAlone() {
254        let existing = entries(100)
255        DomainDataPortabilityService.saveHistoryEntries(existing, defaults: scratch, historyLocation: historyLocation)
256
257        let fresh = SnapshotFixture.historyEntry(index: 5000)
258        DomainDataPortabilityService.appendHistoryEntry(
259            fresh,
260            cap: 250,
261            defaults: scratch,
262            historyLocation: historyLocation
263        )
264
265        let loaded = DomainDataPortabilityService.loadHistoryEntries(defaults: scratch, historyLocation: historyLocation)
266        XCTAssertEqual(loaded.count, 101)
267        XCTAssertTrue(loaded.contains { $0.id == fresh.id })
268        XCTAssertEqual(Set(existing.map(\.id)).subtracting(loaded.map(\.id)), [])
269    }
270
271    func testUpdatingOneSnapshotChangesOnlyThatRow() throws {
272        var saved = entries(20)
273        DomainDataPortabilityService.saveHistoryEntries(saved, defaults: scratch, historyLocation: historyLocation)
274
275        saved[3].note = "edited"
276        DomainDataPortabilityService.updateHistoryEntry(saved[3], defaults: scratch, historyLocation: historyLocation)
277
278        let loaded = DomainDataPortabilityService.loadHistoryEntries(defaults: scratch, historyLocation: historyLocation)
279        XCTAssertEqual(loaded.count, 20)
280        let edited = try XCTUnwrap(loaded.first { $0.id == saved[3].id })
281        XCTAssertEqual(edited.note, "edited")
282        XCTAssertEqual(loaded.filter { $0.note == "edited" }.count, 1)
283    }
284
285    func testRemovingSnapshotsDropsOnlyThoseRows() {
286        let saved = entries(30)
287        DomainDataPortabilityService.saveHistoryEntries(saved, defaults: scratch, historyLocation: historyLocation)
288
289        let doomed = Set(saved.prefix(5).map(\.id))
290        DomainDataPortabilityService.removeHistoryEntries(ids: doomed, defaults: scratch, historyLocation: historyLocation)
291
292        let loaded = DomainDataPortabilityService.loadHistoryEntries(defaults: scratch, historyLocation: historyLocation)
293        XCTAssertEqual(loaded.count, 25)
294        XCTAssertTrue(Set(loaded.map(\.id)).isDisjoint(with: doomed))
295    }
296
297    /// The index is what a list view reads, and it must agree with the files.
298    func testTheIndexMatchesTheStoredEntries() {
299        let saved = entries(120)
300        DomainDataPortabilityService.saveHistoryEntries(saved, defaults: scratch, historyLocation: historyLocation)
301
302        let index = DomainDataPortabilityService.loadHistoryIndex(defaults: scratch, historyLocation: historyLocation)
303        let full = DomainDataPortabilityService.loadHistoryEntries(defaults: scratch, historyLocation: historyLocation)
304
305        XCTAssertEqual(index.map(\.id), full.map(\.id))
306        XCTAssertEqual(index.map(\.domain), full.map(\.domain))
307        XCTAssertEqual(index.map(\.timestamp), full.map(\.timestamp))
308    }
309
310    /// Append is the only writer that prunes: it adds the row that pushes the
311    /// oldest one past the limit, so it is the only one that can delete it.
312    func testAppendingPastTheCapDropsTheOldestRow() {
313        let saved = entries(250)
314        DomainDataPortabilityService.saveHistoryEntries(saved, defaults: scratch, historyLocation: historyLocation)
315        let oldest = DomainDataPortabilityService.loadHistoryIndex(
316            defaults: scratch,
317            historyLocation: historyLocation
318        ).last
319
320        DomainDataPortabilityService.appendHistoryEntry(
321            SnapshotFixture.historyEntry(index: 7000),
322            cap: 250,
323            defaults: scratch,
324            historyLocation: historyLocation
325        )
326
327        let loaded = DomainDataPortabilityService.loadHistoryIndex(defaults: scratch, historyLocation: historyLocation)
328        XCTAssertEqual(loaded.count, 250)
329        XCTAssertFalse(loaded.contains { $0.id == oldest?.id }, "the oldest row survived the cap")
330    }
331
332    /// A full rewrite stores what it is given. The old `UserDefaults` store
333    /// had no cap here either, and a backup import that quietly truncated a
334    /// user's history to 250 rows would be data loss.
335    func testAFullRewriteDoesNotImposeACap() {
336        DomainDataPortabilityService.saveHistoryEntries(
337            entries(Self.proPlusCap),
338            defaults: scratch,
339            historyLocation: historyLocation
340        )
341
342        XCTAssertEqual(
343            DomainDataPortabilityService.loadHistoryIndex(
344                defaults: scratch,
345                historyLocation: historyLocation
346            ).count,
347            Self.proPlusCap
348        )
349    }
350
351    // MARK: Validation at the cap
352
353    func testValidationAcceptsAStoreAtTheCap() throws {
354        let saved = entries(Self.proPlusCap)
355        DomainDataPortabilityService.saveHistoryEntries(saved, defaults: scratch, historyLocation: historyLocation)
356
357        let backup = try DomainDataPortabilityService.backupData(defaults: scratch, historyLocation: historyLocation)
358        let report = try DomainDataPortabilityService.validateBackup(data: backup)
359
360        XCTAssertTrue(report.errors.isEmpty, "a store at the Pro+ cap failed validation: \(report.errors)")
361    }
362}