Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : SP ID & Card Vault7// File : SPVaultTests/StorageTests.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 SPVault4546enum TestSupport {47 static func temporaryRoot() -> URL {48 URL.temporaryDirectory.appending(path: "spvault-tests-\(UUID().uuidString)", directoryHint: .isDirectory)49 }5051 static func images(_ seed: UInt8 = 1, back: Bool = true) -> CardImages {52 // Recognisable byte patterns so plaintext leaks would be found on disk.53 let front = Data(repeating: 0xA0 | (seed & 0x0F), count: 4096) + Data("FRONT-IMAGE-MARKER".utf8)54 let backData = Data(repeating: 0xB0 | (seed & 0x0F), count: 4096) + Data("BACK-IMAGE-MARKER".utf8)55 return CardImages(front: front, frontThumbnail: Data("FRONT-THUMB-MARKER".utf8) + Data(repeating: 1, count: 512),56 back: back ? backData : nil, backThumbnail: back ? Data("BACK-THUMB-MARKER".utf8) : nil)57 }5859 static func card(_ name: String = "Aurora Infinite", kind: CardKind = .creditCard) -> Card {60 var card = Card(name: name, kind: kind)61 card.issuer = "Aurora Bank"62 card.holderName = "Alex Specimen"63 card.number = "4242424242424242"64 card.notes = "Fictitious test card"65 card.expiry = Date(timeIntervalSince1970: 1_900_000_000)66 return card67 }6869 static func allFileContents(_ root: URL) -> [Data] {70 let walker = FileManager.default.enumerator(at: root, includingPropertiesForKeys: [.isRegularFileKey])!71 return walker.compactMap { $0 as? URL }.filter { (try? $0.resourceValues(forKeys: [.isRegularFileKey]).isRegularFile) == true }72 .compactMap { try? Data(contentsOf: $0) }73 }74}7576@Suite("Encrypted storage")77struct StorageTests {78 let root = TestSupport.temporaryRoot()79 let master = VaultCrypto.randomKey()80 var repository: VaultRepository { VaultRepository(root: root) }8182 init() throws {83 try VaultRepository(root: root).create(masterKey: master, recoveryPassphrase: "correct horse battery staple 42", kdfIterations: 1_000)84 }8586 @Test func cardRoundTrip() throws {87 let card = TestSupport.card(), images = TestSupport.images()88 try repository.insert(card, images: images, masterKey: master)89 let loaded = try repository.loadAllCards(masterKey: master)90 #expect(loaded.damaged.isEmpty)91 #expect(loaded.cards.count == 1)92 var expected = card93 expected.hasBack = true94 #expect(loaded.cards[0] == expected)95 #expect(try repository.loadImage(cardID: card.id, side: .front, thumbnail: false, masterKey: master) == images.front)96 #expect(try repository.loadImage(cardID: card.id, side: .back, thumbnail: false, masterKey: master) == images.back)97 #expect(try repository.loadImage(cardID: card.id, side: .front, thumbnail: true, masterKey: master) == images.frontThumbnail)98 }99100 @Test func nothingSensitiveIsWrittenInClear() throws {101 try repository.insert(TestSupport.card(), images: TestSupport.images(), masterKey: master)102 var index = SearchIndex()103 index.index(TestSupport.card(), categoryName: "My Banking")104 try repository.saveSearchIndex(index, masterKey: master)105 let needles = ["Aurora", "Specimen", "4242", "Fictitious", "IMAGE-MARKER", "THUMB-MARKER", "aurora", "banking"].map { Data($0.utf8) }106 let files = TestSupport.allFileContents(root)107 #expect(files.count >= 8)108 for file in files {109 for needle in needles { #expect(file.range(of: needle) == nil) }110 #expect(file.range(of: Data(repeating: 0xA1, count: 64)) == nil)111 }112 }113114 @Test func wrongMasterKeyOpensNothing() throws {115 try repository.insert(TestSupport.card(), images: TestSupport.images(), masterKey: master)116 let other = VaultCrypto.randomKey()117 #expect(throws: VaultCryptoError.authenticationFailed) { try repository.loadManifest(masterKey: other) }118 let loaded = try repository.loadAllCards(masterKey: other)119 #expect(loaded.cards.isEmpty)120 #expect(loaded.damaged.count == 1)121 }122123 @Test func alteredFilesAreReportedAsDamaged() throws {124 let card = TestSupport.card()125 try repository.insert(card, images: TestSupport.images(), masterKey: master)126 let meta = root.appending(path: "cards/\(card.id.uuidString)/meta")127 var bytes = try Data(contentsOf: meta)128 bytes[bytes.count / 2] ^= 0x01129 try bytes.write(to: meta)130 let loaded = try repository.loadAllCards(masterKey: master)131 #expect(loaded.cards.isEmpty)132 #expect(loaded.damaged == [card.id])133134 let front = root.appending(path: "cards/\(card.id.uuidString)/front")135 var image = try Data(contentsOf: front)136 image[40] ^= 0x80137 try image.write(to: front)138 #expect(throws: VaultCryptoError.authenticationFailed) {139 try repository.loadImage(cardID: card.id, side: .front, thumbnail: false, masterKey: master)140 }141 }142143 @Test func filesCannotBeSwappedBetweenCards() throws {144 let a = TestSupport.card("A"), b = TestSupport.card("B")145 try repository.insert(a, images: TestSupport.images(1), masterKey: master)146 try repository.insert(b, images: TestSupport.images(2), masterKey: master)147 let fm = FileManager.default148 let dirA = root.appending(path: "cards/\(a.id.uuidString)"), dirB = root.appending(path: "cards/\(b.id.uuidString)")149 // Move B's whole directory content (key included) over A's.150 try fm.removeItem(at: dirA)151 try fm.copyItem(at: dirB, to: dirA)152 let loaded = try repository.loadAllCards(masterKey: master)153 #expect(loaded.cards.map(\.name) == ["B"])154 #expect(loaded.damaged == [a.id])155 }156157 @Test func eachCardHasItsOwnKey() throws {158 let a = TestSupport.card("A"), b = TestSupport.card("B")159 try repository.insert(a, images: TestSupport.images(), masterKey: master)160 try repository.insert(b, images: TestSupport.images(), masterKey: master)161 let keyA = try Data(contentsOf: root.appending(path: "cards/\(a.id.uuidString)/key"))162 let keyB = try Data(contentsOf: root.appending(path: "cards/\(b.id.uuidString)/key"))163 #expect(keyA != keyB)164 // Same plaintext photograph, different ciphertext.165 let frontA = try Data(contentsOf: root.appending(path: "cards/\(a.id.uuidString)/front"))166 let frontB = try Data(contentsOf: root.appending(path: "cards/\(b.id.uuidString)/front"))167 #expect(frontA.suffix(64) != frontB.suffix(64))168 }169170 @Test func deletionRemovesKeyAndFiles() throws {171 let card = TestSupport.card()172 try repository.insert(card, images: TestSupport.images(), masterKey: master)173 try repository.delete(card.id)174 #expect(!FileManager.default.fileExists(atPath: root.appending(path: "cards/\(card.id.uuidString)").path))175 #expect(try repository.loadAllCards(masterKey: master).cards.isEmpty)176 #expect(throws: VaultStorageError.cardNotFound) { try repository.loadCard(card.id, masterKey: master) }177 #expect(throws: VaultStorageError.cardNotFound) { try repository.delete(card.id) }178 }179180 @Test func updateAndImageReplacement() throws {181 var card = TestSupport.card()182 try repository.insert(card, images: TestSupport.images(), masterKey: master)183 card.name = "Renamed"184 card.isFavorite = true185 card.hasBack = true186 try repository.update(card, masterKey: master)187 #expect(try repository.loadCard(card.id, masterKey: master).name == "Renamed")188 try repository.setImage(nil, thumbnail: nil, side: .back, cardID: card.id, masterKey: master)189 #expect(throws: VaultStorageError.imageMissing) {190 try repository.loadImage(cardID: card.id, side: .back, thumbnail: false, masterKey: master)191 }192 try repository.setImage(Data("NEW".utf8), thumbnail: Data("T".utf8), side: .back, cardID: card.id, masterKey: master)193 #expect(try repository.loadImage(cardID: card.id, side: .back, thumbnail: false, masterKey: master) == Data("NEW".utf8))194 }195196 /// The process dies (or the write fails) part-way through saving a new card.197 @Test func interruptedWriteLeavesNoPartialCard() throws {198 final class Counter: @unchecked Sendable { var writes = 0 }199 for failAt in 1...5 {200 let counter = Counter()201 var failing = VaultRepository(root: root)202 failing.writer = { data, url in203 counter.writes += 1204 if counter.writes == failAt { throw CocoaError(.fileWriteUnknown) }205 try VaultRepository.protectedAtomicWrite(data, url)206 }207 let card = TestSupport.card("Interrupted \(failAt)")208 #expect(throws: CocoaError.self) { try failing.insert(card, images: TestSupport.images(), masterKey: master) }209 #expect(try repository.loadAllCards(masterKey: master).cards.isEmpty)210 #expect(repository.cardIDs().isEmpty)211 }212 // A crash can also leave the staging directory behind: it is ignored, then purged.213 let staging = root.appending(path: "cards/.staging-\(UUID().uuidString)")214 try FileManager.default.createDirectory(at: staging, withIntermediateDirectories: true)215 try Data("partial".utf8).write(to: staging.appending(path: "meta"))216 #expect(try repository.loadAllCards(masterKey: master).cards.isEmpty)217 repository.removeStagingLeftovers()218 #expect(!FileManager.default.fileExists(atPath: staging.path))219 }220221 @Test func fullDiskFailsCleanlyAndKeepsExistingData() throws {222 let existing = TestSupport.card("Existing")223 try repository.insert(existing, images: TestSupport.images(), masterKey: master)224 var full = VaultRepository(root: root)225 full.writer = { _, _ in throw CocoaError(.fileWriteOutOfSpace) }226 #expect(throws: CocoaError.self) { try full.insert(TestSupport.card("New"), images: TestSupport.images(), masterKey: master) }227 var changed = existing228 changed.name = "Changed"229 #expect(throws: CocoaError.self) { try full.update(changed, masterKey: master) }230 let loaded = try repository.loadAllCards(masterKey: master)231 #expect(loaded.cards.map(\.name) == ["Existing"])232 #expect(loaded.damaged.isEmpty)233 }234235 @Test func recoveryPassphraseUnwrapsTheMasterKey() throws {236 let recovered = try repository.recoverMasterKey(passphrase: "correct horse battery staple 42")237 #expect(VaultCrypto.keyData(recovered) == VaultCrypto.keyData(master))238 #expect(throws: VaultStorageError.wrongPassphrase) { try repository.recoverMasterKey(passphrase: "correct horse battery staple 43") }239 try repository.setRecovery(passphrase: "another long passphrase 2026!", masterKey: master, kdfIterations: 1_000)240 #expect(throws: VaultStorageError.wrongPassphrase) { try repository.recoverMasterKey(passphrase: "correct horse battery staple 42") }241 #expect(VaultCrypto.keyData(try repository.recoverMasterKey(passphrase: "another long passphrase 2026!")) == VaultCrypto.keyData(master))242 try repository.setRecovery(passphrase: nil, masterKey: master)243 #expect(throws: VaultStorageError.noRecoveryConfigured) { try repository.recoverMasterKey(passphrase: "another long passphrase 2026!") }244 }245246 @Test func headerHoldsNoCardData() throws {247 try repository.insert(TestSupport.card(), images: TestSupport.images(), masterKey: master)248 let text = String(decoding: try Data(contentsOf: root.appending(path: "vault.json")), as: UTF8.self)249 #expect(text.contains("formatVersion"))250 for needle in ["Aurora", "Specimen", "4242"] { #expect(!text.contains(needle)) }251 #expect(try repository.readHeader().recoveryKDF?.algorithm == "pbkdf2-hmac-sha256")252 }253254 @Test func vaultDirectoryIsExcludedFromBackups() throws {255 #expect(repository.storageReport().excludedFromBackup)256 try repository.insert(TestSupport.card(), images: TestSupport.images(), masterKey: master)257 let report = repository.storageReport()258 #expect(report.cardCount == 1)259 #expect(report.fileCount >= 8)260 #expect(report.totalBytes > 8_000)261 }262263 @Test func newerFormatIsRefused() throws {264 var header = try repository.readHeader()265 header.formatVersion = 99266 try JSONEncoder.vault.encode(header).write(to: root.appending(path: "vault.json"))267 #expect(throws: VaultStorageError.unsupportedFormat(99)) { try repository.readHeader() }268 }269270 @Test func schemaOneRecordsMigrate() throws {271 let id = UUID()272 let legacy: [String: Any] = ["schemaVersion": 1, "id": id.uuidString, "name": "Old Card", "kind": "creditCard", "categoryID": "banking",273 "issuer": "Aurora Bank", "lastFour": "4242", "notes": "", "dominantColor": ["r": 0.1, "g": 0.2, "b": 0.3],274 "format": ["id1": [String: Any]()], "isFavorite": true, "createdAt": 700_000_000.0, "modifiedAt": 700_000_000.0]275 let migrated = try CardMigrator.decode(try JSONSerialization.data(withJSONObject: legacy))276 #expect(migrated.schemaVersion == Card.currentSchema)277 #expect(migrated.id == id)278 #expect(migrated.number == "4242")279 #expect(migrated.last4 == "4242")280 #expect(migrated.reminderOffsets == [30, 7, 0])281 #expect(migrated.isFavorite)282 #expect(migrated.format == .id1)283 let future = try JSONSerialization.data(withJSONObject: ["schemaVersion": 99])284 #expect(throws: VaultStorageError.unsupportedFormat(99)) { try CardMigrator.decode(future) }285 }286}287288@Suite("Search index")289struct SearchIndexTests {290 func makeIndex() -> (SearchIndex, [Card]) {291 var credit = TestSupport.card("Aurora Infinite")292 credit.expiry = Calendar(identifier: .gregorian).date(from: DateComponents(year: 2028, month: 5, day: 31))293 var licence = Card(name: "Driver's Licence", kind: .driverLicense)294 licence.issuer = "Northwind Motor Vehicles"295 licence.number = "S1234-140288-07"296 licence.notes = "Renew online, bring vision test"297 licence.fields = [CardField(label: "Class", value: "5"), CardField(label: "Secret", value: "hidden-value", isSensitive: true)]298 var cafe = Card(name: "Café Élan", kind: .loyaltyCard)299 cafe.issuer = "Élan Coffee"300 var index = SearchIndex()301 index.index(credit, categoryName: "My Banking")302 index.index(licence, categoryName: "My Identity")303 index.index(cafe, categoryName: "My Other Cards")304 return (index, [credit, licence, cafe])305 }306307 @Test func findsByEveryDocumentedField() {308 let (index, cards) = makeIndex()309 #expect(index.search("aurora").first == cards[0].id) // name310 #expect(index.search("banking") == [cards[0].id]) // category311 #expect(index.search("northwind") == [cards[1].id]) // issuer312 #expect(index.search("4242") == [cards[0].id]) // last four313 #expect(index.search("2028") == [cards[0].id]) // expiry year314 #expect(index.search("05/28") == [cards[0].id]) // expiry MM/YY315 #expect(index.search("may") == [cards[0].id]) // expiry month316 #expect(index.search("vision") == [cards[1].id]) // notes317 #expect(index.search("class") == [cards[1].id]) // allowed metadata318 #expect(index.search("licence") == [cards[1].id])319 }320321 @Test func isAccentAndCaseInsensitiveWithPrefixes() {322 let (index, cards) = makeIndex()323 #expect(index.search("cafe elan") == [cards[2].id])324 #expect(index.search("CAF") == [cards[2].id])325 #expect(index.search("aur inf") == [cards[0].id])326 #expect(index.search("aurora northwind").isEmpty)327 #expect(index.search(" ").isEmpty)328 }329330 @Test func sensitiveValuesAndFullNumbersAreNotIndexed() {331 let (index, _) = makeIndex()332 #expect(index.search("hidden").isEmpty)333 #expect(index.search("4242424242424242").isEmpty)334 #expect(index.search("140288").isEmpty)335 let encoded = String(decoding: try! JSONEncoder.vault.encode(index), as: UTF8.self)336 #expect(!encoded.contains("4242424242424242"))337 #expect(!encoded.contains("hidden-value"))338 }339340 @Test func removalAndPersistence() throws {341 var (index, cards) = makeIndex()342 index.remove(cards[0].id)343 #expect(index.search("aurora").isEmpty)344 let root = TestSupport.temporaryRoot(), master = VaultCrypto.randomKey()345 let repository = VaultRepository(root: root)346 try repository.create(masterKey: master, recoveryPassphrase: nil)347 try repository.saveSearchIndex(index, masterKey: master)348 #expect(try repository.loadSearchIndex(masterKey: master) == index)349 #expect(throws: VaultCryptoError.authenticationFailed) { try repository.loadSearchIndex(masterKey: VaultCrypto.randomKey()) }350 }351}352