Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : Tests/QyvoraWalletTests/FindingsCredentialTests.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 QyvoraVault47import QyvoraRecovery48@testable import QyvoraWallet4950/// Regression tests of QYV-APP-001 (password floor enforced by the service) and QYV-APP-011 (trivial PINs).51struct CredentialPolicyTests {52 static let weak = ["", "a", "short1!", "password", "Password2026", "passw0rd!!", "qwertyuiop", "aaaaaaaaaaaa", "1234567890", "abcdefghij",53 "bitcoin123", "letmein letmein"]54 static let acceptable = [Harness.password, "quiet lantern 58 marsh", "Tr0ub4dor&3x", "vier Kaffee ohne Zucker", "9$kQz!m2Lp#x"]5556 @Test func theFloorIsTenCharactersAndAFairEstimate() {57 #expect(WalletService.minimumPasswordLength == 10 && WalletService.minimumPasswordLevel == .fair)58 for candidate in Self.weak {59 let reason = WalletService.passwordRejection(candidate)60 #expect(reason != nil, "\(candidate.debugDescription) must be refused")61 }62 for candidate in Self.acceptable {63 #expect(WalletService.passwordRejection(candidate) == nil, "\(candidate.debugDescription) must be accepted")64 #expect(PasswordQuality.estimate(candidate).level >= .fair)65 }66 // ten characters are needed even when the estimate is high67 #expect(WalletService.passwordRejection("9$kQz!m2L") == "The password is too short: at least 10 characters are needed.")68 }6970 @Test func everyEntryPointOfTheServiceRefusesAWeakPassword() async throws {71 let h = try await Harness.make()72 defer { h.cleanup() }73 func refused(_ what: String, _ body: () async throws -> Void, sourceLocation: SourceLocation = #_sourceLocation) async {74 do {75 try await body()76 Issue.record("\(what) accepted a weak password", sourceLocation: sourceLocation)77 } catch WalletError.weakPassword(let reason) {78 #expect(!reason.isEmpty, sourceLocation: sourceLocation)79 } catch {80 Issue.record("\(what): unexpected \(error)", sourceLocation: sourceLocation)81 }82 }83 for weak in ["password", "short1!", ""] {84 await refused("createWallet") { _ = try await h.service.createWallet(password: weak) }85 await refused("importWallet") { try await h.service.importWallet(words: Harness.abandon, password: weak) }86 }87 // nothing was created by the refused attempts88 #expect(await h.vault.exists == false)89 #expect(await h.service.currentProfile().kind == nil)9091 try await h.service.importWallet(words: Harness.abandon, password: Harness.password)92 _ = try await h.service.createIdentity()93 let directory = FileManager.default.temporaryDirectory.appendingPathComponent("qy-floor-\(UUID().uuidString)")94 try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)95 defer { try? FileManager.default.removeItem(at: directory) }96 let url = directory.appendingPathComponent("wallet.qyvora")97 await refused("changePassword") { try await h.service.changePassword(current: Harness.password, new: "password") }98 await refused("createBackup") { _ = try await h.service.createBackup(to: url, password: "backup password") }99 #expect(!FileManager.default.fileExists(atPath: url.path))100 let receiver = try await Harness.make()101 defer { receiver.cleanup() }102 let reception = try await receiver.service.beginTransferReception()103 await refused("createTransferPackage") { _ = try await h.service.createTransferPackage(to: reception.export.frames, backupPassword: "transfer password") }104 // the old password still opens the vault105 await h.service.lock()106 try await h.service.unlock(password: Harness.password)107108 // restoring: the new vault password is held to the floor before anything is opened or created109 _ = try await h.service.createBackup(to: url, password: "backup river stone 71")110 await refused("restoreBackup") { try await receiver.service.restoreBackup(from: url, backupPassword: "backup river stone 71", newPassword: "password") }111 let transfer = try await h.service.createTransferPackage(to: reception.export.frames, backupPassword: "transfer copper owl 38")112 let sender = try await receiver.service.inspectTransferPackage(package: transfer.package).sender.text113 await refused("completeTransferReception") {114 _ = try await receiver.service.completeTransferReception(package: transfer.package, backupPassword: "transfer copper owl 38", newPassword: "qwertyuiop",115 expectedSender: sender)116 }117 #expect(await receiver.vault.exists == false)118 try await receiver.service.restoreBackup(from: url, backupPassword: "backup river stone 71", newPassword: "new device granite lamp 5")119 #expect(await receiver.vault.isUnlocked)120 }121122 // MARK: QYV-APP-011123124 static let trivialPINs = ["000000", "111111", "999999", "123456", "654321", "012345", "987654", "890123", "246802", "135791", "121212", "123123",125 "112233", "123321", "100001", "199004", "042011", "202612", "121990", "147258", "159753", "135790", "314159", "696969",126 "101010", "110011", "787878"]127 static let acceptablePINs = ["481516", "730915", "064829", "918274", "350718", "602947"]128129 @Test func trivialPINsAreNamedByTheRuleThatCatchesThem() {130 for pin in Self.trivialPINs {131 let reason = WalletService.pinRejection(pin)132 #expect(reason?.contains("too easy to guess") == true, "\(pin) must be refused")133 }134 for pin in Self.acceptablePINs { #expect(WalletService.pinRejection(pin) == nil, "\(pin) must be accepted") }135 #expect(WalletService.trivialPINReason("555555") == "one digit repeated")136 #expect(WalletService.trivialPINReason("345678") == "a sequence")137 #expect(WalletService.trivialPINReason("909090") == "a repeated group")138 #expect(WalletService.trivialPINReason("198706") == "it contains a year")139 // the format rules keep their own sentences140 #expect(WalletService.pinRejection("12345") == "A PIN is exactly 6 digits.")141 #expect(WalletService.pinRejection("48151a") == "A PIN is made of digits only (0 to 9).")142 // the rules leave most of the space: fewer than one PIN in ten is refused143 var refused = 0144 for n in 0..<1_000_000 where WalletService.trivialPINReason(String(format: "%06d", n)) != nil { refused += 1 }145 #expect(refused > 40_000 && refused < 100_000, "\(refused) of 1 000 000 PINs are refused")146 }147148 @Test func theServiceRefusesToEnableATrivialPIN() async throws {149 let h = try await Harness.abandonWallet()150 defer { h.cleanup() }151 for pin in ["000000", "123456", "199004", "147258"] {152 guard case .invalidInput(let reason)? = await walletError({ try await h.service.enablePIN(pin) }) else {153 Issue.record("\(pin) must be refused as a PIN")154 return155 }156 #expect(reason.contains("too easy to guess"))157 #expect(await h.service.vaultStatus().pinEnabled == false)158 }159 try await h.service.enablePIN("481516")160 #expect(await h.service.vaultStatus().pinEnabled)161 // a trivial PIN is not accepted as the PIN kept through a key rotation either: it could never have been set162 await h.service.lock()163 #expect(await walletError { try await h.service.unlock(pin: "123456") } == .wrongPIN(retryAllowedAt: nil))164 }165}166167/// Regression tests of QYV-CRY-003 on the signing path of the service.168struct SigningPathHygieneTests {169 @Test func theStoredPhraseFormIsRecognised() {170 #expect(PhraseCodec.isNormalized(PhraseCodec.payload(Harness.abandon)))171 #expect(PhraseCodec.isNormalized(Bytes("abandon".utf8)))172 for bad in ["", " abandon about", "abandon about ", "abandon about", "Abandon about", "abandon\tabout", "abandon about1", "ab\u{00e9}ndon about"] {173 #expect(!PhraseCodec.isNormalized(Bytes(bad.utf8)), "\(bad.debugDescription)")174 }175 }176177 /// Signing still works when the phrase and the passphrase are read as bytes, with and without a passphrase, and178 /// the wallet still refuses to sign when the phrase in the vault is not the one of its account.179 @Test func signingFromBytesGivesTheSameKeysAsTheImport() async throws {180 for passphrase in [nil, "correct horse \u{00e9}\u{2460}"] as [String?] {181 let h = try await Harness.make()182 defer { h.cleanup() }183 try await h.service.importWallet(words: Harness.abandon, passphrase: passphrase, password: Harness.password)184 let a0 = try await h.receive(0)185 #expect((a0 == Harness.abandonFirstTestAddress) == (passphrase == nil))186 h.backend.fund(a0, 100_000, height: 100)187 h.backend.balances[await h.ethereumAddress] = EthereumWalletTests.oneEther188 _ = try await h.service.syncBitcoin()189 let plan = try await h.service.prepareBitcoinSend(to: externalAddress(), amount: 20_000, feeRate: FeeRate(satPerVByte: 2))190 _ = try await h.service.signAndBroadcastBitcoin(plan)191 let review = try await h.service.prepareEthereumSend(asset: .ether, to: EthereumWalletTests.recipient, amount: UInt256(1_000))192 _ = try await h.service.signAndBroadcastEthereum(review)193 #expect(h.backend.broadcastBitcoin.count == 1 && h.backend.broadcastEthereum.count == 1)194 // twice in a row: nothing the first signature erased was needed by the second195 let again = try await h.service.prepareEthereumSend(asset: .ether, to: EthereumWalletTests.recipient, amount: UInt256(2_000), replacePending: true)196 _ = try await h.service.signAndBroadcastEthereum(again)197 #expect(try await h.service.revealRecoveryPhrase() == Harness.abandon)198 }199 }200}201202/// Regression test of QYV-SVC-012 on the restore path of the service.203struct BackupCostTests {204 @Test func aBackupAskingForMoreThanTheDeviceAcceptsIsRefusedBeforeItsPasswordIsTried() async throws {205 let h = try await Harness.make()206 defer { h.cleanup() }207 let records = [VaultRecord(id: UUID(), type: .recoveryPhrase, createdAt: Date(timeIntervalSince1970: 1_800_000_000),208 updatedAt: Date(timeIntervalSince1970: 1_800_000_000), payload: Bytes(Harness.abandon.joined(separator: " ").utf8))]209 // 17 passes over 32 KiB: above the ceiling of 16 passes, cheap to produce in a test210 let costly = KDFParameters(argon2MemoryKiB: 32, argon2Iterations: 17, argon2Parallelism: 1, pbkdf2Iterations: 8)211 let directory = FileManager.default.temporaryDirectory.appendingPathComponent("qy-cost-\(UUID().uuidString)")212 try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)213 defer { try? FileManager.default.removeItem(at: directory) }214 let bad = directory.appendingPathComponent("costly.qyvora")215 try Data(try BackupFile.create(records: records, vaultID: Bytes(repeating: 7, count: 16), password: "backup river stone 71", kdf: costly)).write(to: bad)216 #expect(try await h.service.inspectBackup(at: bad).kdf == costly)217 for password in ["backup river stone 71", "another wrong phrase 5"] {218 guard case .invalidPayload(let why)? = await walletError({ try await h.service.restoreBackup(from: bad, backupPassword: password, newPassword: Harness.password) }) else {219 Issue.record("a backup above the ceiling must be refused")220 return221 }222 #expect(why.contains("beyond what this device accepts") && why.contains("17 passes"))223 }224 #expect(await h.vault.exists == false)225 // the same content at an accepted cost is restored226 let good = directory.appendingPathComponent("good.qyvora")227 try Data(try BackupFile.create(records: records, vaultID: Bytes(repeating: 7, count: 16), password: "backup river stone 71", kdf: .insecureForTesting)).write(to: good)228 try await h.service.restoreBackup(from: good, backupPassword: "backup river stone 71", newPassword: Harness.password)229 #expect(try await h.receive(0) == Harness.abandonFirstTestAddress)230 }231}232