Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : Tests/QyvoraRecoveryTests/RecoveryTests.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 QyvoraCore44import QyvoraEthereum45import QyvoraMath46import QyvoraStorage47import QyvoraVault48import Testing4950@testable import QyvoraRecovery5152let abandon = BIP39.words(from: "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about")53let junk = BIP39.words(from: "test test test test test test test test test test test junk")5455@Suite struct RecoverySheetTests {56 @Test func bip84VectorAndDescriptors() throws {57 let sheet = try RecoverySheet.make(mnemonic: abandon, createdAt: Date(timeIntervalSince1970: 1_800_000_000.7))58 #expect(sheet.formatVersion == RecoverySheet.currentFormatVersion && sheet.otherChains.isEmpty)59 #expect(sheet.masterFingerprint == "73c5da0a")60 #expect(sheet.mnemonicWordCount == 12)61 #expect(!sheet.usesPassphrase)62 #expect(sheet.privateMaterial == nil)63 #expect(sheet.createdAt == Date(timeIntervalSince1970: 1_800_000_000))64 #expect(sheet.bitcoin.map(\.network) == [.mainnet, .testnet, .signet])6566 // BIP-84 test vector, account 067 let main = sheet.bitcoin[0]68 let zpub = "zpub6rFR7y4Q2AijBEqTUquhVz398htDFrtymD9xYYfG1m4wAcvPhXNfE3EfH1r1ADqtfSdVCToUG868RvUUkgDKf31mGDtKsAYz2oz2AGutZYs"69 let xpub = "xpub6CatWdiZiodmUeTDp8LT5or8nmbKNcuyvz7WyksVFkKB4RHwCD3XyuvPEbvqAQY3rAPshWcMLoP2fMFMKHPJ4ZeZXYVUhLv1VMrjPC7PW6V"70 #expect(main.slip132PublicKey == zpub)71 #expect(main.extendedPublicKey == xpub)72 #expect(main.derivationPath == "m/84'/0'/0'")73 #expect(main.receiveDescriptor == "wpkh([73c5da0a/84h/0h/0h]\(xpub)/0/*)")74 #expect(main.changeDescriptor == "wpkh([73c5da0a/84h/0h/0h]\(xpub)/1/*)")75 #expect(main.firstReceiveAddress == "bc1qcr8te4kr609gcawutmrza0j4xv80jy8z306fyu")7677 // the two serializations describe the same public key, and neither is private78 let a = try ExtendedKey.parse(main.extendedPublicKey), b = try ExtendedKey.parse(main.slip132PublicKey)79 #expect(a.version == .xpub && b.version == .zpub)80 #expect(a.key.publicKey == b.key.publicKey && a.key.chainCode == b.key.chainCode)81 #expect(!a.key.isPrivate && a.key.depth == 3)8283 // test networks: coin type 1, tpub / vpub, tb1 addresses; testnet and signet share keys84 let test = sheet.bitcoin[1], signet = sheet.bitcoin[2]85 #expect(test.derivationPath == "m/84'/1'/0'")86 #expect(test.extendedPublicKey.hasPrefix("tpub") && test.slip132PublicKey.hasPrefix("vpub"))87 #expect(test.slip132PublicKey == "vpub5Y6cjg78GGuNLsaPhmYsiw4gYX3HoQiRBiSwDaBXKUafCt9bNwWQiitDk5VZ5BVxYnQdwoTyXSs2JHRPAgjAvtbBrf8ZhDYe2jWAqvZVnsc")88 #expect(test.receiveDescriptor == "wpkh([73c5da0a/84h/1h/0h]\(test.extendedPublicKey)/0/*)")89 #expect(test.changeDescriptor.hasSuffix("/1/*)"))90 #expect(test.firstReceiveAddress.hasPrefix("tb1q"))91 #expect(signet.extendedPublicKey == test.extendedPublicKey && signet.firstReceiveAddress == test.firstReceiveAddress)92 #expect(test.extendedPublicKey != main.extendedPublicKey)93 }9495 @Test func ethereumAddresses() throws {96 let sheet = try RecoverySheet.make(mnemonic: junk, ethereumAddressCount: 3)97 #expect(sheet.ethereum.map(\.index) == [0, 1, 2])98 #expect(sheet.ethereum.map(\.derivationPath) == ["m/44'/60'/0'/0/0", "m/44'/60'/0'/0/1", "m/44'/60'/0'/0/2"])99 #expect(sheet.ethereum[0].address == "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266")100 #expect(sheet.ethereum[1].address == "0x70997970C51812dc3A010C7d01b50e0d17dc79C8")101 #expect(sheet.ethereum[2].address == "0x3C44CdDdB6a900fa2b585dd299e03d12FA4293BC")102103 // the same address computed step by step with QyvoraEthereum104 let seed = try BIP39.seed(mnemonic: junk)105 let key = try ExtendedKey.master(seed: seed).derive(try #require(DerivationPath("m/44'/60'/0'/0/0")))106 #expect(try EthereumAddress(publicKey: key.publicKey).checksummed == sheet.ethereum[0].address)107108 #expect(try RecoverySheet.make(mnemonic: junk, ethereumAddressCount: 0).ethereum.isEmpty)109 #expect(try RecoverySheet.make(mnemonic: junk).ethereum.count == 5)110 #expect(throws: RecoverySheetError.invalidParameters) { _ = try RecoverySheet.make(mnemonic: junk, ethereumAddressCount: 1001) }111 #expect(throws: RecoverySheetError.invalidParameters) { _ = try RecoverySheet.make(mnemonic: junk, ethereumAddressCount: -1) }112 }113114 @Test func noPrivateMaterialUnlessRequested() throws {115 let phrase = junk.joined(separator: " ")116 let sheet = try RecoverySheet.make(mnemonic: junk, passphrase: "TREZOR")117 #expect(sheet.usesPassphrase && sheet.privateMaterial == nil)118 let json = String(decoding: try sheet.json(), as: UTF8.self)119 let text = sheet.plainText()120 for output in [json, text, String(describing: sheet)] {121 #expect(!output.contains(phrase))122 #expect(!output.contains("junk"))123 #expect(!output.contains("TREZOR"))124 #expect(!output.contains("prv"))125 }126 #expect(text.contains("contains NO private key"))127 #expect(text.contains("BIP-39 passphrase: YES"))128 for account in sheet.bitcoin {129 #expect(text.contains(account.receiveDescriptor) && text.contains(account.changeDescriptor))130 #expect(text.contains(account.slip132PublicKey) && text.contains(account.firstReceiveAddress))131 }132 for account in sheet.ethereum { #expect(text.contains(account.address)) }133 #expect(text.contains(sheet.masterFingerprint))134 #expect(text.utf8.allSatisfy { $0 < 0x80 })135136 // the passphrase changes every key137 let plain = try RecoverySheet.make(mnemonic: junk)138 #expect(plain.masterFingerprint != sheet.masterFingerprint)139 #expect(plain.bitcoin[0].extendedPublicKey != sheet.bitcoin[0].extendedPublicKey)140 #expect(plain.ethereum[0].address != sheet.ethereum[0].address)141142 // explicit request143 let full = try RecoverySheet.make(mnemonic: junk, passphrase: "TREZOR", includePrivateMaterial: true, createdAt: sheet.createdAt)144 #expect(full.privateMaterial == .init(mnemonic: phrase, passphrase: "TREZOR"))145 #expect(full.plainText().contains(phrase) && full.plainText().contains("Passphrase: TREZOR"))146 #expect(full.plainText().contains("PRIVATE"))147 #expect(full.withoutPrivateMaterial == sheet)148 #expect(try RecoverySheet.make(mnemonic: junk, includePrivateMaterial: true).privateMaterial?.passphrase == nil)149 }150151 @Test func jsonRoundTripAndInvalidPhrase() throws {152 let sheet = try RecoverySheet.make(mnemonic: abandon, includePrivateMaterial: true)153 #expect(try RecoverySheet.fromJSON(try sheet.json()) == sheet)154 #expect(try JSONDecoder().decode(RecoverySheet.self, from: try JSONEncoder().encode(sheet)) == sheet)155156 var wrongChecksum = abandon157 wrongChecksum[11] = "abandon"158 #expect(throws: RecoverySheetError.invalidMnemonic) { _ = try RecoverySheet.make(mnemonic: wrongChecksum) }159 #expect(throws: RecoverySheetError.invalidMnemonic) { _ = try RecoverySheet.make(mnemonic: Array(abandon.dropLast())) }160 #expect(throws: RecoverySheetError.invalidMnemonic) { _ = try RecoverySheet.make(mnemonic: ["hello", "world"]) }161 #expect(throws: RecoverySheetError.invalidMnemonic) { _ = try RecoverySheet.make(mnemonic: []) }162 }163}164165/// Signature double for the format tests (Ed25519 from CryptoKit). The production signer is166/// `IdentityDetachedSigner` in QyvoraIdentity, tested in that module.167struct TestSigner: DetachedSigner {168 let key = Curve25519.Signing.PrivateKey()169 var signerEncoding: Bytes { Bytes(key.publicKey.rawRepresentation) }170171 func detachedSignature(over message: Bytes, purpose: String) throws -> Bytes {172 Bytes(try key.signature(for: Data(Bytes(purpose.utf8) + [0] + message)))173 }174}175176struct TestVerifier: DetachedVerifier {177 func isValid(signature: Bytes, over message: Bytes, signerEncoding: Bytes, purpose: String) -> Bool {178 guard let key = try? Curve25519.Signing.PublicKey(rawRepresentation: Data(signerEncoding)) else { return false }179 return key.isValidSignature(Data(signature), for: Data(Bytes(purpose.utf8) + [0] + message))180 }181182 func signerFingerprint(of signerEncoding: Bytes) -> Bytes? {183 signerEncoding.count == 32 ? Bytes(CryptoKit.SHA256.hash(data: signerEncoding)) : nil184 }185}186187func fixedChecksum(_ bytes: Bytes) -> Bytes {188 let body = Bytes(bytes[0..<(bytes.count - 32)])189 return body + Bytes(CryptoKit.SHA256.hash(data: body))190}191192func sampleRecords() -> [VaultRecord] {193 let t = Date(timeIntervalSince1970: 1_800_000_000)194 return [195 VaultRecord(id: UUID(), type: .recoveryPhrase, createdAt: t, updatedAt: t.addingTimeInterval(5), payload: Bytes("zoo zoo zoo wrong".utf8)),196 VaultRecord(id: UUID(), type: .watchOnlyAccount, createdAt: t.addingTimeInterval(10), updatedAt: t.addingTimeInterval(10), payload: []),197 VaultRecord(id: UUID(), type: .custom, createdAt: t.addingTimeInterval(20), updatedAt: t.addingTimeInterval(30), payload: SystemRandom.bytes(300)),198 ]199}200201let testVaultID = Bytes((0..<16).map { UInt8($0) })202203@Suite struct BackupFileTests {204 static let records = sampleRecords()205 static let created = Date(timeIntervalSince1970: 1_800_000_500)206 static let backup = try! BackupFile.create(207 records: records, vaultID: testVaultID, password: "backup password", kdf: .insecureForTesting, createdAt: created)208 static let signer = TestSigner()209 static let signedBackup = try! BackupFile.create(210 records: records, vaultID: testVaultID, password: "backup password", kdf: .insecureForTesting, signer: signer, createdAt: created)211212 func expectBackupError(_ expected: BackupError, sourceLocation: SourceLocation = #_sourceLocation, _ body: () throws -> Void) {213 #expect(throws: expected, sourceLocation: sourceLocation) { try body() }214 }215216 @Test func roundTrip() throws {217 let contents = try BackupFile.open(Self.backup, password: "backup password")218 #expect(contents.records == Self.records)219 #expect(!contents.signatureVerified)220 #expect(contents.header == (try BackupFile.inspect(Self.backup)))221 let header = contents.header222 #expect(header.formatVersion == 1 && header.createdAt == Self.created && header.vaultID == testVaultID)223 #expect(header.kdf == .insecureForTesting && header.recordCount == 3 && !header.isSigned)224225 // two backups of the same data share no salt, nonce or ciphertext226 let again = try BackupFile.create(records: Self.records, vaultID: testVaultID, password: "backup password", kdf: .insecureForTesting, createdAt: Self.created)227 #expect(again.count == Self.backup.count)228 #expect(Bytes(again[54..<86]) != Bytes(Self.backup[54..<86]))229 #expect(Bytes(again[98...]) != Bytes(Self.backup[98...]))230231 let empty = try BackupFile.create(records: [], vaultID: testVaultID, password: "p", kdf: .insecureForTesting)232 #expect(try BackupFile.open(empty, password: "p").records.isEmpty)233 }234235 @Test func layoutMatchesTheDocumentedFormat() throws {236 let b = Self.backup237 #expect(Bytes(b[0..<8]) == Bytes("QYVORABK".utf8))238 #expect(Bytes(b[8..<10]) == [0, 1])239 var r = ByteReader(Bytes(b[10...]))240 var header = ByteReader(try r.prefixed32(max: 1000))241 #expect(header.remaining == 8 + 16 + 16 + 16 + 16 + 4 + 4)242 #expect(try header.u64() == 1_800_000_500)243 #expect(try header.raw(16) == testVaultID)244 #expect(try KDFParameters(from: &header) == .insecureForTesting)245 let argon2Salt = try header.raw(16), pbkdf2Salt = try header.raw(16)246 #expect(try header.u32() == 3)247 #expect(try header.u32() == 0)248 let nonce = try r.raw(12)249 let sealed = try r.prefixed32(max: 10_000)250 #expect(try r.u32() == 0)251 #expect(r.remaining == 32)252 #expect(Bytes(b[(b.count - 32)...]) == Bytes(CryptoKit.SHA256.hash(data: b[0..<(b.count - 32)])))253254 // decrypt independently from the documented key schedule255 let key = try KeyStretching.deriveKey(256 secret: Bytes("backup password".utf8), argon2Salt: argon2Salt, pbkdf2Salt: pbkdf2Salt, parameters: .insecureForTesting, info: "qyvora/v1/backup")257 let plain = try EngineAEAD().open(key: key, nonce: nonce, sealed: sealed, associatedData: Bytes(b[0..<94]))258 var p = ByteReader(plain)259 #expect(try p.u32() == 3)260 for record in Self.records {261 let start = p.offset262 #expect(try p.raw(16) == record.id.bytes16)263 #expect(try p.u8() == record.type.rawValue)264 #expect(try p.u64() == UInt64(record.createdAt.timeIntervalSince1970))265 #expect(try p.u64() == UInt64(record.updatedAt.timeIntervalSince1970))266 #expect(try p.prefixed32(max: 1000) == record.payload)267 let digest = Bytes(CryptoKit.SHA256.hash(data: plain[start..<p.offset]))268 #expect(try p.raw(32) == digest)269 }270 #expect(p.remaining == 0)271 }272273 @Test func wrongPasswordAndParameters() throws {274 expectBackupError(.authenticationFailed) { _ = try BackupFile.open(Self.backup, password: "Backup password") }275 expectBackupError(.authenticationFailed) { _ = try BackupFile.open(Self.backup, password: "backup password ") }276 expectBackupError(.invalidParameters) { _ = try BackupFile.open(Self.backup, password: "") }277 expectBackupError(.invalidParameters) { _ = try BackupFile.create(records: [], vaultID: testVaultID, password: "", kdf: .insecureForTesting) }278 expectBackupError(.invalidParameters) { _ = try BackupFile.create(records: [], vaultID: [1, 2], password: "p", kdf: .insecureForTesting) }279 let bad = KDFParameters(argon2MemoryKiB: 1, argon2Iterations: 1, argon2Parallelism: 1, pbkdf2Iterations: 1)280 expectBackupError(.invalidParameters) { _ = try BackupFile.create(records: [], vaultID: testVaultID, password: "p", kdf: bad) }281 }282283 @Test func everySingleByteCorruptionIsDetected() throws {284 for backup in [Self.backup, Self.signedBackup] {285 for i in 0..<backup.count {286 var bad = backup287 bad[i] ^= UInt8(1) << UInt8(i % 8)288 do {289 _ = try BackupFile.open(bad, password: "backup password", verifier: TestVerifier())290 Issue.record("corruption at offset \(i) was accepted")291 } catch {292 if i < 8 {293 #expect(error == .badMagic)294 } else if i >= 10 {295 #expect(error == .checksumMismatch)296 } else if case .unsupportedVersion = error {297 } else {298 Issue.record("offset \(i): \(error)")299 }300 }301 #expect(throws: BackupError.self) { _ = try BackupFile.inspect(bad) }302 }303 }304 }305306 @Test func truncationGarbageAndVersion() throws {307 let b = Self.backup308 for cut in [0, 1, 8, 9, 10, 13, 50, 94, 106, b.count / 2, b.count - 33, b.count - 32, b.count - 1] {309 #expect(throws: BackupError.self, "cut \(cut)") { _ = try BackupFile.open(Bytes(b[0..<cut]), password: "backup password") }310 // a truncated file whose checksum was recomputed is still refused by the structure or the AEAD311 if cut > 110 {312 #expect(throws: BackupError.self, "cut \(cut), checksum fixed") {313 _ = try BackupFile.open(fixedChecksum(Bytes(b[0..<cut])), password: "backup password")314 }315 }316 }317 expectBackupError(.truncated) { _ = try BackupFile.open([], password: "p") }318 expectBackupError(.truncated) { _ = try BackupFile.open(Bytes(b[0..<60]), password: "p") }319 expectBackupError(.badMagic) { _ = try BackupFile.open(SystemRandom.bytes(400), password: "p") }320 expectBackupError(.badMagic) { _ = try BackupFile.open(Bytes("QYVORAVF".utf8) + Bytes(b[8...]), password: "p") }321 var newer = b322 newer[9] = 2323 expectBackupError(.unsupportedVersion(2)) { _ = try BackupFile.open(fixedChecksum(newer), password: "backup password") }324 expectBackupError(.checksumMismatch) { _ = try BackupFile.open(b + [0], password: "backup password") }325 expectBackupError(.malformed) { _ = try BackupFile.open(fixedChecksum(b + Bytes(repeating: 0, count: 33)), password: "backup password") }326 }327328 @Test func tamperingWithARecomputedChecksumIsDetected() throws {329 // (offsets 38..<54 hold the KDF parameters: a flipped bit there can request gigabytes of Argon2 memory, so they330 // are exercised separately below)331 let b = Self.backup332 for i in 10..<(b.count - 32) where !(38..<54).contains(i) {333 var bad = b334 bad[i] ^= UInt8(1) << UInt8(i % 8)335 do {336 _ = try BackupFile.open(fixedChecksum(bad), password: "backup password")337 Issue.record("tampering at offset \(i) was accepted")338 } catch {339 switch error {340 case .authenticationFailed, .malformed, .truncated: break341 default: Issue.record("offset \(i): unexpected \(error)")342 }343 }344 }345 // weaker or different KDF parameters: another key, so authentication fails346 var weaker = b347 weaker[53] = 1 // pbkdf2Iterations 8 → 1348 expectBackupError(.authenticationFailed) { _ = try BackupFile.open(fixedChecksum(weaker), password: "backup password") }349 var other = b350 other[45] = 2 // argon2Iterations 1 → 2351 expectBackupError(.authenticationFailed) { _ = try BackupFile.open(fixedChecksum(other), password: "backup password") }352 var outOfRange = b353 outOfRange[38] = 0xff // 4 TiB of Argon2 memory354 expectBackupError(.malformed) { _ = try BackupFile.open(fixedChecksum(outOfRange), password: "backup password") }355 // header fields are authenticated: creation time, vault id, record count356 for offset in [14, 21, 22, 37, 89] {357 var changed = b358 changed[offset] ^= 0x01359 expectBackupError(.authenticationFailed) { _ = try BackupFile.open(fixedChecksum(changed), password: "backup password") }360 }361 }362363 @Test func everyRecordIsIntegrityChecked() throws {364 // a backup written by a faulty or hostile tool that knows the password: valid encryption, wrong record digest365 func forge(_ mutate: (inout Bytes) -> Void) throws -> Bytes {366 let record = Self.records[0]367 var body = ByteWriter()368 body.raw(record.id.bytes16)369 body.u8(record.type.rawValue)370 body.u64(1_800_000_000)371 body.u64(1_800_000_005)372 body.prefixed32(record.payload)373 var plain = ByteWriter()374 plain.u32(1)375 plain.raw(body.bytes)376 plain.raw(Bytes(CryptoKit.SHA256.hash(data: body.bytes)))377 var plaintext = plain.bytes378 mutate(&plaintext)379380 let s1 = SystemRandom.bytes(16), s2 = SystemRandom.bytes(16), nonce = SystemRandom.bytes(12)381 var header = ByteWriter()382 header.u64(1)383 header.raw(testVaultID)384 KDFParameters.insecureForTesting.encode(into: &header)385 header.raw(s1)386 header.raw(s2)387 header.u32(1)388 header.u32(0)389 var out = ByteWriter()390 out.raw(Bytes("QYVORABK".utf8))391 out.u16(1)392 out.prefixed32(header.bytes)393 let key = try KeyStretching.deriveKey(secret: Bytes("pw".utf8), argon2Salt: s1, pbkdf2Salt: s2, parameters: .insecureForTesting, info: "qyvora/v1/backup")394 let sealed = try SystemAEAD().seal(key: key, nonce: nonce, plaintext: plaintext, associatedData: out.bytes)395 out.raw(nonce)396 out.prefixed32(sealed)397 out.u32(0)398 out.raw(Bytes(CryptoKit.SHA256.hash(data: out.bytes)))399 return out.bytes400 }401402 // the independent writer produces a file the reader accepts403 #expect(try BackupFile.open(try forge { _ in }, password: "pw").records.first?.payload == Self.records[0].payload)404 expectBackupError(.recordIntegrity) { _ = try BackupFile.open(try forge { $0[$0.count - 1] ^= 1 }, password: "pw") }405 expectBackupError(.recordIntegrity) { _ = try BackupFile.open(try forge { $0[45] ^= 1 }, password: "pw") } // payload byte406 expectBackupError(.recordIntegrity) { _ = try BackupFile.open(try forge { $0[4] ^= 1 }, password: "pw") } // record id407 expectBackupError(.malformed) { _ = try BackupFile.open(try forge { $0[3] = 2 }, password: "pw") } // count ≠ header408 expectBackupError(.malformed) { _ = try BackupFile.open(try forge { $0 += [0] }, password: "pw") } // trailing byte409 expectBackupError(.malformed) { _ = try BackupFile.open(try forge { $0 = Bytes($0.dropLast()) }, password: "pw") }410 }411412 @Test func signedBackup() throws {413 let b = Self.signedBackup414 let fingerprint = try #require(TestVerifier().signerFingerprint(of: Self.signer.signerEncoding))415 let header = try BackupFile.inspect(b)416 #expect(header.isSigned && header.signerEncoding == Self.signer.signerEncoding)417418 let contents = try BackupFile.open(b, password: "backup password", verifier: TestVerifier(), expectedSignerFingerprint: fingerprint, requireSignature: true)419 #expect(contents.signatureVerified && contents.records == Self.records)420421 // a signature is never silently skipped422 expectBackupError(.signatureRequired) { _ = try BackupFile.open(b, password: "backup password") }423 // unsigned backups are refused on request424 expectBackupError(.signatureRequired) { _ = try BackupFile.open(Self.backup, password: "backup password", verifier: TestVerifier(), requireSignature: true) }425 expectBackupError(.signatureRequired) { _ = try BackupFile.open(Self.backup, password: "backup password", verifier: TestVerifier(), expectedSignerFingerprint: fingerprint) }426 // signed by someone else427 expectBackupError(.unexpectedSigner) {428 _ = try BackupFile.open(b, password: "backup password", verifier: TestVerifier(), expectedSignerFingerprint: Bytes(repeating: 7, count: 32))429 }430 // the signature is checked before the password431 expectBackupError(.authenticationFailed) { _ = try BackupFile.open(b, password: "wrong", verifier: TestVerifier()) }432433 // any modification with a recomputed checksum breaks the signature (or the structure)434 for i in stride(from: 10, to: b.count - 32, by: 3) where !(38..<54).contains(i) {435 var bad = b436 bad[i] ^= 0x20437 do {438 _ = try BackupFile.open(fixedChecksum(bad), password: "backup password", verifier: TestVerifier())439 Issue.record("tampering at offset \(i) was accepted")440 } catch {441 switch error {442 case .invalidSignature, .malformed, .truncated: break443 default: Issue.record("offset \(i): unexpected \(error)")444 }445 }446 }447448 // replacing the signer and re-signing gives a valid signature by the attacker, who still lacks the password:449 // the signer is part of the associated data450 let mallory = TestSigner()451 var forged = Bytes(b[0..<94]) + mallory.signerEncoding + Bytes(b[126..<(b.count - 32 - 64 - 4)])452 forged += [0, 0, 0, 64] + (try mallory.detachedSignature(over: forged, purpose: "backup"))453 forged += Bytes(CryptoKit.SHA256.hash(data: forged))454 #expect(try BackupFile.inspect(forged).signerEncoding == mallory.signerEncoding)455 expectBackupError(.authenticationFailed) { _ = try BackupFile.open(forged, password: "backup password", verifier: TestVerifier()) }456 expectBackupError(.unexpectedSigner) {457 _ = try BackupFile.open(forged, password: "backup password", verifier: TestVerifier(), expectedSignerFingerprint: fingerprint)458 }459460 // stripping the signature changes the header, which is authenticated461 var stripped = Bytes(b[0..<10]) + [0, 0, 0, 80] + Bytes(b[14..<90]) + [0, 0, 0, 0] + Bytes(b[126..<(b.count - 32 - 64 - 4)]) + [0, 0, 0, 0]462 stripped += Bytes(CryptoKit.SHA256.hash(data: stripped))463 #expect(try !BackupFile.inspect(stripped).isSigned)464 expectBackupError(.authenticationFailed) { _ = try BackupFile.open(stripped, password: "backup password") }465 // signer without signature, or signature without signer466 var half = Bytes(b[0..<(b.count - 32 - 64 - 4)]) + [0, 0, 0, 0]467 half += Bytes(CryptoKit.SHA256.hash(data: half))468 expectBackupError(.malformed) { _ = try BackupFile.open(half, password: "backup password", verifier: TestVerifier()) }469 }470471 @Test func exportFromAVaultAndRestoreIntoAFreshOne() async throws {472 let rootA = FileManager.default.temporaryDirectory.appendingPathComponent("qyvora-recovery-a-\(UUID().uuidString)", isDirectory: true)473 let rootB = FileManager.default.temporaryDirectory.appendingPathComponent("qyvora-recovery-b-\(UUID().uuidString)", isDirectory: true)474 defer {475 try? FileManager.default.removeItem(at: rootA)476 try? FileManager.default.removeItem(at: rootB)477 }478 let old = Vault(fileStore: try FileStore(root: rootA), keychain: InMemoryKeychainStore(), configuration: .init(kdf: .insecureForTesting))479 try await old.create(password: "old device password")480 var expected: [UUID: (RecordType, Bytes)] = [:]481 for (i, type) in RecordType.allCases.enumerated() {482 let payload = SystemRandom.bytes(i * 37)483 expected[try await old.addRecord(type: type, payload: payload)] = (type, payload)484 }485 let backup = try await BackupFile.export(from: old, password: "backup password", kdf: .insecureForTesting, signer: Self.signer)486 #expect(try BackupFile.inspect(backup).vaultID == (try await old.vaultID()))487 #expect(try BackupFile.inspect(backup).recordCount == 6)488489 await old.lock()490 do {491 _ = try await BackupFile.export(from: old, password: "backup password", kdf: .insecureForTesting)492 Issue.record("a locked vault cannot be exported")493 } catch {494 #expect(error == .vault(.locked))495 }496497 // the new device: a fresh vault with its own password498 let fresh = Vault(fileStore: try FileStore(root: rootB), keychain: InMemoryKeychainStore(), configuration: .init(kdf: .insecureForTesting))499 try await fresh.create(password: "new device password")500 do {501 _ = try await BackupFile.restore(backup, password: "not the password", into: fresh, verifier: TestVerifier())502 Issue.record("wrong backup password accepted")503 } catch {504 #expect(error == .authenticationFailed)505 }506 #expect(try await fresh.records().isEmpty)507508 let restored = try await BackupFile.restore(backup, password: "backup password", into: fresh, verifier: TestVerifier(), requireSignature: true)509 #expect(restored.signatureVerified && restored.records.count == 6)510 let records = try await fresh.records()511 #expect(records.count == 6)512 for record in records {513 let (type, payload) = try #require(expected[record.id])514 #expect(record.type == type && record.payload == payload)515 }516 try await old.unlock(password: "old device password")517 #expect(try await fresh.recordSummaries().map(\.createdAt) == (try await old.recordSummaries().map(\.createdAt)))518 #expect(try await fresh.vaultID() != (try await old.vaultID()))519 #expect(try await fresh.verifyIntegrity().recordsVerified == 6)520521 // the restored vault survives a lock / unlock cycle with its own password522 await fresh.lock()523 try await fresh.unlock(password: "new device password")524 #expect(try await fresh.records().count == 6)525526 // restoring twice would duplicate identifiers: refused, nothing added527 do {528 _ = try await BackupFile.restore(backup, password: "backup password", into: fresh, verifier: TestVerifier())529 Issue.record("duplicate restore accepted")530 } catch {531 #expect(error == .vault(.invalidParameters))532 }533 await fresh.lock()534 do {535 _ = try await BackupFile.restore(backup, password: "backup password", into: fresh, verifier: TestVerifier())536 Issue.record("restore into a locked vault accepted")537 } catch {538 #expect(error == .vault(.locked))539 }540 }541}542543@Suite struct QRChunkTests {544 @Test func splitAndReassemble() throws {545 for (size, chunk) in [(1, 600), (599, 600), (600, 600), (601, 600), (4278, 600), (10_000, 333), (50, 16), (5000, 2048)] {546 let payload = SystemRandom.bytes(size)547 let frames = try QRChunker.split(payload, chunkSize: chunk)548 #expect(frames.count == (size + chunk - 1) / chunk)549 #expect(try QRAssembler.assemble(frames) == payload)550 #expect(try QRAssembler.assemble(frames.reversed()) == payload)551 #expect(try QRAssembler.assemble(frames.shuffled() + frames.shuffled()) == payload)552 for frame in frames {553 #expect(frame.wholeMatch(of: /qyv1:[1-9][0-9]{0,3}\/[1-9][0-9]{0,3}:[0-9a-f]{16}:[A-Za-z0-9_-]+/) != nil)554 #expect(frame.utf8.count <= 5 + 9 + 1 + 16 + 1 + (chunk * 4 + 2) / 3)555 }556 }557 #expect(try QRChunker.split([0xff], chunkSize: 16) == ["qyv1:1/1:\(QRChunker.checksum(total: 1, payload: [0xff])):_w"])558 #expect(throws: QRChunkError.emptyPayload) { _ = try QRChunker.split([]) }559 #expect(throws: QRChunkError.invalidChunkSize) { _ = try QRChunker.split([1], chunkSize: 15) }560 #expect(throws: QRChunkError.invalidChunkSize) { _ = try QRChunker.split([1], chunkSize: 2049) }561 #expect(throws: QRChunkError.tooManyFrames) { _ = try QRChunker.split(Bytes(repeating: 0, count: 16 * 9999 + 1), chunkSize: 16) }562 #expect(try QRChunker.split(Bytes(repeating: 0, count: 16 * 9999), chunkSize: 16).count == 9999)563 }564565 @Test func progressDuplicatesAndMissingFrames() throws {566 let payload = SystemRandom.bytes(2000)567 let frames = try QRChunker.split(payload, chunkSize: 300)568 #expect(frames.count == 7)569 var assembler = QRAssembler()570 #expect(assembler.total == nil && !assembler.isComplete && assembler.missingIndices.isEmpty)571 #expect(throws: QRChunkError.incomplete(missing: [])) { _ = try assembler.assemble() }572 #expect(try assembler.add(frames[4]))573 #expect(assembler.total == 7 && assembler.receivedCount == 1)574 #expect(try !assembler.add(frames[4]))575 #expect(assembler.receivedCount == 1)576 #expect(try assembler.add(frames[0]))577 #expect(try assembler.add(frames[6]))578 #expect(assembler.missingIndices == [2, 3, 4, 6])579 #expect(throws: QRChunkError.incomplete(missing: [2, 3, 4, 6])) { _ = try assembler.assemble() }580 for i in [1, 2, 3, 5, 5, 1] { try assembler.add(frames[i]) }581 #expect(assembler.isComplete && assembler.missingIndices.isEmpty)582 #expect(try assembler.assemble() == payload)583 }584585 @Test func mixedSetsAndConflictsAreRejected() throws {586 let a = try QRChunker.split(SystemRandom.bytes(1000), chunkSize: 300)587 let b = try QRChunker.split(SystemRandom.bytes(1000), chunkSize: 300)588 let c = try QRChunker.split(SystemRandom.bytes(500), chunkSize: 300)589 var assembler = QRAssembler()590 try assembler.add(a[0])591 #expect(throws: QRChunkError.mixedSet) { try assembler.add(b[1]) } // same total, other payload592 #expect(throws: QRChunkError.mixedSet) { try assembler.add(c[1]) } // other total593 #expect(throws: QRChunkError.mixedSet) { _ = try QRAssembler.assemble([a[0], a[1], b[2], a[3]]) }594 #expect(assembler.receivedCount == 1)595596 // same set identifier, same index, different data597 let parts = a[0].split(separator: ":")598 let conflicting = "\(parts[0]):\(parts[1]):\(parts[2]):" + Base64URL.encode(SystemRandom.bytes(300))599 #expect(throws: QRChunkError.conflictingDuplicate) { try assembler.add(conflicting) }600601 // a frame altered in transit that still parses: caught by the final checksum602 var altered = QRAssembler()603 try altered.add(conflicting)604 for frame in a.dropFirst() { try altered.add(frame) }605 #expect(altered.isComplete)606 #expect(throws: QRChunkError.checksumMismatch) { _ = try altered.assemble() }607608 // the same bytes cut into a different number of frames form a different set609 let payload = SystemRandom.bytes(900)610 let three = try QRChunker.split(payload, chunkSize: 300), two = try QRChunker.split(payload, chunkSize: 450)611 #expect(throws: QRChunkError.mixedSet) { _ = try QRAssembler.assemble([three[0], two[1]]) }612 }613614 @Test func malformedFramesAreRejected() throws {615 let good = try QRChunker.split(SystemRandom.bytes(100), chunkSize: 64)[0]616 let p = good.split(separator: ":").map(String.init)617 let bad = [618 "", "qyv1", "qyv1:", good + ":", ":" + good, " " + good, good + "\n", good + "=",619 "qyv2:\(p[1]):\(p[2]):\(p[3])", "QYV1:\(p[1]):\(p[2]):\(p[3])",620 "qyv1:0/2:\(p[2]):\(p[3])", "qyv1:3/2:\(p[2]):\(p[3])", "qyv1:01/2:\(p[2]):\(p[3])", "qyv1:1/02:\(p[2]):\(p[3])",621 "qyv1:+1/2:\(p[2]):\(p[3])", "qyv1:1/10000:\(p[2]):\(p[3])", "qyv1:1:\(p[2]):\(p[3])", "qyv1:1/2/3:\(p[2]):\(p[3])",622 "qyv1:١/2:\(p[2]):\(p[3])", "qyv1:1/2:\(p[2].uppercased()):\(p[3])", "qyv1:1/2:\(p[2].dropLast()):\(p[3])",623 "qyv1:1/2:\(p[2])0:\(p[3])", "qyv1:1/2:\(p[2]):", "qyv1:1/2:\(p[2]):\(p[3])+", "qyv1:1/2:\(p[2]):A",624 "qyv1:1/2:\(p[2]):" + Base64URL.encode(Bytes(repeating: 0, count: 2049)),625 ]626 for frame in bad {627 var assembler = QRAssembler()628 #expect(throws: QRChunkError.malformedFrame, "\(frame.prefix(40))") { try assembler.add(frame) }629 #expect(assembler.receivedCount == 0 && assembler.total == nil)630 }631 var assembler = QRAssembler()632 #expect(try assembler.add(good))633 }634635 /// The chain identifier of an account of another chain is additive: a sheet written without it still decodes,636 /// and one written with it carries it through JSON.637 @Test func aChainAccountCarriesItsRegistryIdentifierAndOlderSheetsStillDecode() throws {638 let account = RecoverySheet.ChainAccount(chain: "Solana", networks: "every cluster", derivationPath: "m/44'/501'/0'/0'", scheme: "SLIP-0010 Ed25519",639 address: "HAgk14JpMQLgt6rVgv7cBQFJWFto5Dqxi472uT3DKpqk", chainID: "solana")640 let encoded = try JSONEncoder().encode(account)641 let decoded = try JSONDecoder().decode(RecoverySheet.ChainAccount.self, from: encoded)642 #expect(decoded == account && decoded.chainID == "solana" && decoded.chain == "Solana")643 // the form written before the field existed644 let older = Data(#"{"chain":"TRON","networks":"mainnet, Nile and Shasta: the same address","derivationPath":"m/44'/195'/0'/0/0","scheme":"BIP-32 secp256k1","address":"TUEZSdKsoDHQMeZwihtdoBiN46zxhGWYdH"}"#.utf8)645 let legacy = try JSONDecoder().decode(RecoverySheet.ChainAccount.self, from: older)646 #expect(legacy.chainID == nil && legacy.chain == "TRON" && legacy.address == "TUEZSdKsoDHQMeZwihtdoBiN46zxhGWYdH" && legacy.note == nil)647 // an account made without identifier has none, and does not write the key648 let plain = RecoverySheet.ChainAccount(chain: "TRON", networks: "x", derivationPath: "m/44'/195'/0'/0/0", scheme: "BIP-32 secp256k1", address: nil)649 let plainJSON = String(decoding: try JSONEncoder().encode(plain), as: UTF8.self)650 #expect(plain.chainID == nil && !plainJSON.contains("chainID"))651 // a whole sheet with such accounts survives JSON652 let sheet = try RecoverySheet.make(mnemonic: BIP39.words(from: "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about"),653 extraAccounts: { _, _ in [account, plain] })654 let copy = try JSONDecoder().decode(RecoverySheet.self, from: try JSONEncoder().encode(sheet))655 #expect(copy.otherChains.map(\.chainID) == ["solana", nil] && copy.otherChains == sheet.otherChains)656 }657}658