SPB Git

Repository Public

VaultTests.swift 49.5 KB 977 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Tests/QyvoraVaultTests/VaultTests.swift8// Module           : Tests9// Repository       : https://git.spboucher.ai/qyvora10// Project Website  : Not specified11// Created          : 2026-12-0412// Last Modified    : 2026-12-0413//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 QyvoraMath44import QyvoraStorage45import QyvoraSymmetric46import Testing4748@testable import QyvoraVault4950/// A clock the test moves by hand.51final class TestClock: @unchecked Sendable {52    private let lock = NSLock()53    private var current: Date5455    init(_ start: TimeInterval = 1_800_000_000) { current = Date(timeIntervalSince1970: start) }5657    var now: Date { lock.withLock { current } }58    /// Time passes: the wall clock and the monotonic clock move together.59    func advance(_ seconds: TimeInterval) {60        lock.withLock {61            current = current.addingTimeInterval(seconds)62            uptime += seconds63        }64    }6566    // The clock the user cannot set (QYV-SVC-010), and the two ways it can part from the wall clock.67    private var uptime: TimeInterval = 5_00068    private var boot = Bytes(repeating: 0xb0, count: 16)69    var monotonic: MonotonicInstant { lock.withLock { MonotonicInstant(bootSession: boot, seconds: UInt64(max(0, uptime))) } }70    /// The date is changed in the settings: only the wall clock moves.71    func setDate(by seconds: TimeInterval) { lock.withLock { current = current.addingTimeInterval(seconds) } }72    /// The device restarts: a new boot session, the monotonic clock starts again; `downtime` passes on the wall clock.73    func reboot(downtime: TimeInterval = 30, uptimeAfter: TimeInterval = 20) {74        lock.withLock {75            current = current.addingTimeInterval(downtime)76            uptime = uptimeAfter77            boot = boot.map { $0 &+ 1 }78        }79    }80}8182/// One temporary directory, one Keychain double, and vault instances over them.83final class Fixture: @unchecked Sendable {84    let store: FileStore85    let keychain = InMemoryKeychainStore()86    let enclave = SoftwareEnclaveKey()87    let clock = TestClock()88    let name = "vault.qyv"8990    init() throws {91        store = try FileStore(92            root: FileManager.default.temporaryDirectory.appendingPathComponent("qyvora-vault-\(UUID().uuidString)", isDirectory: true))93    }9495    deinit { try? FileManager.default.removeItem(at: store.root) }9697    func vault(aead: AEADKind = .system, enclave: (any SecureEnclaveKeyProvider)? = nil) -> Vault {98        let clock = self.clock99        return Vault(100            fileStore: store, keychain: keychain, secureEnclave: enclave ?? self.enclave,101            configuration: .init(fileName: name, kdf: .insecureForTesting, aead: aead, now: { clock.now }, monotonic: { clock.monotonic }))102    }103104    func fileBytes() throws -> Bytes { try store.read(name) }105106    /// Rewrites the trailing checksum so that only keyed checks can notice a modification.107    static func withFixedChecksum(_ bytes: Bytes) -> Bytes {108        let body = Bytes(bytes[0..<(bytes.count - 32)])109        return body + Bytes(CryptoKit.SHA256.hash(data: body))110    }111}112113func expectVaultError(_ expected: VaultError, _ body: () async throws -> Void, sourceLocation: SourceLocation = #_sourceLocation) async {114    do {115        try await body()116        Issue.record("expected \(expected), nothing was thrown", sourceLocation: sourceLocation)117    } catch let error as VaultError {118        #expect(error == expected, sourceLocation: sourceLocation)119    } catch {120        Issue.record("unexpected error type \(type(of: error))", sourceLocation: sourceLocation)121    }122}123124@Suite struct VaultLifecycleTests {125    @Test func createUnlockLockAndRecords() async throws {126        let f = try Fixture()127        let vault = f.vault()128        #expect(await !vault.exists)129        await expectVaultError(.notFound) { try await vault.unlock(password: "pw") }130        try await vault.create(password: "correct horse")131        #expect(await vault.exists)132        #expect(await vault.isUnlocked)133        await expectVaultError(.alreadyExists) { try await vault.create(password: "x") }134135        let phrase = Bytes("abandon abandon about".utf8)136        let id = try await vault.addRecord(type: .recoveryPhrase, payload: phrase)137        let other = try await vault.addRecord(type: .setting, payload: [])138        #expect(try await vault.record(id).payload == phrase)139        #expect(try await vault.record(id).type == .recoveryPhrase)140        #expect(try await vault.record(other).payload == [])141        #expect(try await vault.records().count == 2)142        #expect(try await vault.records(ofType: .setting).map(\.id) == [other])143144        try await vault.updateRecord(id, payload: [1, 2, 3])145        #expect(try await vault.record(id).payload == [1, 2, 3])146        try await vault.deleteRecord(other)147        await expectVaultError(.recordNotFound) { _ = try await vault.record(other) }148        await expectVaultError(.recordNotFound) { try await vault.deleteRecord(other) }149        await expectVaultError(.recordNotFound) { try await vault.updateRecord(other, payload: []) }150        await expectVaultError(.invalidParameters) { _ = try await vault.addRecord(type: .custom, payload: [], id: id) }151152        await vault.lock()153        #expect(await !vault.isUnlocked)154        await expectVaultError(.locked) { _ = try await vault.record(id) }155        await expectVaultError(.locked) { _ = try await vault.addRecord(type: .custom, payload: [1]) }156        await expectVaultError(.locked) { try await vault.changePassword(current: "correct horse", new: "n") }157        await expectVaultError(.locked) { try await vault.enableDeviceSlot() }158        await expectVaultError(.locked) { _ = try await vault.verifyIntegrity() }159        #expect(try await vault.recordSummaries().map(\.id) == [id])160161        // a second instance over the same files162        let again = f.vault()163        await expectVaultError(.wrongPassword) { try await again.unlock(password: "wrong") }164        #expect(await !again.isUnlocked)165        try await again.unlock(password: "correct horse")166        #expect(try await again.record(id).payload == [1, 2, 3])167        #expect(try await again.verifyIntegrity().recordsVerified == 1)168    }169170    @Test func emptyPasswordAndUnicodeNormalization() async throws {171        let f = try Fixture()172        let vault = f.vault()173        await expectVaultError(.invalidParameters) { try await vault.create(password: "") }174        try await vault.create(password: "caf\u{00e9} \u{2460}")175        await vault.lock()176        // the decomposed spelling of the same text opens the vault177        try await vault.unlock(password: "cafe\u{0301} 1")178        #expect(await vault.isUnlocked)179    }180181    @Test func changePasswordInvalidatesTheOldOne() async throws {182        let f = try Fixture()183        let vault = f.vault()184        try await vault.create(password: "old password")185        let id = try await vault.addRecord(type: .custom, payload: [42])186        await expectVaultError(.wrongPassword) { try await vault.changePassword(current: "nope", new: "new password") }187        await expectVaultError(.invalidParameters) { try await vault.changePassword(current: "old password", new: "") }188        try await vault.changePassword(current: "old password", new: "new password")189        #expect(try await vault.record(id).payload == [42])190191        let again = f.vault()192        await expectVaultError(.wrongPassword) { try await again.unlock(password: "old password") }193        try await again.unlock(password: "new password")194        #expect(try await again.record(id).payload == [42])195196        // the `.previous` copy was overwritten: even with the current file gone, the old password opens nothing197        #expect(try f.store.readPrevious(f.name) == f.fileBytes())198        try FileManager.default.removeItem(at: f.store.url(for: f.name))199        let fallback = f.vault()200        await expectVaultError(.wrongPassword) { try await fallback.unlock(password: "old password") }201        try await fallback.unlock(password: "new password")202        #expect(try await fallback.report().recoveredFromPreviousCopy)203    }204205    @Test func reportAndAutoLock() async throws {206        let f = try Fixture()207        let vault = f.vault()208        try await vault.create(password: "pw")209        _ = try await vault.addRecord(type: .watchOnlyAccount, payload: [1])210        _ = try await vault.addRecord(type: .watchOnlyAccount, payload: [2])211        _ = try await vault.addRecord(type: .identityKeys, payload: [3])212        try await vault.enableDeviceSlot(useSecureEnclave: true)213        let report = try await vault.report()214        #expect(report.formatVersion == 1)215        #expect(report.keyEpoch == 1)216        #expect(report.recordCounts == ["watchOnlyAccount": 2, "identityKeys": 1])217        #expect(report.totalRecords == 3)218        #expect(report.passwordSlot?.parameters == .insecureForTesting)219        #expect(report.deviceSlotEnabled && report.deviceSlotUsesSecureEnclave)220        #expect(report.pinSlot == nil && report.pinFailedAttempts == nil)221        #expect(report.isUnlocked && report.selfTestPassed && !report.recoveredFromPreviousCopy)222        #expect(report.vaultID == (try await vault.vaultID()).hex)223        let json = try JSONEncoder().encode(report)224        #expect(try JSONDecoder().decode(VaultReport.self, from: json) == report)225226        let t = Date(timeIntervalSince1970: 1000)227        #expect(!Vault.shouldLock(now: t.addingTimeInterval(1e9), lastActivity: t, policy: .never))228        #expect(Vault.shouldLock(now: t, lastActivity: t, policy: .immediately))229        #expect(!Vault.shouldLock(now: t.addingTimeInterval(59), lastActivity: t, policy: .after(seconds: 60)))230        #expect(Vault.shouldLock(now: t.addingTimeInterval(60), lastActivity: t, policy: .after(seconds: 60)))231        #expect(Vault.shouldLock(now: t.addingTimeInterval(-1), lastActivity: t, policy: .after(seconds: 60)))232233        await vault.noteActivity()234        f.clock.advance(30)235        #expect(await !vault.autoLockIfNeeded(policy: .after(seconds: 60)))236        f.clock.advance(31)237        #expect(await vault.autoLockIfNeeded(policy: .after(seconds: 60)))238        #expect(await !vault.isUnlocked)239    }240241    @Test func destroyErasesFilesAndKeychain() async throws {242        let f = try Fixture()243        let vault = f.vault()244        try await vault.create(password: "pw")245        try await vault.enableDeviceSlot()246        try await vault.enablePIN("246810")247        #expect(f.keychain.accounts.count == 3)248        try await vault.destroy()249        #expect(f.keychain.accounts.isEmpty)250        #expect(await !vault.exists)251        #expect(!f.store.exists(f.name) && !f.store.previousExists(f.name))252        try await vault.create(password: "again")253    }254}255256@Suite struct VaultDeviceSlotTests {257    @Test func deviceUnlockWithAndWithoutSecureEnclave() async throws {258        for useEnclave in [false, true] {259            let f = try Fixture()260            let vault = f.vault()261            try await vault.create(password: "pw")262            let id = try await vault.addRecord(type: .custom, payload: [7])263            await expectVaultError(.deviceSlotNotEnabled) { try await vault.unlockWithDevice() }264            await expectVaultError(.deviceSlotNotEnabled) { try await vault.disableDeviceSlot() }265            try await vault.enableDeviceSlot(useSecureEnclave: useEnclave)266            #expect(await vault.isDeviceSlotEnabled)267            await vault.lock()268269            let again = f.vault()270            try await again.unlockWithDevice(prompt: "Unlock QYVORA")271            #expect(try await again.record(id).payload == [7])272            await again.lock()273274            f.keychain.setBiometryPasses(false)275            await expectVaultError(.deviceAuthenticationFailed) { try await again.unlockWithDevice() }276            #expect(await !again.isUnlocked)277            f.keychain.setBiometryPasses(true)278279            if useEnclave {280                // another enclave key (another device) cannot remove the outer layer281                let foreign = f.vault(enclave: SoftwareEnclaveKey())282                await expectVaultError(.deviceKeyUnavailable) { try await foreign.unlockWithDevice() }283                let none = f.vault(enclave: SoftwareEnclaveKey(available: false))284                await expectVaultError(.secureEnclaveUnavailable) { try await none.unlockWithDevice() }285            }286287            // new biometric enrolment: the Keychain item is gone, the password still works288            f.keychain.invalidateBiometricItems()289            await expectVaultError(.deviceKeyUnavailable) { try await again.unlockWithDevice() }290            try await again.unlock(password: "pw")291            try await again.disableDeviceSlot()292            #expect(await !again.isDeviceSlotEnabled)293            await again.lock()294            await expectVaultError(.deviceSlotNotEnabled) { try await again.unlockWithDevice() }295        }296    }297298    @Test func secureEnclaveMustBeAvailableToEnable() async throws {299        let f = try Fixture()300        let vault = f.vault(enclave: SoftwareEnclaveKey(available: false))301        try await vault.create(password: "pw")302        await expectVaultError(.secureEnclaveUnavailable) { try await vault.enableDeviceSlot(useSecureEnclave: true) }303        #expect(await !vault.isDeviceSlotEnabled)304        try await vault.enableDeviceSlot(useSecureEnclave: false)305    }306307    @Test func deviceKeyOfAnOlderSlotIsRejected() async throws {308        let f = try Fixture()309        let vault = f.vault()310        try await vault.create(password: "pw")311        try await vault.enableDeviceSlot()312        let account = try #require(f.keychain.accounts.first)313        let oldKey = try f.keychain.get(account: account, prompt: nil)314        try await vault.enableDeviceSlot()315        try f.keychain.set(oldKey, account: account, access: .biometryCurrentSet)316        await vault.lock()317        await expectVaultError(.deviceKeyUnavailable) { try await vault.unlockWithDevice() }318    }319}320321@Suite struct VaultPINTests {322    @Test func pinUnlockAndValidation() async throws {323        let f = try Fixture()324        let vault = f.vault()325        try await vault.create(password: "pw")326        let id = try await vault.addRecord(type: .custom, payload: [9])327        await expectVaultError(.pinNotEnabled) { try await vault.unlock(pin: "123456") }328        await expectVaultError(.invalidParameters) { try await vault.enablePIN("12345") }329        await expectVaultError(.invalidParameters) { try await vault.enablePIN("123456", policy: .init(wipeAfterFailedAttempts: 0)) }330        try await vault.enablePIN("135790")331        #expect(await vault.isPINEnabled)332        await vault.lock()333334        let again = f.vault()335        try await again.unlock(pin: "135790")336        #expect(try await again.record(id).payload == [9])337        #expect(try await again.report().pinFailedAttempts == 0)338        try await again.disablePIN()339        await again.lock()340        await expectVaultError(.pinNotEnabled) { try await again.unlock(pin: "135790") }341        #expect(f.keychain.accounts.isEmpty)342    }343344    @Test func delaySchedule() {345        #expect((0...9).map { PINPolicy.delay(afterFailedAttempts: $0) } == [0, 0, 0, 60, 300, 900, 3600, 10800, 86400, 86400])346    }347348    @Test func lockoutScheduleWithInjectedClock() async throws {349        let f = try Fixture()350        let vault = f.vault()351        try await vault.create(password: "pw")352        try await vault.enablePIN("135790")353        await vault.lock()354        let start = f.clock.now355356        // three free attempts; the third failure announces the first delay357        await expectVaultError(.wrongPIN(retryAllowedAt: nil)) { try await vault.unlock(pin: "000000") }358        await expectVaultError(.wrongPIN(retryAllowedAt: nil)) { try await vault.unlock(pin: "000001") }359        await expectVaultError(.wrongPIN(retryAllowedAt: start.addingTimeInterval(60))) { try await vault.unlock(pin: "000002") }360        #expect(try await vault.report().pinFailedAttempts == 3)361362        // during the delay even the right PIN is refused, and refused attempts do not count363        await expectVaultError(.pinLocked(until: start.addingTimeInterval(60))) { try await vault.unlock(pin: "135790") }364        f.clock.advance(59)365        await expectVaultError(.pinLocked(until: start.addingTimeInterval(60))) { try await vault.unlock(pin: "135790") }366        #expect(try await vault.report().pinFailedAttempts == 3)367368        var expected: [TimeInterval] = [300, 900, 3600, 10800, 86400, 86400]369        f.clock.advance(1)370        while !expected.isEmpty {371            let delay = expected.removeFirst()372            let at = f.clock.now373            await expectVaultError(.wrongPIN(retryAllowedAt: at.addingTimeInterval(delay))) { try await vault.unlock(pin: "999999") }374            f.clock.advance(delay - 1)375            await expectVaultError(.pinLocked(until: at.addingTimeInterval(delay))) { try await vault.unlock(pin: "135790") }376            f.clock.advance(1)377        }378        #expect(try await vault.report().pinFailedAttempts == 9)379380        // once the delay has elapsed the right PIN works and clears the counter381        try await vault.unlock(pin: "135790")382        #expect(try await vault.report().pinFailedAttempts == 0)383        #expect(await vault.isUnlocked)384    }385386    @Test func clockRollbackRestartsTheDelay() async throws {387        let f = try Fixture()388        let vault = f.vault()389        try await vault.create(password: "pw")390        try await vault.enablePIN("135790")391        await vault.lock()392        for _ in 0..<4 {393            _ = try? await vault.unlock(pin: "000000")394            f.clock.advance(60)395        }396        // four failures: five minutes from the last one. Moving the clock back two hours must not help…397        f.clock.setDate(by: -7200)398        let rolledBack = f.clock.now399        await expectVaultError(.pinLocked(until: rolledBack.addingTimeInterval(300))) { try await vault.unlock(pin: "135790") }400        // …and the full delay now runs from the rolled-back time401        f.clock.advance(299)402        await expectVaultError(.pinLocked(until: rolledBack.addingTimeInterval(300))) { try await vault.unlock(pin: "135790") }403        f.clock.advance(1)404        try await vault.unlock(pin: "135790")405    }406407    @Test func counterSurvivesFileReplacementAndPasswordResetsIt() async throws {408        let f = try Fixture()409        let vault = f.vault()410        try await vault.create(password: "pw")411        try await vault.enablePIN("135790")412        await vault.lock()413        let pristine = try f.fileBytes()414        for _ in 0..<3 { _ = try? await vault.unlock(pin: "000000") }415416        // restoring the original file (or reinstalling it) does not reset the counter kept in the Keychain417        try f.store.write(pristine, to: f.name)418        let again = f.vault()419        do {420            try await again.unlock(pin: "135790")421            Issue.record("the PIN must be locked")422        } catch VaultError.pinLocked {423        }424        try await again.unlock(password: "pw")425        #expect(try await again.report().pinFailedAttempts == 0)426        await again.lock()427        try await again.unlock(pin: "135790")428    }429430    @Test func wipePolicyIsOffByDefaultAndErasesWhenEnabled() async throws {431        let f = try Fixture()432        let vault = f.vault()433        try await vault.create(password: "pw")434        try await vault.enablePIN("135790")435        #expect(try await vault.report().pinWipeAfterFailedAttempts == nil)436        try await vault.enablePIN("135790", policy: .init(wipeAfterFailedAttempts: 4))437        #expect(try await vault.report().pinWipeAfterFailedAttempts == 4)438        await vault.lock()439        for _ in 0..<3 {440            _ = try? await vault.unlock(pin: "000000")441        }442        #expect(await vault.exists)443        f.clock.advance(60)444        await expectVaultError(.wiped) { try await vault.unlock(pin: "000000") }445        #expect(await !vault.exists)446        #expect(f.keychain.accounts.isEmpty)447        await expectVaultError(.notFound) { try await vault.unlock(password: "pw") }448    }449450    @Test func pinIsUselessWithoutTheDeviceSecret() async throws {451        let f = try Fixture()452        let vault = f.vault()453        try await vault.create(password: "pw")454        try await vault.enablePIN("135790")455        await vault.lock()456        let secretAccount = try #require(f.keychain.accounts.first { $0.hasSuffix("pin-secret") })457        try f.keychain.set(SystemRandom.bytes(32), account: secretAccount, access: .passcodeSetThisDeviceOnly)458        await expectVaultError(.wrongPIN(retryAllowedAt: nil)) { try await vault.unlock(pin: "135790") }459        try f.keychain.delete(account: secretAccount)460        await expectVaultError(.pinNotEnabled) { try await vault.unlock(pin: "135790") }461    }462}463464@Suite struct VaultCorruptionTests {465    func populated(_ f: Fixture) async throws -> (Vault, [UUID]) {466        let vault = f.vault()467        try await vault.create(password: "pw")468        try await vault.enableDeviceSlot()469        try await vault.enablePIN("135790")470        var ids: [UUID] = []471        for i in 0..<3 { ids.append(try await vault.addRecord(type: .custom, payload: Bytes(repeating: UInt8(i), count: 20 + i))) }472        await vault.lock()473        return (vault, ids)474    }475476    @Test func layoutMatchesTheDocumentedFormat() async throws {477        let f = try Fixture()478        _ = try await populated(f)479        let bytes = try f.fileBytes()480        #expect(Bytes(bytes[0..<8]) == Bytes("QYVORAVF".utf8))481        #expect(Bytes(bytes[8..<10]) == [0, 1])482        var r = ByteReader(Bytes(bytes[10...]))483        var header = ByteReader(try r.prefixed32(max: 1 << 16))484        var body = ByteReader(try r.prefixed32(max: 1 << 20))485        #expect(r.remaining == 64)486        _ = try header.raw(16)487        _ = try header.u64()488        #expect(try header.u32() == 1)489        _ = try header.u64()490        #expect(try header.u8() == 3)491        #expect(try header.u8() == 1)492        #expect(try header.prefixed16().count == 108)493        #expect(try header.u8() == 2)494        #expect(try header.prefixed16().count == 61)495        #expect(try header.u8() == 3)496        #expect(try header.prefixed16().count == 108)497        #expect(header.remaining == 0)498        #expect(try body.u32() == 3)499        #expect(Bytes(bytes[(bytes.count - 32)...]) == Bytes(CryptoKit.SHA256.hash(data: bytes[0..<(bytes.count - 32)])))500        let parsed = try VaultFile.parse(bytes)501        #expect(parsed.file.encoded(macKey: Bytes(repeating: 0, count: 32)).count == bytes.count)502        #expect(parsed.authenticated + parsed.mac + Bytes(bytes[(bytes.count - 32)...]) == bytes)503    }504505    @Test func everySingleByteCorruptionIsDetected() async throws {506        let f = try Fixture()507        _ = try await populated(f)508        let good = try f.fileBytes()509        try f.store.removePrevious(f.name)510        for i in 0..<good.count {511            var bad = good512            bad[i] ^= UInt8(1) << UInt8(i % 8)513            try f.store.write(bad, to: f.name, keepPrevious: false)514            let vault = f.vault()515            do {516                try await vault.unlock(password: "pw")517                Issue.record("corruption at offset \(i) was accepted")518            } catch VaultError.corrupted(let kind) {519                if i < 8 { #expect(kind == .badMagic) } else if i >= 10 { #expect(kind == .checksumMismatch) }520            } catch {521                Issue.record("offset \(i): unexpected error \(error)")522            }523            #expect(await !vault.isUnlocked)524        }525    }526527    @Test func truncationAndGarbageAreTypedErrors() async throws {528        let f = try Fixture()529        _ = try await populated(f)530        let good = try f.fileBytes()531        try f.store.removePrevious(f.name)532        for cut in [0, 1, 7, 8, 9, 10, 40, good.count / 2, good.count - 33, good.count - 1] {533            try f.store.write(Bytes(good[0..<cut]), to: f.name, keepPrevious: false)534            do {535                try await f.vault().unlock(password: "pw")536                Issue.record("truncated file accepted (\(cut))")537            } catch VaultError.corrupted {538            }539        }540        for garbage in [SystemRandom.bytes(500), good + [0], Bytes("QYVORAVF".utf8) + [0, 2] + SystemRandom.bytes(200)] {541            try f.store.write(garbage, to: f.name, keepPrevious: false)542            do {543                try await f.vault().unlock(password: "pw")544                Issue.record("garbage accepted")545            } catch VaultError.corrupted {546            }547        }548        #expect(throws: VaultError.corrupted(.unsupportedVersion(2))) {549            _ = try VaultFile.parse(Bytes("QYVORAVF".utf8) + [0, 2] + SystemRandom.bytes(200))550        }551    }552553    @Test func previousCopyTakesOverWhenTheCurrentFileIsDamaged() async throws {554        let f = try Fixture()555        let (_, ids) = try await populated(f)556        // the last write added the third record: `.previous` holds two records557        var bad = try f.fileBytes()558        bad[bad.count / 2] ^= 0xff559        try f.store.write(bad, to: f.name, keepPrevious: false)560561        let vault = f.vault()562        #expect(try await vault.recordSummaries().count == 2)563        try await vault.unlock(password: "pw")564        #expect(try await vault.report().recoveredFromPreviousCopy)565        #expect(try await vault.records().map(\.id) == Array(ids[0..<2]))566        // the current file was repaired from the copy567        let repaired = f.vault()568        try await repaired.unlock(pin: "135790")569        #expect(try await !repaired.report().recoveredFromPreviousCopy)570        #expect(try await repaired.verifyIntegrity().recordsVerified == 2)571572        // a missing current file is handled the same way573        try FileManager.default.removeItem(at: f.store.url(for: f.name))574        let third = f.vault()575        try await third.unlockWithDevice()576        #expect(try await third.records().count == 2)577    }578579    @Test func modificationWithARecomputedChecksumFailsTheKeyedChecks() async throws {580        let f = try Fixture()581        _ = try await populated(f)582        let good = try f.fileBytes()583        try f.store.removePrevious(f.name)584        // every byte between the version field and the checksum, one flipped bit each585        // (the 16 bytes of password-slot KDF parameters, offsets 54..<70, are skipped here: a flipped bit there can ask586        // for gigabytes of Argon2 memory; `slotHeaderTamperingIsDetected` covers them)587        for i in 10..<(good.count - 32) where !(54..<70).contains(i) {588            var bad = good589            bad[i] ^= UInt8(1) << UInt8(i % 8)590            try f.store.write(Fixture.withFixedChecksum(bad), to: f.name, keepPrevious: false)591            let vault = f.vault()592            do {593                try await vault.unlock(password: "pw")594                Issue.record("tampering at offset \(i) was accepted")595            } catch let error as VaultError {596                switch error {597                case .integrityFailure, .wrongPassword, .corrupted, .invalidParameters: break598                default: Issue.record("offset \(i): unexpected \(error)")599                }600            }601            #expect(await !vault.isUnlocked)602        }603    }604605    @Test func tamperedFileFallsBackToTheAuthenticPreviousCopy() async throws {606        let f = try Fixture()607        let (_, ids) = try await populated(f)608        var bad = try f.fileBytes()609        bad[bad.count - 70] ^= 0x01  // inside the last record's ciphertext610        try f.store.write(Fixture.withFixedChecksum(bad), to: f.name, keepPrevious: false)611        let vault = f.vault()612        try await vault.unlock(password: "pw")613        #expect(try await vault.report().recoveredFromPreviousCopy)614        #expect(try await vault.records().map(\.id) == Array(ids[0..<2]))615    }616617    @Test func slotHeaderTamperingIsDetected() async throws {618        let f = try Fixture()619        _ = try await populated(f)620        let parsed = try VaultFile.parse(try f.fileBytes())621        try f.store.removePrevious(f.name)622        let fakeMAC = Bytes(repeating: 0, count: 32)623624        func attempt(_ label: String, _ mutate: (inout VaultFile) -> Void, unlock: (Vault) async throws -> Void) async throws {625            var forged = parsed.file626            mutate(&forged)627            // keep the genuine MAC bytes: the attacker cannot compute a new one628            var bytes = forged.authenticatedBytes() + parsed.mac629            bytes += Bytes(CryptoKit.SHA256.hash(data: bytes))630            #expect(bytes.count == forged.encoded(macKey: fakeMAC).count)631            try f.store.write(bytes, to: f.name, keepPrevious: false)632            let vault = f.vault()633            do {634                try await unlock(vault)635                Issue.record("\(label): forged header accepted")636            } catch let error as VaultError {637                #expect(error == .integrityFailure, "\(label)")638            }639            #expect(await !vault.isUnlocked, "\(label)")640        }641642        // sanity: the unmodified reconstruction is accepted643        var same = parsed.file.authenticatedBytes() + parsed.mac644        same += Bytes(CryptoKit.SHA256.hash(data: same))645        #expect(same == (try f.fileBytes()))646647        try await attempt("PIN slot removed", { $0.pin = nil }) { try await $0.unlock(password: "pw") }648        try await attempt("device slot removed", { $0.device = nil }) { try await $0.unlock(password: "pw") }649        try await attempt("generation changed", { $0.generation += 1 }) { try await $0.unlock(password: "pw") }650        try await attempt("creation time changed", { $0.createdAt += 1 }) { try await $0.unlock(password: "pw") }651        try await attempt("PIN slot replaced by the password slot", { $0.pin = $0.password }) { try await $0.unlock(password: "pw") }652        try await attempt("device blob altered, password unlock", { $0.device?.blob[20] ^= 1 }) { try await $0.unlock(password: "pw") }653        try await attempt("record removed", { $0.records.removeLast() }) { try await $0.unlockWithDevice() }654        try await attempt("records reordered", { $0.records.swapAt(0, 1) }) { try await $0.unlock(pin: "135790") }655        try await attempt("record type changed", { $0.records[0].type = .recoveryPhrase }) { try await $0.unlock(password: "pw") }656        try await attempt("record timestamps changed", { $0.records[0].updatedAt += 5 }) { try await $0.unlock(password: "pw") }657658        // weaker KDF parameters change the derived key: the slot no longer opens659        var forged = parsed.file660        forged.password?.kdf.pbkdf2Iterations = 1661        var bytes = forged.authenticatedBytes() + parsed.mac662        bytes += Bytes(CryptoKit.SHA256.hash(data: bytes))663        try f.store.write(bytes, to: f.name, keepPrevious: false)664        await expectVaultError(.wrongPassword) { try await f.vault().unlock(password: "pw") }665    }666667    @Test func recordsCannotBeSwappedOrRelabelledEvenWithTheKey() async throws {668        // associated data binds each ciphertext to its identifier, type, creation time and epoch669        let f = try Fixture()670        let vault = f.vault()671        try await vault.create(password: "pw")672        let a = try await vault.addRecord(type: .custom, payload: [1])673        _ = try await vault.addRecord(type: .custom, payload: [2])674        var key = try #require(await vault.masterKeyCopyForTesting())675        defer { SecureMemory.zero(&key) }676        var forged = try VaultFile.parse(try f.fileBytes()).file677        let sealedA = forged.records[0].sealed, nonceA = forged.records[0].nonce678        forged.records[0].sealed = forged.records[1].sealed679        forged.records[0].nonce = forged.records[1].nonce680        forged.records[1].sealed = sealedA681        forged.records[1].nonce = nonceA682        // a valid MAC, as if the file-MAC key alone had leaked683        let macKey = VaultFile.subkey(master: key, vaultID: forged.vaultID, epoch: forged.epoch, label: VaultLabels.fileMAC)684        try f.store.write(forged.encoded(macKey: macKey), to: f.name, keepPrevious: false)685        try f.store.removePrevious(f.name)686        let again = f.vault()687        try await again.unlock(password: "pw")688        await expectVaultError(.integrityFailure) { _ = try await again.record(a) }689        await expectVaultError(.integrityFailure) { _ = try await again.verifyIntegrity() }690    }691}692693@Suite struct VaultCryptoTests {694    @Test func selfTestPasses() throws {695        try VaultSelfTest.run()696        #expect(VaultSelfTest.passed)697    }698699    @Test func aeadInteropBothWays() throws {700        let system = SystemAEAD(), engine = EngineAEAD()701        for size in [0, 1, 16, 31, 32, 33, 100, 1000, 4097] {702            let key = SystemRandom.bytes(32), nonce = SystemRandom.bytes(12)703            let plain = SystemRandom.bytes(size), aad = SystemRandom.bytes(size % 40)704            let a = try system.seal(key: key, nonce: nonce, plaintext: plain, associatedData: aad)705            let b = try engine.seal(key: key, nonce: nonce, plaintext: plain, associatedData: aad)706            #expect(a == b)707            #expect(try engine.open(key: key, nonce: nonce, sealed: a, associatedData: aad) == plain)708            #expect(try system.open(key: key, nonce: nonce, sealed: b, associatedData: aad) == plain)709            for backend in [system, engine] as [any AEADBackend] {710                var bad = a711                bad[Int.random(in: 0..<bad.count)] ^= 0x10712                #expect(throws: VaultError.integrityFailure) { _ = try backend.open(key: key, nonce: nonce, sealed: bad, associatedData: aad) }713                #expect(throws: VaultError.integrityFailure) { _ = try backend.open(key: key, nonce: nonce, sealed: a, associatedData: aad + [1]) }714                #expect(throws: VaultError.integrityFailure) { _ = try backend.open(key: key, nonce: nonce, sealed: Bytes(a.dropLast()), associatedData: aad) }715                #expect(throws: VaultError.integrityFailure) { _ = try backend.open(key: key, nonce: nonce, sealed: [], associatedData: aad) }716                #expect(throws: VaultError.invalidParameters) { _ = try backend.seal(key: Bytes(key.dropLast()), nonce: nonce, plaintext: plain, associatedData: aad) }717                #expect(throws: VaultError.invalidParameters) { _ = try backend.seal(key: key, nonce: nonce + [0], plaintext: plain, associatedData: aad) }718            }719        }720    }721722    @Test func vaultSealedByOneBackendOpensWithTheOther() async throws {723        for (writer, reader) in [(AEADKind.system, AEADKind.engine), (.engine, .system)] {724            let f = try Fixture()725            let a = f.vault(aead: writer)726            try await a.create(password: "pw")727            let id = try await a.addRecord(type: .recoveryPhrase, payload: Bytes("zoo zoo wrong".utf8))728            try await a.enableDeviceSlot(useSecureEnclave: true)729            try await a.enablePIN("135790")730            await a.lock()731            let b = f.vault(aead: reader)732            try await b.unlock(password: "pw")733            #expect(try await b.record(id).payload == Bytes("zoo zoo wrong".utf8))734            try await b.updateRecord(id, payload: [5])735            await b.lock()736            try await b.unlockWithDevice()737            await b.lock()738            try await a.unlock(pin: "135790")739            #expect(try await a.record(id).payload == [5])740            #expect(try await a.verifyIntegrity().recordsVerified == 1)741        }742    }743744    @Test func keyStretchingIsTheDocumentedCombiner() throws {745        let secret = Bytes("pässword".utf8), s1 = SystemRandom.bytes(16), s2 = SystemRandom.bytes(16)746        let p = KDFParameters(argon2MemoryKiB: 64, argon2Iterations: 2, argon2Parallelism: 2, pbkdf2Iterations: 20)747        let key = try KeyStretching.deriveKey(secret: secret, argon2Salt: s1, pbkdf2Salt: s2, parameters: p, info: "label")748        // independent recomputation with the engine's PBKDF2 and HKDF749        let a = try Argon2.id(password: secret, salt: s1, parameters: .init(memoryKiB: 64, iterations: 2, parallelism: 2, tagLength: 32))750        let b = PBKDF2<QyvoraSymmetric.SHA512>.deriveKey(password: secret, salt: s2, iterations: 20, length: 32)751        let expected = QyvoraSymmetric.HKDF<QyvoraSymmetric.SHA256>.deriveKey(inputKeyMaterial: a + b, salt: s1 + s2, info: Bytes("label".utf8), length: 32)752        #expect(key == expected)753        #expect(key.count == 32)754755        var other = s1756        other[0] ^= 1757        #expect(try KeyStretching.deriveKey(secret: secret, argon2Salt: other, pbkdf2Salt: s2, parameters: p, info: "label") != key)758        #expect(try KeyStretching.deriveKey(secret: secret, argon2Salt: s1, pbkdf2Salt: other, parameters: p, info: "label") != key)759        #expect(try KeyStretching.deriveKey(secret: secret, argon2Salt: s1, pbkdf2Salt: s2, parameters: p, info: "other") != key)760        #expect(try KeyStretching.deriveKey(secret: secret + [0], argon2Salt: s1, pbkdf2Salt: s2, parameters: p, info: "label") != key)761        var q = p762        q.pbkdf2Iterations = 21763        #expect(try KeyStretching.deriveKey(secret: secret, argon2Salt: s1, pbkdf2Salt: s2, parameters: q, info: "label") != key)764        q = p765        q.argon2Iterations = 3766        #expect(try KeyStretching.deriveKey(secret: secret, argon2Salt: s1, pbkdf2Salt: s2, parameters: q, info: "label") != key)767        // the empty secret is a valid input of both functions768        _ = try KeyStretching.deriveKey(secret: [], argon2Salt: s1, pbkdf2Salt: s2, parameters: p, info: "label")769    }770771    @Test func kdfParameterLimits() {772        #expect(KDFParameters.standard.isWithinLimits)773        #expect(KDFParameters.standard == KDFParameters(argon2MemoryKiB: 64 * 1024, argon2Iterations: 3, argon2Parallelism: 4, pbkdf2Iterations: 600_000))774        #expect(KDFParameters.insecureForTesting.isWithinLimits)775        let bad: [KDFParameters] = [776            .init(argon2MemoryKiB: 7, argon2Iterations: 1, argon2Parallelism: 1, pbkdf2Iterations: 1),777            .init(argon2MemoryKiB: (1 << 21) + 1, argon2Iterations: 1, argon2Parallelism: 1, pbkdf2Iterations: 1),778            .init(argon2MemoryKiB: 64, argon2Iterations: 0, argon2Parallelism: 1, pbkdf2Iterations: 1),779            .init(argon2MemoryKiB: 64, argon2Iterations: 65, argon2Parallelism: 1, pbkdf2Iterations: 1),780            .init(argon2MemoryKiB: 64, argon2Iterations: 1, argon2Parallelism: 0, pbkdf2Iterations: 1),781            .init(argon2MemoryKiB: 64, argon2Iterations: 1, argon2Parallelism: 17, pbkdf2Iterations: 1),782            .init(argon2MemoryKiB: 64, argon2Iterations: 1, argon2Parallelism: 1, pbkdf2Iterations: 0),783            .init(argon2MemoryKiB: 64, argon2Iterations: 1, argon2Parallelism: 1, pbkdf2Iterations: 10_000_001),784        ]785        for p in bad {786            #expect(!p.isWithinLimits)787            #expect(throws: VaultError.invalidParameters) {788                _ = try KeyStretching.deriveKey(secret: [1], argon2Salt: Bytes(repeating: 0, count: 16), pbkdf2Salt: Bytes(repeating: 0, count: 16), parameters: p, info: "x")789            }790        }791    }792793    @Test func systemPBKDF2MatchesRFC6070StyleVector() throws {794        // PBKDF2-HMAC-SHA512, "password" / "salt", 1 and 2 iterations (widely published vectors)795        let one = try SystemCrypto.pbkdf2SHA512(password: Bytes("password".utf8), salt: Bytes("salt".utf8), iterations: 1, length: 64)796        #expect(one.hex == "867f70cf1ade02cff3752599a3a53dc4af34c7a669815ae5d513554e1c8cf252c02d470a285a0501bad999bfe943c08f050235d7d68b1da55e63f73b60a57fce")797        let two = try SystemCrypto.pbkdf2SHA512(password: Bytes("password".utf8), salt: Bytes("salt".utf8), iterations: 2, length: 64)798        #expect(two.hex == "e1d9c16aa681708a45f5c7c4e215ceb66e011a2e9f0040713f18aefdb866d53cf76cab2868a39b9f7840edce4fef5a82be67335c77a6068e04112754f27ccf4e")799    }800801    @Test func noncesAreUniqueAcrossManySeals() async throws {802        let f = try Fixture()803        let vault = f.vault()804        try await vault.create(password: "pw")805        var nonces = Set<Bytes>()806        let first = try await vault.addRecord(type: .custom, payload: [0])807        for i in 0..<150 {808            _ = try await vault.addRecord(type: .custom, payload: [UInt8(i)])809            try await vault.updateRecord(first, payload: [UInt8(i)])810            let file = try VaultFile.parse(try f.fileBytes()).file811            nonces.insert(file.records[0].nonce)812            nonces.insert(try #require(file.records.last).nonce)813        }814        #expect(nonces.count == 300)815        let file = try VaultFile.parse(try f.fileBytes()).file816        let all = file.records.map(\.nonce) + [try #require(file.password).nonce]817        #expect(Set(all).count == all.count)818        // identical plaintexts never give identical ciphertexts819        let x = try await vault.addRecord(type: .custom, payload: [1, 2, 3])820        let y = try await vault.addRecord(type: .custom, payload: [1, 2, 3])821        let last = try VaultFile.parse(try f.fileBytes()).file.records.suffix(2)822        #expect(last.first?.sealed != last.last?.sealed)823        #expect(x != y)824    }825}826827@Suite struct VaultRotationTests {828    @Test func rotationKeepsRecordsAndInvalidatesTheOldKey() async throws {829        let f = try Fixture()830        let vault = f.vault()831        try await vault.create(password: "pw")832        var payloads: [UUID: Bytes] = [:]833        for (i, type) in RecordType.allCases.enumerated() {834            let p = SystemRandom.bytes(10 + i)835            payloads[try await vault.addRecord(type: type, payload: p)] = p836        }837        try await vault.enableDeviceSlot(useSecureEnclave: true)838        try await vault.enablePIN("135790")839        let before = try await vault.recordSummaries()840        let oldKey = try #require(await vault.masterKeyCopyForTesting())841        let oldFile = try VaultFile.parse(try f.fileBytes())842843        await expectVaultError(.wrongPassword) { _ = try await vault.rotateMasterKey(password: "nope", pin: "135790") }844        await expectVaultError(.wrongPIN(retryAllowedAt: nil)) { _ = try await vault.rotateMasterKey(password: "pw", pin: "000000") }845        #expect(try await vault.report().keyEpoch == 1)846847        let result = try await vault.rotateMasterKey(password: "pw", pin: "135790")848        #expect(result == KeyRotationResult(newKeyEpoch: 2, recordsReencrypted: 6, pinSlotKept: true))849        let newKey = try #require(await vault.masterKeyCopyForTesting())850        #expect(newKey != oldKey)851852        // every record is still readable, with the same identity and dates853        for (id, p) in payloads { #expect(try await vault.record(id).payload == p) }854        let after = try await vault.recordSummaries()855        #expect(after.map(\.id) == before.map(\.id))856        #expect(after.map(\.createdAt) == before.map(\.createdAt))857        #expect(after.allSatisfy { $0.keyEpoch == 2 })858        #expect(try await vault.verifyIntegrity().recordsVerified == 6)859860        // the old master key opens nothing in the new file, and no copy of the old file is left861        let newFile = try VaultFile.parse(try f.fileBytes())862        #expect(try f.store.readPrevious(f.name) == f.fileBytes())863        for epoch in [UInt32(1), 2] {864            let oldMAC = VaultFile.subkey(master: oldKey, vaultID: newFile.file.vaultID, epoch: epoch, label: VaultLabels.fileMAC)865            #expect(SystemCrypto.hmacSHA256(key: oldMAC, message: newFile.authenticated) != newFile.mac)866            let oldRecords = VaultFile.subkey(master: oldKey, vaultID: newFile.file.vaultID, epoch: epoch, label: VaultLabels.records)867            for r in newFile.file.records {868                let aad = VaultFile.recordAAD(vaultID: newFile.file.vaultID, recordID: r.id, type: r.type, createdAt: r.createdAt, epoch: r.epoch)869                #expect(throws: VaultError.integrityFailure) { _ = try SystemAEAD().open(key: oldRecords, nonce: r.nonce, sealed: r.sealed, associatedData: aad) }870            }871        }872        for (old, new) in zip(oldFile.file.records, newFile.file.records) {873            #expect(old.sealed != new.sealed && old.nonce != new.nonce)874        }875        #expect(oldFile.file.password != newFile.file.password)876        #expect(oldFile.file.device != newFile.file.device)877        #expect(oldFile.file.pin != newFile.file.pin)878879        // every slot opens the rotated vault880        await vault.lock()881        let unlocks: [(Vault) async throws -> Void] = [882            { try await $0.unlock(password: "pw") }, { try await $0.unlockWithDevice() }, { try await $0.unlock(pin: "135790") },883        ]884        for unlock in unlocks {885            let again = f.vault()886            try await unlock(again)887            #expect(await again.masterKeyCopyForTesting() == newKey)888            #expect(try await again.records().count == 6)889        }890891        // an attacker holding the old file and the old slots' secrets cannot use them against the new file892        try f.store.write(oldFile.file.encoded(macKey: VaultFile.subkey(master: oldKey, vaultID: oldFile.file.vaultID, epoch: 1, label: VaultLabels.fileMAC)), to: f.name, keepPrevious: false)893        try f.store.removePrevious(f.name)894        let stale = f.vault()895        await expectVaultError(.deviceKeyUnavailable) { try await stale.unlockWithDevice() }896    }897898    @Test func rotationWithoutThePINRemovesThePINSlot() async throws {899        let f = try Fixture()900        let vault = f.vault()901        try await vault.create(password: "pw")902        let id = try await vault.addRecord(type: .custom, payload: [1])903        try await vault.enablePIN("135790")904        let result = try await vault.rotateMasterKey(password: "pw")905        #expect(result == KeyRotationResult(newKeyEpoch: 2, recordsReencrypted: 1, pinSlotKept: false))906        #expect(await !vault.isPINEnabled)907        #expect(f.keychain.accounts.isEmpty)908        await vault.lock()909        await expectVaultError(.pinNotEnabled) { try await vault.unlock(pin: "135790") }910        try await vault.unlock(password: "pw")911        #expect(try await vault.record(id).payload == [1])912        let second = try await vault.rotateMasterKey(password: "pw")913        #expect(second.newKeyEpoch == 3 && second.pinSlotKept)914    }915}916917@Suite struct SecretBytesTests {918    @Test func neverPrintable() {919        let secret = SecretBytes(Bytes("top secret seed".utf8))920        #expect(secret.description == "<redacted>")921        #expect(secret.debugDescription == "<redacted>")922        #expect("\(secret)" == "<redacted>")923        #expect(String(describing: secret) == "<redacted>")924        #expect(String(reflecting: secret) == "<redacted>")925        var dumped = ""926        dump(secret, to: &dumped)927        #expect(!dumped.contains("116"))928        #expect(Mirror(reflecting: secret).children.isEmpty)929        struct Holder { let s: SecretBytes }930        #expect(!"\(Holder(s: secret))".contains("top"))931    }932933    @Test func contentAccess() {934        let bytes = SystemRandom.bytes(48)935        let a = SecretBytes(bytes), b = SecretBytes(bytes), c = SecretBytes(Bytes(bytes.reversed()))936        #expect(a.count == 48)937        #expect(a.copyBytes() == bytes)938        #expect(a.withBytes { Bytes($0) } == bytes)939        #expect(a.constantTimeEquals(b))940        #expect(!a.constantTimeEquals(c))941        #expect(!a.constantTimeEquals(SecretBytes(Bytes(bytes.dropLast()))))942        #expect(SecretBytes([]).count == 0)943        #expect(SecretBytes([]).copyBytes().isEmpty)944        let r = SecretBytes.random(32), s = SecretBytes.random(32)945        #expect(r.count == 32 && !r.constantTimeEquals(s))946    }947}948949@Suite struct PasswordQualityTests {950    @Test func levelsAreOrderedSensibly() {951        let veryWeak = ["", "a", "password", "Password1!", "123456", "qwertyuiop", "aaaaaaaaaaaa", "bitcoin2024", "abcdefgh"]952        for p in veryWeak {953            #expect(PasswordQuality.estimate(p).level <= .weak, "\(p): \(PasswordQuality.estimate(p))")954        }955        let strong = ["correct horse battery staple", "T7#kq9!Lm2$xVb4@", "vexing-Quartz-plumb-91-otter"]956        for p in strong {957            #expect(PasswordQuality.estimate(p).level >= .strong, "\(p): \(PasswordQuality.estimate(p))")958        }959        #expect(PasswordQuality.estimate("hT9$kLw2").level < PasswordQuality.estimate("hT9$kLw2pQ7!zR4&").level)960    }961962    @Test func warnings() {963        #expect(PasswordQuality.estimate("").warnings == [.tooShort])964        #expect(PasswordQuality.estimate("password").warnings.contains(.commonPassword))965        #expect(PasswordQuality.estimate("MyP@ssw0rd!!").warnings.contains(.commonPassword))966        #expect(PasswordQuality.estimate("zzzzzzzzzzzz").warnings.contains(.repeatedCharacters))967        #expect(PasswordQuality.estimate("xk abcdef pt").warnings.contains(.sequentialCharacters))968        #expect(PasswordQuality.estimate("mz asdfgh pt").warnings.contains(.keyboardPattern))969        #expect(PasswordQuality.estimate("otter1987plum").warnings.contains(.yearOrDate))970        #expect(PasswordQuality.estimate("lowercaseonly").warnings.contains(.singleCharacterClass))971        #expect(PasswordQuality.estimate("8402751936").warnings.contains(.mostlyDigits))972        let e = PasswordQuality.estimate("T7#kq9!Lm2$xVb4@")973        #expect(e.warnings.isEmpty && e.characterClasses == 4 && e.length == 16 && e.entropyBits > 90)974        #expect(PasswordQuality.estimate("été chaud à Québec").characterClasses == 3)975    }976}977
Files main
Menu

Theme