SPB Git

Repository Public

PINClockTests.swift 11.0 KB 216 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Tests/QyvoraVaultTests/PINClockTests.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 Foundation42import QyvoraMath43import QyvoraStorage44import Testing4546@testable import QyvoraVault4748/// Regression tests of QYV-SVC-010: the PIN delays are measured with a clock the holder of the device cannot set.49@Suite struct PINClockTests {50    /// A locked vault with a PIN and `failures` consecutive wrong PINs, each entered as soon as it is allowed.51    static func lockedOut(_ f: Fixture, failures: Int) async throws -> Vault {52        let vault = f.vault()53        try await vault.create(password: "pw")54        try await vault.enablePIN("135790")55        await vault.lock()56        for n in 1...failures {57            _ = try? await vault.unlock(pin: "000000")58            if n < failures { f.clock.advance(PINPolicy.delay(afterFailedAttempts: n)) }59        }60        #expect(try await vault.report().pinFailedAttempts == failures)61        return vault62    }6364    @Test func settingTheDateForwardDoesNotShortenTheDelay() async throws {65        let f = try Fixture()66        let vault = try await Self.lockedOut(f, failures: 8)   // 24 hours67        // the attack of the finding: the date is set one day (then one year) ahead; no time has really passed68        f.clock.setDate(by: 86_400)69        await expectVaultError(.pinLocked(until: f.clock.now.addingTimeInterval(86_400))) { try await vault.unlock(pin: "135790") }70        f.clock.setDate(by: 365 * 86_400)71        await expectVaultError(.pinLocked(until: f.clock.now.addingTimeInterval(86_400))) { try await vault.unlock(pin: "135790") }72        #expect(try await vault.report().pinFailedAttempts == 8)73        #expect(await !vault.isUnlocked)74        // the refusal restarted the delay: one second short of a real day is still too early75        f.clock.advance(86_399)76        await expectVaultError(.pinLocked(until: f.clock.now.addingTimeInterval(1))) { try await vault.unlock(pin: "135790") }77        f.clock.advance(1)78        try await vault.unlock(pin: "135790")79        #expect(try await vault.report().pinFailedAttempts == 0)80    }8182    @Test func aRestartOfTheDeviceRestartsTheDelay() async throws {83        let f = try Fixture()84        let vault = try await Self.lockedOut(f, failures: 4)   // 5 minutes85        f.clock.advance(200)86        // restart, with a date far ahead for good measure: the time elapsed cannot be measured any more87        f.clock.reboot(downtime: 100_000)88        let after = f.clock.now89        await expectVaultError(.pinLocked(until: after.addingTimeInterval(300))) { try await vault.unlock(pin: "135790") }90        f.clock.advance(299)91        await expectVaultError(.pinLocked(until: after.addingTimeInterval(300))) { try await vault.unlock(pin: "135790") }92        f.clock.advance(1)93        try await vault.unlock(pin: "135790")94    }9596    /// A restart shortly after which the monotonic clock is already past its value at the failure: the boot session97    /// identifier is what tells the two sessions apart.98    @Test func aLongerUptimeInAnotherBootSessionGivesNoCredit() async throws {99        let f = try Fixture()100        let vault = try await Self.lockedOut(f, failures: 5)   // 15 minutes101        f.clock.reboot(downtime: 10, uptimeAfter: 1_000_000)102        await expectVaultError(.pinLocked(until: f.clock.now.addingTimeInterval(900))) { try await vault.unlock(pin: "135790") }103    }104105    @Test func settingTheDateBackwardsRestartsTheDelayAndCannotExtendItForever() async throws {106        let f = try Fixture()107        let vault = try await Self.lockedOut(f, failures: 3)   // 1 minute108        f.clock.advance(50)109        f.clock.setDate(by: -3_600)110        await expectVaultError(.pinLocked(until: f.clock.now.addingTimeInterval(60))) { try await vault.unlock(pin: "135790") }111        f.clock.advance(60)112        try await vault.unlock(pin: "135790")113    }114115    /// A small correction of the clock (network time) while a delay is pending changes nothing.116    @Test func aSmallClockCorrectionIsTolerated() async throws {117        let f = try Fixture()118        let vault = try await Self.lockedOut(f, failures: 3)119        f.clock.advance(20)120        f.clock.setDate(by: PINPolicy.clockDisagreementTolerance)121        await expectVaultError(.pinLocked(until: f.clock.now.addingTimeInterval(40))) { try await vault.unlock(pin: "135790") }122        f.clock.advance(40)123        try await vault.unlock(pin: "135790")124    }125126    /// A date set forward once the delay has really elapsed blocks nothing.127    @Test func theDelayIsServedInMonotonicTimeWhateverTheDateSays() async throws {128        let f = try Fixture()129        let vault = try await Self.lockedOut(f, failures: 4)130        f.clock.advance(300)131        f.clock.setDate(by: 5_000_000)132        try await vault.unlock(pin: "135790")133    }134135    /// The state written before this rule (version 1, 17 bytes) has no monotonic time: a pending delay starts again.136    @Test func aStateOfTheOldFormatRestartsItsDelay() async throws {137        let f = try Fixture()138        let vault = f.vault()139        try await vault.create(password: "pw")140        try await vault.enablePIN("135790")141        await vault.lock()142        let account = try #require(f.keychain.accounts.first { $0.hasSuffix("pin-state") })143        // the new format carries the monotonic time and the boot session144        #expect(try f.keychain.get(account: account, prompt: nil).count == 1 + 4 + 8 + 4 + 8 + 1)145        _ = try? await vault.unlock(pin: "000000")146        #expect(try f.keychain.get(account: account, prompt: nil).count == 1 + 4 + 8 + 4 + 8 + 1 + 16)147148        // version 1: four failures, the last one ten minutes ago by the wall clock (its five minutes would be over)149        var w = ByteWriter()150        w.u8(1)151        w.u32(4)152        w.u64(VaultTime.seconds(f.clock.now) - 600)153        w.u32(0)154        try f.keychain.set(w.bytes, account: account, access: .passcodeSetThisDeviceOnly)155        await expectVaultError(.pinLocked(until: f.clock.now.addingTimeInterval(300))) { try await vault.unlock(pin: "135790") }156        f.clock.advance(300)157        try await vault.unlock(pin: "135790")158        // without a pending delay an old state is simply read159        var free = ByteWriter()160        free.u8(1)161        free.u32(2)162        free.u64(VaultTime.seconds(f.clock.now))163        free.u32(0)164        await vault.lock()165        try f.keychain.set(free.bytes, account: account, access: .passcodeSetThisDeviceOnly)166        try await vault.unlock(pin: "135790")167    }168169    @Test func theSystemClockIsMonotonicAndNamesItsBootSession() {170        let a = MonotonicInstant.system(), b = MonotonicInstant.system()171        #expect(b.seconds >= a.seconds && a.seconds > 0)172        #expect(a.bootSession == b.bootSession)173        // macOS and iOS give the boot session identifier; without it the monotonic comparison alone applies174        #expect(a.bootSession.count == 16 || a.bootSession.isEmpty)175    }176}177178/// Regression tests of QYV-SVC-012: the key-derivation cost written in a file is bounded by what the device accepts.179@Suite struct KDFCeilingTests {180    @Test func theCeilingIsFourTimesTheDefaultAndFarBelowTheFormatBound() {181        let ceiling = KDFParameters.deviceCeiling182        #expect(ceiling == KDFParameters(argon2MemoryKiB: 262_144, argon2Iterations: 16, argon2Parallelism: 16, pbkdf2Iterations: 2_400_000))183        #expect(ceiling.isWithinLimits && KDFParameters.standard.isWithin(ceiling) && KDFParameters.insecureForTesting.isWithin(ceiling))184        #expect(ceiling.isWithin(ceiling))185        // each cost alone is enough to be above it; all of these are inside the format bound186        for above in [KDFParameters(argon2MemoryKiB: 262_145, argon2Iterations: 3, argon2Parallelism: 4, pbkdf2Iterations: 600_000),187                      KDFParameters(argon2MemoryKiB: 1 << 21, argon2Iterations: 64, argon2Parallelism: 16, pbkdf2Iterations: 10_000_000),188                      KDFParameters(argon2MemoryKiB: 65_536, argon2Iterations: 17, argon2Parallelism: 4, pbkdf2Iterations: 600_000),189                      KDFParameters(argon2MemoryKiB: 65_536, argon2Iterations: 3, argon2Parallelism: 4, pbkdf2Iterations: 2_400_001)] {190            #expect(above.isWithinLimits && !above.isWithin(ceiling))191        }192    }193194    /// A vault file whose password slot asks for 17 passes (cheap to produce here: 32 KiB of memory) is refused by a195    /// vault with the default ceiling before any derivation runs, and opened by one configured to accept it.196    @Test func aVaultHeaderAboveTheCeilingIsNotDerived() async throws {197        let f = try Fixture()198        let costly = KDFParameters(argon2MemoryKiB: 32, argon2Iterations: 17, argon2Parallelism: 1, pbkdf2Iterations: 8)199        func vault(ceiling: KDFParameters) -> Vault {200            var configuration = Vault.Configuration(fileName: f.name, kdf: costly)201            configuration.kdfCeiling = ceiling202            return Vault(fileStore: f.store, keychain: f.keychain, configuration: configuration)203        }204        // a vault does not create a slot above its own ceiling205        await expectVaultError(.invalidParameters) { try await vault(ceiling: .deviceCeiling).create(password: "pw") }206        #expect(await !vault(ceiling: .deviceCeiling).exists)207        var raised = KDFParameters.deviceCeiling208        raised.argon2Iterations = 17209        try await vault(ceiling: raised).create(password: "pw")210        // the same file, read with the default ceiling211        await expectVaultError(.corrupted(.malformed)) { try await f.vault().unlock(password: "pw") }212        await expectVaultError(.corrupted(.malformed)) { try await f.vault().unlock(password: "wrong") }213        try await vault(ceiling: raised).unlock(password: "pw")214    }215}216
Files main
Menu

Theme