Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : SP ID & Card Vault7// File : SPVaultTests/VaultTests.swift8// Module : Tests9// Repository : https://git.spboucher.ai/sp-id-card-vault10// Project Website : Not specified11// Created : 2026-12-0212// Last Modified : 2026-12-0213//14// Author : Simon-Pierre Boucher15// Position : Professor of Finance16// Institution : Université du Québec en Outaouais (UQO)17// Organization : SP Boucher18// Website : https://spboucher.ai19// Git : https://git.spboucher.ai20//21// Preferred Contact: contact@spboucher.ai22// Development : dev@spboucher.ai23// Support : support@spboucher.ai24// Security/Admin : admin@spboucher.ai25//26// Copyright (c) 202627// Simon-Pierre Boucher28// All rights reserved where applicable. This file is governed by the29// applicable project license, copyright notices and relevant law.30// Existing third-party rights and notices remain unaffected.31//32// License : None specified (no license file in this repository)33//34// Do not embed credentials, private keys, access tokens,35// certificates or confidential personal information.36//37// =============================================================================38// END OF SP BOUCHER SOURCE HEADER39// =============================================================================4041import CryptoKit42import Foundation43import Testing44@testable import SPVault4546@MainActor47struct VaultHarness {48 let root = TestSupport.temporaryRoot()49 let protector = ScriptedKeyProtector()50 static let recovery = "correct horse battery staple 42"5152 func makeVault() -> Vault {53 let vault = Vault(repository: VaultRepository(root: root), protector: protector)54 vault.kdfIterations = 1_00055 vault.bootstrap()56 return vault57 }5859 func demoImages() throws -> CardImages {60 let demo = DemoCardFactory.all()[0]61 return try CardImageCodec.images(front: demo.front, back: demo.back)62 }63}6465@Suite("Vault security engine")66@MainActor67struct VaultTests {68 let harness = VaultHarness()6970 @Test func creationThenLockThenFaceIDUnlock() async throws {71 let vault = harness.makeVault()72 #expect(vault.state == .noVault)73 try await vault.createVault(recoveryPassphrase: VaultHarness.recovery)74 #expect(vault.state == .unlocked)75 try await vault.add(TestSupport.card(), images: TestSupport.images())76 #expect(vault.cards.count == 1)7778 vault.lock()79 #expect(vault.state == .locked)80 #expect(vault.cards.isEmpty)81 #expect(vault.search("aurora").isEmpty)82 #expect(vault.cachedImage(for: UUID(), side: .front, thumbnail: true) == nil)83 #expect(throws: VaultError.locked) { try vault.update(TestSupport.card()) }84 #expect(await vault.image(for: UUID(), side: .front, thumbnail: true) == nil)8586 try await vault.unlock()87 #expect(vault.state == .unlocked)88 #expect(vault.cards.map(\.name) == ["Aurora Infinite"])89 }9091 @Test func refusedFaceIDKeepsTheVaultLocked() async throws {92 let vault = harness.makeVault()93 try await vault.createVault(recoveryPassphrase: nil)94 try await vault.add(TestSupport.card(), images: TestSupport.images())95 vault.lock()96 for error in [KeyProtectorError.authenticationFailed, .cancelled, .biometryLockedOut] {97 harness.protector.setNextError(error)98 await #expect(throws: error) { try await vault.unlock() }99 #expect(vault.state == .locked)100 #expect(vault.cards.isEmpty)101 }102 try await vault.unlock()103 #expect(vault.cards.count == 1)104 }105106 @Test func aKeyThatIsNotTheVaultKeyOpensNothing() async throws {107 let vault = harness.makeVault()108 try await vault.createVault(recoveryPassphrase: nil)109 vault.lock()110 try harness.protector.storeMasterKey(VaultCrypto.keyData(VaultCrypto.randomKey()))111 await #expect(throws: VaultCryptoError.authenticationFailed) { try await vault.unlock() }112 #expect(vault.state == .locked)113 }114115 /// Enrolling a new face invalidates the Keychain item (`biometryCurrentSet`).116 @Test func biometricChangeRequiresRecoveryPassphrase() async throws {117 let vault = harness.makeVault()118 try await vault.createVault(recoveryPassphrase: VaultHarness.recovery)119 try await vault.add(TestSupport.card(), images: TestSupport.images())120 vault.lock()121122 harness.protector.invalidate()123 await #expect(throws: KeyProtectorError.keyInvalidated) { try await vault.unlock() }124 #expect(vault.state == .keyInvalidated)125126 await #expect(throws: VaultStorageError.wrongPassphrase) { try await vault.recover(passphrase: "not the passphrase at all") }127 #expect(vault.state == .keyInvalidated)128129 try await vault.recover(passphrase: VaultHarness.recovery)130 #expect(vault.state == .unlocked)131 #expect(vault.cards.count == 1)132 #expect(harness.protector.masterKeyExists()) // re-bound to the new biometric set133134 vault.lock()135 try await vault.unlock()136 #expect(vault.cards.count == 1)137 }138139 @Test func withoutRecoveryABiometricChangeLeavesOnlyTheBackup() async throws {140 let vault = harness.makeVault()141 try await vault.createVault(recoveryPassphrase: nil)142 vault.lock()143 harness.protector.invalidate()144 vault.refreshLockState()145 #expect(vault.state == .keyInvalidated)146 await #expect(throws: VaultStorageError.noRecoveryConfigured) { try await vault.recover(passphrase: VaultHarness.recovery) }147 }148149 /// Force quit and device restart: a new process finds the vault locked and150 /// everything intact after Face ID.151 @Test func forceQuitAndRestartComeBackLocked() async throws {152 let first = harness.makeVault()153 try await first.createVault(recoveryPassphrase: nil)154 try await first.add(TestSupport.card("One"), images: TestSupport.images())155 try await first.add(TestSupport.card("Two"), images: TestSupport.images(2, back: false))156 first.toggleFavorite(first.cards[0].id)157 // No lock(), no teardown: the process simply goes away.158159 let second = harness.makeVault()160 #expect(second.state == .locked)161 #expect(second.cards.isEmpty)162 try await second.unlock()163 #expect(second.cards.map(\.name) == ["Two", "One"])164 #expect(second.cards[0].isFavorite)165 #expect(second.cards[0].hasBack == false)166 #expect(second.cards[1].hasBack)167 #expect(second.search("two").count == 1)168 }169170 @Test func reauthenticationGoesThroughTheKeyAgain() async throws {171 let vault = harness.makeVault()172 try await vault.createVault(recoveryPassphrase: nil)173 let before = harness.protector.promptCount174 #expect(await vault.reauthenticate(reason: "Reveal"))175 #expect(harness.protector.promptCount == before + 1)176 harness.protector.setNextError(.authenticationFailed)177 #expect(await vault.reauthenticate(reason: "Reveal") == false)178 vault.lock()179 #expect(await vault.reauthenticate(reason: "Reveal") == false)180 }181182 @Test func securityCodesNeverReachStorage() async throws {183 let vault = harness.makeVault()184 try await vault.createVault(recoveryPassphrase: nil)185 var card = TestSupport.card()186 card.fields = [CardField(label: "CVV", value: "737"), CardField(label: "PIN", value: "4821"), CardField(label: "Tier", value: "Gold")]187 try await vault.add(card, images: TestSupport.images())188 #expect(vault.cards[0].fields.map(\.label) == ["Tier"])189 var edited = vault.cards[0]190 edited.fields.append(CardField(label: "cvc", value: "737"))191 #expect(throws: SensitiveDataPolicy.Violation.forbiddenLabel("cvc")) { try vault.update(edited) }192 vault.lock()193 try await vault.unlock()194 #expect(vault.cards[0].fields.map(\.label) == ["Tier"])195 }196197 @Test func deletionOrderingFavoritesAndCategories() async throws {198 let vault = harness.makeVault()199 try await vault.createVault(recoveryPassphrase: nil)200 for name in ["Alpha", "Bravo", "Zulu"] { try await vault.add(TestSupport.card(name), images: TestSupport.images()) }201 #expect(vault.cards.map(\.name) == ["Zulu", "Bravo", "Alpha"])202 vault.move(vault.cards[2].id, before: vault.cards[0].id)203 #expect(vault.cards.map(\.name) == ["Alpha", "Zulu", "Bravo"])204 try vault.addCategory(name: "Travel", symbol: "airplane", tint: .electric)205 let travel = try #require(vault.customCategories.first)206 var moved = vault.cards[0]207 moved.categoryID = travel.id208 try vault.update(moved)209 #expect(vault.search("travel").map(\.name) == ["Alpha"])210 let deleted = vault.cards[1].id211 try vault.delete(deleted)212 #expect(vault.cards.map(\.name) == ["Alpha", "Bravo"])213 #expect(vault.search("zulu").isEmpty)214215 vault.lock()216 try await vault.unlock()217 #expect(vault.cards.map(\.name) == ["Alpha", "Bravo"])218 #expect(vault.category(id: travel.id).name == "Travel")219 try vault.removeCategory(id: travel.id)220 #expect(vault.cards[0].categoryID == CardCategory.banking.id)221 #expect(vault.customCategories.isEmpty)222 }223224 @Test func imagesDecryptOnlyWhileUnlocked() async throws {225 let vault = harness.makeVault()226 try await vault.createVault(recoveryPassphrase: nil)227 let demo = DemoCardFactory.all()[0]228 try await vault.add(demo.card, images: try harness.demoImages())229 let id = vault.cards[0].id230 let thumb = try #require(await vault.image(for: id, side: .front, thumbnail: true))231 #expect(max(thumb.size.width, thumb.size.height) <= CGFloat(CardImageCodec.thumbnailLongEdge))232 #expect(abs(thumb.size.width / thumb.size.height - CardFormat.id1.aspectRatio) < 0.01)233 #expect(await vault.image(for: id, side: .back, thumbnail: false) != nil)234 #expect(vault.cachedImage(for: id, side: .front, thumbnail: true) != nil)235 vault.lock()236 #expect(vault.cachedImage(for: id, side: .front, thumbnail: true) == nil)237 #expect(await vault.image(for: id, side: .front, thumbnail: true) == nil)238 }239240 @Test func securityReportReflectsRealState() async throws {241 let vault = harness.makeVault()242 try await vault.createVault(recoveryPassphrase: VaultHarness.recovery)243 try await vault.add(TestSupport.card(), images: TestSupport.images())244 var report = vault.securityReport()245 #expect(report.encryptionSelfTestPassed)246 #expect(report.keyPresent)247 #expect(report.cardCount == 1)248 #expect(report.recoveryConfigured)249 #expect(report.recoveryIterations == 1_000)250 #expect(report.storage.excludedFromBackup)251 #expect(report.lastBackupAt == nil)252 try await vault.setRecoveryPassphrase(nil)253 report = vault.securityReport()254 #expect(!report.recoveryConfigured)255 vault.lock()256 #expect(!vault.securityReport().encryptionSelfTestPassed) // no key in memory, nothing to test with257 }258259 @Test func eraseRemovesKeyAndFiles() async throws {260 let vault = harness.makeVault()261 try await vault.createVault(recoveryPassphrase: nil)262 try await vault.add(TestSupport.card(), images: TestSupport.images())263 vault.eraseEverything()264 #expect(vault.state == .noVault)265 #expect(!harness.protector.masterKeyExists())266 #expect(!FileManager.default.fileExists(atPath: harness.root.path))267 }268269 @Test func weakRecoveryPassphraseIsRefused() async throws {270 let vault = harness.makeVault()271 await #expect(throws: VaultError.weakPassphrase) { try await vault.createVault(recoveryPassphrase: "password") }272 #expect(vault.state == .noVault)273 harness.protector.setState(.notEnrolled)274 await #expect(throws: VaultError.biometryRequired(.notEnrolled)) { try await vault.createVault(recoveryPassphrase: nil) }275 }276}277278@Suite("Backup and restore")279@MainActor280struct BackupTests {281 static let passphrase = "orbit-lantern-quartz-meadow-71"282283 func contents(_ count: Int = 3) -> BackupContents {284 let cards = (0..<count).map { i -> BackupCard in285 let images = TestSupport.images(UInt8(i), back: i % 2 == 0)286 return BackupCard(card: TestSupport.card("Card \(i)"), front: images.front, frontThumbnail: images.frontThumbnail,287 back: images.back, backThumbnail: images.backThumbnail)288 }289 var manifest = VaultManifest()290 manifest.order = cards.map(\.card.id)291 return BackupContents(createdAt: Date(timeIntervalSince1970: 1_800_000_000), manifest: manifest, cards: cards)292 }293294 @Test func roundTripAndNoClearText() throws {295 let original = contents()296 let file = try BackupArchive.encode(original, passphrase: Self.passphrase, iterations: 1_000)297 #expect(file.prefix(8) == BackupArchive.magic)298 for needle in ["Aurora", "Specimen", "4242", "Card 0", "IMAGE-MARKER", "cardCount"] {299 #expect(file.range(of: Data(needle.utf8)) == nil)300 }301 let header = try BackupArchive.readHeader(file)302 #expect(header.kdf.algorithm == "pbkdf2-hmac-sha256")303 // 1 000 iterations is below the accepted minimum: decoding must refuse it…304 #expect(throws: BackupError.corrupted) { try BackupArchive.decode(file, passphrase: Self.passphrase) }305 // …and a file written with production parameters round-trips.306 let strong = try BackupArchive.encode(original, passphrase: Self.passphrase, iterations: KDFParameters.minimumAcceptedIterations)307 #expect(try BackupArchive.decode(strong, passphrase: Self.passphrase) == original)308 }309310 @Test func wrongPassphraseAndWeakPassphrase() throws {311 let file = try BackupArchive.encode(contents(1), passphrase: Self.passphrase, iterations: KDFParameters.minimumAcceptedIterations)312 #expect(throws: BackupError.wrongPassphrase) { try BackupArchive.decode(file, passphrase: Self.passphrase + "x") }313 #expect(throws: BackupError.weakPassphrase) { try BackupArchive.encode(contents(1), passphrase: "12345678") }314 }315316 @Test func tamperingTruncationAndReorderingAreDetected() throws {317 let file = try BackupArchive.encode(contents(3), passphrase: Self.passphrase, iterations: KDFParameters.minimumAcceptedIterations)318 // Flip one byte in the last record.319 var tampered = file320 tampered[tampered.count - 40] ^= 0x01321 #expect(throws: BackupError.corrupted) { try BackupArchive.decode(tampered, passphrase: Self.passphrase) }322323 // Parse the record table to drop and reorder records.324 var offset = 8 + 2325 func u32(_ data: Data, _ at: Int) -> Int { data.subdata(in: at..<(at + 4)).reduce(0) { ($0 << 8) | Int($1) } }326 let headerLength = u32(file, offset)327 offset += 4 + headerLength328 let prefix = file.prefix(offset)329 var records: [Data] = []330 while offset < file.count {331 let length = u32(file, offset)332 records.append(file.subdata(in: offset..<(offset + 4 + length)))333 offset += 4 + length334 }335 #expect(records.count == 4)336 let truncated = prefix + records[0] + records[1] + records[2]337 #expect(throws: BackupError.corrupted) { try BackupArchive.decode(truncated, passphrase: Self.passphrase) }338 let reordered = prefix + records[0] + records[2] + records[1] + records[3]339 #expect(throws: BackupError.corrupted) { try BackupArchive.decode(reordered, passphrase: Self.passphrase) }340 let onlySummary = prefix + records[0]341 #expect(throws: (any Error).self) { try BackupArchive.decode(onlySummary, passphrase: Self.passphrase) }342343 // Changing the clear header changes the derived key: nothing opens.344 var headerTampered = file345 let range = try #require(headerTampered.range(of: Data("1.0.0".utf8)))346 headerTampered.replaceSubrange(range, with: Data("9.9.9".utf8))347 #expect(throws: BackupError.wrongPassphrase) { try BackupArchive.decode(headerTampered, passphrase: Self.passphrase) }348 }349350 @Test func foreignFilesAndVersions() throws {351 #expect(throws: BackupError.notABackup) { try BackupArchive.decode(Data("PK\u{3}\u{4} not a vault".utf8), passphrase: Self.passphrase) }352 var file = try BackupArchive.encode(contents(1), passphrase: Self.passphrase, iterations: KDFParameters.minimumAcceptedIterations)353 file[9] = 7354 #expect(throws: BackupError.unsupportedVersion(7)) { try BackupArchive.decode(file, passphrase: Self.passphrase) }355 }356357 /// Export on one iPhone, restore on a new one with its own Face ID key.358 @Test func restoreOnANewDevice() async throws {359 let old = VaultHarness()360 let source = old.makeVault()361 source.kdfIterations = KDFParameters.minimumAcceptedIterations362 try await source.createVault(recoveryPassphrase: nil)363 let demos = DemoCardFactory.all().prefix(3)364 for demo in demos.reversed() {365 try await source.add(demo.card, images: try CardImageCodec.images(front: demo.front, back: demo.back))366 }367 try source.addCategory(name: "Travel", symbol: "airplane", tint: .electric)368 let url = try await source.exportBackup(passphrase: Self.passphrase)369 defer { try? FileManager.default.removeItem(at: url.deletingLastPathComponent()) }370 #expect(url.pathExtension == "spvault")371 #expect(source.lastBackupAt != nil)372 let file = try Data(contentsOf: url)373374 let new = VaultHarness()375 let target = new.makeVault()376 try await target.createVault(recoveryPassphrase: nil)377 await #expect(throws: BackupError.wrongPassphrase) { try await target.restoreBackup(file, passphrase: "wrong passphrase 123456", mode: .merge) }378 #expect(target.cards.isEmpty)379 #expect(try await target.restoreBackup(file, passphrase: Self.passphrase, mode: .merge) == 3)380 #expect(target.cards.map(\.name) == source.cards.map(\.name))381 #expect(target.customCategories.map(\.name) == ["Travel"])382 let id = target.cards[0].id383 #expect(await target.image(for: id, side: .front, thumbnail: false) != nil)384 #expect(target.search("aurora").count == 1)385386 // The restored vault is bound to the new device's key, not the old one.387 target.lock()388 try await target.unlock()389 #expect(target.cards.count == 3)390 let oldKey = try await old.protector.loadMasterKey(reason: ""), newKey = try await new.protector.loadMasterKey(reason: "")391 #expect(oldKey != newKey)392393 // Restoring again merges by identity instead of duplicating; replace wipes first.394 #expect(try await target.restoreBackup(file, passphrase: Self.passphrase, mode: .merge) == 3)395 #expect(target.cards.count == 3)396 try await target.add(TestSupport.card("Extra"), images: TestSupport.images())397 #expect(try await target.restoreBackup(file, passphrase: Self.passphrase, mode: .replace) == 3)398 #expect(target.cards.count == 3)399 #expect(!target.cards.contains { $0.name == "Extra" })400 }401}402403@Suite("Expiry reminders")404struct ReminderTests {405 @Test func planUsesOffsetsAndSkipsThePast() {406 let calendar = Calendar(identifier: .gregorian)407 let now = calendar.date(from: DateComponents(year: 2026, month: 12, day: 2, hour: 12))!408 var card = TestSupport.card("Aurora Infinite")409 card.expiry = calendar.date(byAdding: .day, value: 45, to: now)410 card.reminderOffsets = [180, 90, 60, 30, 7, 0]411 let plan = ExpiryReminderScheduler.plan(for: [card], now: now, calendar: calendar)412 #expect(plan.count == 3) // 30, 7 and 0 days before; 180/90/60 are already past413 #expect(plan.map(\.fireDate) == plan.map(\.fireDate).sorted())414 #expect(calendar.component(.hour, from: plan[0].fireDate) == 9)415 var none = card416 none.expiry = nil417 #expect(ExpiryReminderScheduler.plan(for: [none], now: now, calendar: calendar).isEmpty)418 }419420 @Test func notificationTextNeverNamesACard() {421 let now = Date()422 var card = TestSupport.card("Aurora Infinite")423 card.expiry = now.addingTimeInterval(86_400 * 200)424 card.reminderOffsets = AppSettings.reminderChoices425 for reminder in ExpiryReminderScheduler.plan(for: [card], now: now) {426 for secret in ["Aurora", "Infinite", "Specimen", "4242", "Bank"] { #expect(!reminder.body.contains(secret)) }427 #expect(reminder.body.hasPrefix("A document in your vault"))428 }429 }430431 @Test func planIsCappedBelowTheSystemLimit() {432 let now = Date()433 let cards = (0..<40).map { i -> Card in434 var card = TestSupport.card("Card \(i)")435 card.expiry = now.addingTimeInterval(86_400 * Double(200 + i))436 card.reminderOffsets = AppSettings.reminderChoices437 return card438 }439 #expect(ExpiryReminderScheduler.plan(for: cards, now: now).count == ExpiryReminderScheduler.maximumPending)440 }441442 @Test func expiryStatus() {443 let now = Date()444 var card = TestSupport.card()445 card.expiry = now.addingTimeInterval(86_400 * 200); #expect(card.expiryStatus(now: now) == .valid)446 card.expiry = now.addingTimeInterval(86_400 * 30); #expect(card.expiryStatus(now: now) == .expiringSoon)447 card.expiry = now; #expect(card.expiryStatus(now: now) == .expiringSoon)448 card.expiry = now.addingTimeInterval(-86_400 * 2); #expect(card.expiryStatus(now: now) == .expired)449 card.expiry = nil; #expect(card.expiryStatus(now: now) == .noExpiry)450 }451}452