Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : Tests/QyvoraWalletTests/FindingsFreshAuthenticationTests.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 Testing43import QyvoraMath44import QyvoraCore45import QyvoraBitcoin46import QyvoraEthereum47import QyvoraNetworking48import QyvoraVault49@testable import QyvoraWallet5051/// Regression tests of QYV-APP-002: the sensitive calls of the service need a credential verified recently, not52/// only an unlocked vault, so that no screen can skip the re-authentication.53struct FreshAuthenticationTests {54 /// Runs `body` and expects `authenticationRequired`.55 static func required(_ what: String, _ body: () async throws -> Void, sourceLocation: SourceLocation = #_sourceLocation) async {56 do {57 try await body()58 Issue.record("\(what) ran without a fresh authentication", sourceLocation: sourceLocation)59 } catch WalletError.authenticationRequired {60 } catch {61 Issue.record("\(what): expected authenticationRequired, got \(error)", sourceLocation: sourceLocation)62 }63 }6465 @Test func theWindowsAreTheDocumentedOnes() {66 #expect(WalletService.authenticationWindow == 120)67 #expect(WalletService.setupAuthenticationWindow == 900)68 #expect(WalletError.authenticationRequired.userMessage.contains("Confirm it is you"))69 }7071 @Test func everySensitiveCallNeedsAFreshAuthentication() async throws {72 let h = try await Harness.abandonWallet()73 defer { h.cleanup() }74 _ = try await h.service.createIdentity()75 try await h.service.enablePIN("481516")76 try await h.service.enableBiometrics(useSecureEnclave: false)77 let a0 = try await h.receive(0)78 h.backend.fund(a0, 200_000, height: 100)79 h.backend.balances[EthereumWalletTests.owner] = EthereumWalletTests.oneEther80 _ = try await h.service.syncBitcoin()81 let directory = FileManager.default.temporaryDirectory.appendingPathComponent("qy-auth-\(UUID().uuidString)")82 try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)83 defer { try? FileManager.default.removeItem(at: directory) }84 let url = directory.appendingPathComponent("wallet.qyvora")85 let receiver = try await Harness.make()86 defer { receiver.cleanup() }87 let reception = try await receiver.service.beginTransferReception()8889 // the vault stays unlocked; the authentication ages past the window90 #expect(await h.service.authenticationValidity() == 120)91 h.clock.advance(WalletService.authenticationWindow + 1)92 #expect(await h.vault.isUnlocked)93 #expect(await h.service.authenticationValidity() == 0)9495 // preparing and reviewing are not sensitive: nothing secret is read96 let plan = try await h.service.prepareBitcoinSend(to: externalAddress(), amount: 50_000, feeRate: FeeRate(satPerVByte: 2))97 let review = try await h.service.prepareEthereumSend(asset: .ether, to: EthereumWalletTests.recipient, amount: UInt256(1_000))98 let psbt = try await h.service.exportPSBT(plan).text99 let payload = try await h.service.exportUnsignedEthereum(review).text100 _ = try await h.service.reviewPSBT([psbt])101 _ = try await h.service.recoverySheet()102 _ = try await h.service.identity()103104 await Self.required("revealRecoveryPhrase") { _ = try await h.service.revealRecoveryPhrase() }105 await Self.required("recoverySheet with private material") { _ = try await h.service.recoverySheet(includePrivateMaterial: true) }106 await Self.required("createBackup") { _ = try await h.service.createBackup(to: url, password: "backup river stone 71") }107 await Self.required("createTransferPackage") { _ = try await h.service.createTransferPackage(to: reception.export.frames, backupPassword: "transfer copper owl 38") }108 await Self.required("signAndBroadcastBitcoin") { _ = try await h.service.signAndBroadcastBitcoin(plan) }109 await Self.required("signPSBT") { _ = try await h.service.signPSBT([psbt]) }110 await Self.required("signAndBroadcastEthereum") { _ = try await h.service.signAndBroadcastEthereum(review) }111 await Self.required("signColdEthereumPayload") { _ = try await h.service.signColdEthereumPayload([payload]) }112 await Self.required("signMessage") { _ = try await h.service.signMessage([1, 2, 3]) }113 await Self.required("rotateIdentity") { _ = try await h.service.rotateIdentity(dual: false) }114 await Self.required("disablePIN") { try await h.service.disablePIN() }115 await Self.required("disableBiometrics") { try await h.service.disableBiometrics() }116 var endpoints = FakeBackend.endpoints117 endpoints.priceAPI = ""118 await Self.required("setEndpoints") { try await h.service.setEndpoints(endpoints) }119 await Self.required("resetEndpoints") { try await h.service.resetEndpoints() }120 await Self.required("setMainnetOptIn") { _ = try await h.service.setMainnetOptIn(true) }121 // nothing happened122 #expect(!FileManager.default.fileExists(atPath: url.path))123 #expect(h.backend.broadcastBitcoin.isEmpty && h.backend.broadcastEthereum.isEmpty)124 #expect(await h.service.vaultStatus() == VaultStatus(exists: true, isUnlocked: true, biometricEnabled: true, pinEnabled: true))125 #expect(await h.service.currentProfile().endpoints == FakeBackend.endpoints)126 #expect(await h.service.currentProfile().mainnetOptIn == false)127128 // adding an unlock method has the longer set-up window, and it ends too129 try await h.service.enablePIN("730915")130 h.clock.advance(WalletService.setupAuthenticationWindow)131 await Self.required("enablePIN") { try await h.service.enablePIN("730915") }132 await Self.required("enableBiometrics") { try await h.service.enableBiometrics(useSecureEnclave: false) }133134 // each kind of credential authorizes again: PIN, biometrics, password135 try await h.service.unlock(pin: "730915")136 #expect(try await h.service.revealRecoveryPhrase() == Harness.abandon)137 h.clock.advance(121)138 await Self.required("revealRecoveryPhrase") { _ = try await h.service.revealRecoveryPhrase() }139 try await h.service.unlockWithBiometrics(prompt: "test")140 #expect(try await h.service.recoverySheet(includePrivateMaterial: true).privateMaterial != nil)141 h.clock.advance(121)142 // a wrong credential authorizes nothing143 #expect(await walletError { try await h.service.unlock(password: "not the password") } == .wrongPassword)144 await Self.required("signMessage") { _ = try await h.service.signMessage([1, 2, 3]) }145 try await h.service.unlock(password: Harness.password)146 _ = try await h.service.signMessage([1, 2, 3])147 _ = try await h.service.createBackup(to: url, password: "backup river stone 71")148 _ = try await h.service.signAndBroadcastBitcoin(plan)149 _ = try await h.service.signAndBroadcastEthereum(review)150 #expect(h.backend.broadcastBitcoin.count == 1 && h.backend.broadcastEthereum.count == 1)151 try await h.service.setEndpoints(endpoints)152 try await h.service.disablePIN()153154 // exactly at the end of the window it still holds; one second later it does not155 try await h.service.unlock(password: Harness.password)156 h.clock.advance(120)157 _ = try await h.service.revealRecoveryPhrase()158 h.clock.advance(1)159 await Self.required("revealRecoveryPhrase") { _ = try await h.service.revealRecoveryPhrase() }160 }161162 @Test func lockingAndClockTricksEndTheAuthentication() async throws {163 let h = try await Harness.abandonWallet()164 defer { h.cleanup() }165 _ = try await h.service.revealRecoveryPhrase()166 // setting the date back does not extend it (the window is counted on the monotonic clock)…167 h.clock.advance(100)168 h.clock.setDate(by: -3_600)169 _ = try await h.service.revealRecoveryPhrase()170 h.clock.advance(21)171 await Self.required("revealRecoveryPhrase") { _ = try await h.service.revealRecoveryPhrase() }172 // …a restart of the device ends it…173 try await h.service.unlock(password: Harness.password)174 h.clock.reboot(downtime: 1, uptimeAfter: 1_000_000)175 await Self.required("revealRecoveryPhrase") { _ = try await h.service.revealRecoveryPhrase() }176 // …and so does a lock: after it the vault is the first obstacle177 try await h.service.unlock(password: Harness.password)178 await h.service.lock()179 #expect(await h.service.authenticationValidity() == 0)180 #expect(await walletError { try await h.service.revealRecoveryPhrase() } == .vaultLocked)181 // the auto-lock ends it as well182 try await h.service.unlock(password: Harness.password)183 try await h.service.setAutoLockPolicy(.immediately)184 #expect(await h.service.autoLockIfNeeded())185 #expect(await h.service.authenticationValidity() == 0)186 }187188 /// A watch-only wallet has no vault and no credential: its settings are not gated (there is nothing to verify).189 @Test func aWalletWithoutVaultIsNotAskedForACredential() async throws {190 let h = try await Harness.make()191 defer { h.cleanup() }192 try await h.service.importWatchOnly(bitcoinExtendedPublicKey: nil, ethereumAddress: EthereumWalletTests.recipient)193 h.clock.advance(10_000)194 var endpoints = FakeBackend.endpoints195 endpoints.priceAPI = ""196 try await h.service.setEndpoints(endpoints)197 #expect(await walletError { try await h.service.revealRecoveryPhrase() } == .watchOnly)198 }199}200201/// Regression tests of QYV-APP-003 (the auto-lock is applied at every event of the application's life cycle) and202/// QYV-APP-004 (no "never", a delay of fifteen minutes at most).203struct AutoLockTests {204 @Test func theRuleNeverTouchesALockedVaultAndNeverLocksOnInactivity() {205 for event in AutoLockRule.Event.allCases {206 for policy in [AutoLockPolicy.immediately, .after(seconds: 60), .never] {207 #expect(AutoLockRule.action(for: event, policy: policy, isUnlocked: false) == .none)208 // the Face ID sheet of the system makes the application inactive: locking there would undo the unlock209 #expect(AutoLockRule.action(for: .becameInactive, policy: policy, isUnlocked: true) == .none)210 }211 }212 }213214 @Test func everyOtherEventLocksOrAppliesThePolicy() {215 #expect(AutoLockRule.action(for: .enteredBackground, policy: .immediately, isUnlocked: true) == .lock)216 #expect(AutoLockRule.action(for: .enteredBackground, policy: .after(seconds: 300), isUnlocked: true) == .applyPolicy)217 for policy in [AutoLockPolicy.immediately, .after(seconds: 30), .after(seconds: 900)] {218 #expect(AutoLockRule.action(for: .returnedFromBackground, policy: policy, isUnlocked: true) == .applyPolicy)219 #expect(AutoLockRule.action(for: .timerFired, policy: policy, isUnlocked: true) == .applyPolicy)220 }221 #expect(AutoLockRule.timerRuns(policy: .after(seconds: 300), isUnlocked: true, sceneIsActive: true))222 #expect(!AutoLockRule.timerRuns(policy: .after(seconds: 300), isUnlocked: false, sceneIsActive: true))223 #expect(!AutoLockRule.timerRuns(policy: .after(seconds: 300), isUnlocked: true, sceneIsActive: false))224 #expect(!AutoLockRule.timerRuns(policy: .immediately, isUnlocked: true, sceneIsActive: true))225 #expect(AutoLockRule.timerInterval <= 15)226 // the wallet stays covered until the policy has been applied on return227 #expect(AutoLockRule.coversContent(sceneIsActive: true, applyingPolicy: true))228 #expect(AutoLockRule.coversContent(sceneIsActive: false, applyingPolicy: false))229 #expect(!AutoLockRule.coversContent(sceneIsActive: true, applyingPolicy: false))230 }231232 /// The life cycle played against the real service, the way the root view does it.233 @Test func theLifeCycleLocksTheVaultImmediatelyAfterTheDelayAndInTheBackground() async throws {234 let h = try await Harness.abandonWallet()235 defer { h.cleanup() }236 /// Carries out the action of the rule; returns true when the vault is locked afterwards.237 func play(_ event: AutoLockRule.Event) async -> Bool {238 let profile = await h.service.currentProfile()239 switch AutoLockRule.action(for: event, policy: profile.autoLock, isUnlocked: await h.vault.isUnlocked) {240 case .none: break241 case .lock: await h.service.lock()242 case .applyPolicy: _ = await h.service.autoLockIfNeeded()243 }244 return await !h.vault.isUnlocked245 }246247 // after N: the timer locks once the delay has passed without activity, not before248 try await h.service.setAutoLockPolicy(.after(seconds: 60))249 await h.service.noteActivity()250 h.clock.advance(45)251 #expect(await play(.timerFired) == false)252 await h.service.noteActivity()253 h.clock.advance(45)254 #expect(await play(.timerFired) == false)255 h.clock.advance(15)256 #expect(await play(.timerFired))257258 // background: the time spent away counts when the application comes back259 try await h.service.unlock(password: Harness.password)260 #expect(await play(.becameInactive) == false)261 #expect(await play(.enteredBackground) == false)262 h.clock.advance(59)263 #expect(await play(.returnedFromBackground) == false)264 #expect(await play(.enteredBackground) == false)265 h.clock.advance(2)266 #expect(await play(.returnedFromBackground))267 // a delay that elapsed before the application left is applied on the way out268 try await h.service.unlock(password: Harness.password)269 h.clock.advance(61)270 #expect(await play(.enteredBackground))271272 // immediately: leaving for the background locks at once; the Face ID sheet (inactive) does not273 try await h.service.unlock(password: Harness.password)274 try await h.service.setAutoLockPolicy(.immediately)275 #expect(await play(.becameInactive) == false)276 #expect(await play(.enteredBackground))277 // a wall clock set backwards locks rather than extending the session278 try await h.service.unlock(password: Harness.password)279 try await h.service.setAutoLockPolicy(.after(seconds: 300))280 h.clock.setDate(by: -3_600)281 #expect(await play(.timerFired))282 }283284 @Test func neverAndLongDelaysAreRefusedAndOldProfilesAreBounded() async throws {285 #expect(WalletService.maximumAutoLockDelay == 900)286 let h = try await Harness.abandonWallet()287 defer { h.cleanup() }288 #expect(await h.service.currentProfile().autoLock == .after(seconds: 300))289 guard case .invalidInput(let why)? = await walletError({ try await h.service.setAutoLockPolicy(.never) }) else {290 Issue.record("never must be refused")291 return292 }293 #expect(why.contains("cannot be switched off"))294 for bad in [901.0, 3_600, .infinity, .nan, 4, -1] {295 guard case .invalidInput? = await walletError({ try await h.service.setAutoLockPolicy(.after(seconds: bad)) }) else {296 Issue.record("\(bad) seconds must be refused")297 return298 }299 }300 #expect(await h.service.currentProfile().autoLock == .after(seconds: 300))301 try await h.service.setAutoLockPolicy(.after(seconds: 900))302 try await h.service.setAutoLockPolicy(.immediately)303304 // lengthening the delay needs a fresh authentication; shortening it does not305 h.clock.advance(WalletService.authenticationWindow + 1)306 try await h.service.unlock(password: Harness.password)307 h.clock.advance(WalletService.authenticationWindow + 1)308 #expect(await walletError { try await h.service.setAutoLockPolicy(.after(seconds: 600)) } == .authenticationRequired)309 try await h.service.unlock(password: Harness.password)310 try await h.service.setAutoLockPolicy(.after(seconds: 600))311 h.clock.advance(WalletService.authenticationWindow + 1)312 try await h.service.unlock(password: Harness.password)313 h.clock.advance(WalletService.authenticationWindow + 1)314 try await h.service.setAutoLockPolicy(.after(seconds: 30))315316 // a profile written by an earlier build with "never" (or one hour) is bounded when it is loaded and applied317 #expect(WalletService.boundedAutoLock(.never) == .after(seconds: 300))318 #expect(WalletService.boundedAutoLock(.after(seconds: 3_600)) == .after(seconds: 900))319 #expect(WalletService.boundedAutoLock(.after(seconds: 60)) == .after(seconds: 60))320 #expect(WalletService.boundedAutoLock(.immediately) == .immediately)321 let url = h.directory.appendingPathComponent(WalletService.profileFile)322 var json = try #require(JSONSerialization.jsonObject(with: Data(contentsOf: url)) as? [String: Any])323 var stored = await h.service.currentProfile()324 stored.autoLock = .never325 let encoded = try #require(JSONSerialization.jsonObject(with: JSONEncoder().encode(stored)) as? [String: Any])326 json["autoLock"] = encoded["autoLock"]327 try JSONSerialization.data(withJSONObject: json).write(to: url)328 let reopened = try await Harness.make(clock: h.clock, directory: h.directory, configure: false)329 #expect(await reopened.service.currentProfile().autoLock == .after(seconds: 300))330 try await reopened.service.unlock(password: Harness.password)331 h.clock.advance(301)332 #expect(await reopened.service.autoLockIfNeeded())333 }334}335