SPB Git

Repository Public

ScreensLogicTests.swift 10.0 KB 175 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : SP ID & Card Vault7// File             : SPVaultTests/ScreensLogicTests.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 Foundation42import Testing43@testable import SPVault4445@Suite("Security assessment")46struct SecurityAssessmentTests {47    let now = Date(timeIntervalSince1970: 1_800_000_000)4849    func report(biometry: BiometryState = .available(kind: .faceID), keyPresent: Bool = true, cards: Int = 3, damaged: Int = 0,50                protected: Int = 14, files: Int = 14, excluded: Bool = true, recovery: Bool = true, backupDaysAgo: Int? = 3,51                selfTest: Bool = true) -> SecurityReport {52        SecurityReport(biometry: biometry, keyPresent: keyPresent, keyProtection: "Keychain", cardCount: cards, damagedCards: damaged,53                       storage: StorageReport(totalBytes: 1_000_000, fileCount: files, cardCount: cards, protectedFiles: protected,54                                              excludedFromBackup: excluded, freeBytes: 5_000_000_000),55                       recoveryConfigured: recovery, recoveryIterations: recovery ? 600_000 : nil,56                       lastBackupAt: backupDaysAgo.map { now.addingTimeInterval(-86_400 * Double($0)) },57                       vaultCreatedAt: now.addingTimeInterval(-86_400 * 100), formatVersion: 1, encryptionSelfTestPassed: selfTest)58    }5960    @Test func aHealthyVaultPassesEveryCheck() {61        let assessment = SecurityAssessment(report: report(), now: now)62        #expect(assessment.level == .good)63        #expect(assessment.issues.isEmpty)64        #expect(assessment.findings.count == SecurityAssessment.Topic.allCases.count)65        #expect(assessment.headline == "Vault secured")66    }6768    @Test func backupAgeDrivesItsLevel() {69        #expect(SecurityAssessment.backupLevel(lastBackup: nil, cardCount: 0, now: now) == .good)70        #expect(SecurityAssessment.backupLevel(lastBackup: nil, cardCount: 2, now: now) == .attention)71        #expect(SecurityAssessment(report: report(backupDaysAgo: 30), now: now).finding(.backup)?.level == .good)72        #expect(SecurityAssessment(report: report(backupDaysAgo: 31), now: now).finding(.backup)?.level == .attention)73        #expect(SecurityAssessment(report: report(backupDaysAgo: 91), now: now).finding(.backup)?.level == .risk)74        let never = SecurityAssessment(report: report(backupDaysAgo: nil), now: now)75        #expect(never.finding(.backup)?.title == "No backup yet")76        #expect(never.headline == "1 point needs attention")77        #expect(never.summary == "No backup yet")78    }7980    @Test func everyRealProblemIsSurfaced() {81        let bad = SecurityAssessment(report: report(biometry: .notEnrolled, keyPresent: false, damaged: 2, protected: 10, excluded: false,82                                                    recovery: false, backupDaysAgo: 200, selfTest: false), now: now)83        #expect(bad.level == .risk)84        #expect(bad.issues.count == SecurityAssessment.Topic.allCases.count)85        #expect(bad.headline == "Action required")86        #expect(bad.finding(.integrity)?.title == "2 damaged cards")87        #expect(bad.finding(.fileProtection)?.detail == "10 of 14 files use complete protection.")88        #expect(SecurityAssessment(report: report(biometry: .lockedOut), now: now).finding(.biometry)?.level == .attention)89        #expect(SecurityAssessment(report: report(recovery: false), now: now).level == .attention)90    }9192    /// The simulator reports no protection class: say so instead of claiming either way.93    @Test func unreportedFileProtectionIsNotPresentedAsAResult() {94        let simulator = SecurityAssessment(report: report(protected: 0), now: now, fileProtectionEnforced: false)95        #expect(simulator.finding(.fileProtection)?.title == "File protection not reported")96        #expect(simulator.finding(.fileProtection)?.level == .good)97        let device = SecurityAssessment(report: report(protected: 0), now: now, fileProtectionEnforced: true)98        #expect(device.finding(.fileProtection)?.level == .attention)99    }100}101102@Suite("Expiration summary")103struct ExpirationSummaryTests {104    let now = Calendar.current.date(from: DateComponents(year: 2026, month: 12, day: 2, hour: 12))!105106    func card(_ name: String, days: Int?) -> Card {107        var card = Card(name: name, kind: .membershipCard)108        card.expiry = days.map { Calendar.current.date(byAdding: .day, value: $0, to: now)! }109        return card110    }111112    @Test func groupsAndOrdersByUrgency() {113        let cards = [card("Far", days: 400), card("Soon", days: 40), card("Sooner", days: 5), card("Old", days: -200),114                     card("Recent", days: -3), card("Zeta", days: nil), card("Alpha", days: nil), card("Today", days: 0), card("Near", days: 120)]115        let summary = ExpirationSummary(cards: cards, now: now, soonWithinDays: 90)116        #expect(summary.expired.map(\.name) == ["Recent", "Old"])117        #expect(summary.expiringSoon.map(\.name) == ["Today", "Sooner", "Soon"])118        #expect(summary.valid.map(\.name) == ["Near", "Far"])119        #expect(summary.noExpiry.map(\.name) == ["Alpha", "Zeta"])120        #expect(summary.toRenew.count == 5)121        #expect(summary.datedCount == 7)122        #expect(summary.next?.name == "Today")123        #expect(!summary.isEmpty)124        #expect(ExpirationSummary(cards: cards, now: now, soonWithinDays: 180).expiringSoon.count == 4)125        #expect(ExpirationSummary(cards: [], now: now).isEmpty)126        #expect(ExpirationSummary(cards: [card("Far", days: 400)], now: now).next?.name == "Far")127    }128129    @Test func wording() {130        #expect(ExpirationSummary.describe(daysUntilExpiry: -20) == "Expired 20 days ago")131        #expect(ExpirationSummary.describe(daysUntilExpiry: -1) == "Expired yesterday")132        #expect(ExpirationSummary.describe(daysUntilExpiry: 0) == "Expires today")133        #expect(ExpirationSummary.describe(daysUntilExpiry: 1) == "Expires tomorrow")134        #expect(ExpirationSummary.describe(daysUntilExpiry: 42) == "Expires in 42 days")135        #expect(card("x", days: -20).expiryPill(now: now)?.text == "Expired 20 d")136        #expect(card("x", days: 0).expiryPill(now: now)?.tone == .critical)137        #expect(card("x", days: 42).expiryPill(now: now)?.text == "42 d left")138        #expect(card("x", days: 400).expiryPill(now: now)?.text == "Valid")139        #expect(card("x", days: nil).expiryPill(now: now) == nil)140    }141}142143@Suite("Lock and onboarding logic")144struct LockLogicTests {145    @Test func everyProtectorErrorHasItsOwnMessage() {146        let errors: [KeyProtectorError] = [.cancelled, .authenticationFailed, .biometryUnavailable, .biometryNotEnrolled, .biometryLockedOut,147                                           .keyInvalidated, .passcodeNotSet, .keychain(-25300)]148        let messages = errors.map { LockMessage.forError($0) }149        #expect(Set(messages.map(\.title)).count == errors.count)150        #expect(LockMessage.forError(KeyProtectorError.biometryLockedOut).detail.contains("unlock your iPhone with its passcode to re-enable Face ID"))151        #expect(LockMessage.forError(KeyProtectorError.keyInvalidated).canRetry == false)152        #expect(LockMessage.forError(KeyProtectorError.keychain(-25300)).detail.contains("-25300"))153        #expect(LockMessage.forError(KeyProtectorError.authenticationFailed, biometryName: "Touch ID").title.hasPrefix("Touch ID"))154        #expect(LockMessage.forRecoveryError(VaultStorageError.wrongPassphrase).title == "Wrong passphrase")155        #expect(LockMessage.forRecoveryError(VaultStorageError.noRecoveryConfigured).canRetry == false)156    }157158    @Test func onboardingSequences() {159        #expect(OnboardingStep.sequence(restoring: false) == [.welcome, .protection, .biometry, .recovery, .notifications])160        #expect(OnboardingStep.sequence(restoring: true).last == .restore)161        #expect(PassphraseFields.isValid("correct horse battery staple 42", "correct horse battery staple 42"))162        #expect(!PassphraseFields.isValid("correct horse battery staple 42", "correct horse battery staple 43"))163        #expect(!PassphraseFields.isValid("password", "password"))164    }165166    @Test func backupErrorsAreExplained() {167        let errors: [BackupError] = [.wrongPassphrase, .corrupted, .notABackup, .unsupportedVersion(7), .weakPassphrase]168        #expect(Set(errors.map { BackupMessages.describe($0) }).count == errors.count)169        #expect(BackupMessages.describe(BackupError.unsupportedVersion(7)).contains("7"))170        #expect(SearchView.shortName("My Professional Cards") == "Professional")171        #expect(SearchView.shortName("My Identity") == "Identity")172        #expect(SearchView.shortName("Travel") == "Travel")173    }174}175
Files main
Menu

Theme