SPB Git

Repository Public

AuditRegressionTests.swift 8.4 KB 157 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Tests/QyvoraCoreTests/AuditRegressionTests.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 QyvoraMath44@testable import QyvoraCore4546/// Regression tests of the security audit (findings QYV-SVC-006 and QYV-SVC-015).47@Suite struct CoreAuditRegressionTests {48    /// QYV-SVC-006. A negative `decimals` used to trap in `String(repeating:count:)` / `dropLast`, and a huge one49    /// allocated as many zeros. Both are now handled without trap or allocation.50    @Test func baseUnitsToleratesHostileDecimals() {51        #expect(BaseUnits.parse("1.5", decimals: -1) == nil)52        #expect(BaseUnits.parse("1", decimals: Int.min) == nil)53        #expect(BaseUnits.parse("1", decimals: Int.max) == nil)54        #expect(BaseUnits.parse("1", decimals: 256) == nil)55        #expect(BaseUnits.parse(String(repeating: "9", count: 600), decimals: 18) == nil)56        // unchanged behaviour inside the range57        #expect(BaseUnits.parse("1.5", decimals: 18) == UInt256(1_500_000_000_000_000_000))58        #expect(BaseUnits.parse("0.00000001", decimals: 8) == UInt256(1))59        #expect(BaseUnits.parse("1", decimals: 0) == UInt256(1))60        #expect(BaseUnits.parse("1", decimals: 77) != nil)61        #expect(BaseUnits.parse("1", decimals: 78) == nil)  // overflow of 256 bits, reported as nil6263        let v = UInt256(123_456_789)64        #expect(BaseUnits.format(v, decimals: -1) == "123456789")65        #expect(BaseUnits.format(v, decimals: Int.min) == "123456789")66        #expect(BaseUnits.format(v, decimals: 8) == "1.23456789")67        #expect(BaseUnits.format(v, decimals: 8, maxFractionDigits: -3) == "1")68        #expect(BaseUnits.format(v, decimals: 8, maxFractionDigits: 2) == "1.23")69        // clamped to 255 decimals: a bounded string, not an allocation of Int.max characters70        let clamped = BaseUnits.format(v, decimals: Int.max)71        #expect(clamped.hasPrefix("0.") && clamped.count == 2 + BaseUnits.maximumDecimals)72        #expect(clamped == BaseUnits.format(v, decimals: BaseUnits.maximumDecimals))73    }7475    /// QYV-SVC-015. Base58 decoding is quadratic: text far longer than an extended key is refused before decoding.76    @Test func oversizedExtendedKeyTextIsRefusedWithoutDecoding() throws {77        let seed = Bytes((0..<32).map { UInt8($0) })78        let master = try ExtendedKey.master(seed: seed)79        let xpub = try master.neutered.serialized(.xpub)80        #expect(xpub.utf8.count == 111)81        #expect((try? ExtendedKey.parse(xpub)) != nil)8283        let huge = String(repeating: "1", count: 2_000_000)84        let clock = ContinuousClock()85        let elapsed = clock.measure {86            #expect(throws: ExtendedKey.Error.invalidEncoding) { _ = try ExtendedKey.parse(huge) }87            #expect(throws: ExtendedKey.Error.invalidEncoding) { _ = try ExtendedKey.parse(xpub + xpub) }88        }89        // the quadratic decoder would need minutes for two million characters90        #expect(elapsed < .seconds(2))91    }92}9394/// Regression tests of QYV-CRY-003 (key material the service could not erase): the seed is computed from bytes, and95/// an extended key erases its secrets in place.96struct KeyMaterialHygieneTests {97    static let about12 = ["abandon", "abandon", "abandon", "abandon", "abandon", "abandon", "abandon", "abandon", "abandon", "abandon", "abandon", "about"]9899    @Test func theSeedFromBytesIsTheSeedFromWords() throws {100        let stored = Bytes(Self.about12.joined(separator: " ").utf8)101        // official BIP-39 vector102        #expect(BIP39.seed(normalizedMnemonic: stored, normalizedPassphrase: Bytes("TREZOR".utf8)).hex103            == "c55257c360c07c72029aebc1b53c05ed0362ada38ead3e3e9efa3708e53495531f09a6987599d18264c1e1c92f2cf141630c7a3c4ab7c81b2f001698e7463b04")104        for passphrase in ["", "TREZOR", "pässwörd ①", "\u{212b}ngstr\u{00f6}m \u{fb01}"] {105            let normalized = Bytes(passphrase.decomposedStringWithCompatibilityMapping.utf8)106            #expect(BIP39.seed(normalizedMnemonic: stored, normalizedPassphrase: normalized) == (try BIP39.seed(mnemonic: Self.about12, passphrase: passphrase)))107        }108        #expect(BIP39.seed(normalizedMnemonic: stored) == (try BIP39.seed(mnemonic: Self.about12)))109        for count in [15, 18, 21, 24] {110            let words = try BIP39.generate(wordCount: count)111            #expect(BIP39.seed(normalizedMnemonic: Bytes(words.joined(separator: " ").utf8)) == (try BIP39.seed(mnemonic: words)))112        }113    }114115    @Test func wipeErasesThePrivateKeyAndTheChainCodeWhereTheyAre() throws {116        var key = try ExtendedKey.master(seed: Bytes(repeating: 0x5a, count: 32)).derive(DerivationPath("m/84'/1'/0'")!)117        let publicKey = key.publicKey118        #expect(key.privateKey?.contains { $0 != 0 } == true && key.chainCode.contains { $0 != 0 })119        // the addresses of the two buffers: erasing in place must not move them (a copy would be erased instead)120        let keyAddress = key.privateKey!.withUnsafeBytes { UInt(bitPattern: $0.baseAddress) }121        let chainAddress = key.chainCode.withUnsafeBytes { UInt(bitPattern: $0.baseAddress) }122        key.wipe()123        #expect(key.privateKey == Bytes(repeating: 0, count: 32))124        #expect(key.chainCode == Bytes(repeating: 0, count: 32))125        #expect(key.privateKey!.withUnsafeBytes { UInt(bitPattern: $0.baseAddress) } == keyAddress)126        #expect(key.chainCode.withUnsafeBytes { UInt(bitPattern: $0.baseAddress) } == chainAddress)127        // public data is untouched, and the erased key signs nothing128        #expect(key.publicKey == publicKey)129        #expect(throws: (any Error).self) { _ = try key.derive(.hardened(0)) }130        // a public-only key has nothing to erase but its chain code131        var neutered = try ExtendedKey.master(seed: Bytes(repeating: 0x5a, count: 32)).neutered132        neutered.wipe()133        #expect(neutered.privateKey == nil)134    }135136    /// Copy-on-write: a copy that is still alive keeps its bytes; the documentation of `wipe` says so, this pins it.137    @Test func wipeLeavesALiveCopyIntact() throws {138        var key = try ExtendedKey.master(seed: Bytes(repeating: 0x11, count: 32))139        let copy = key140        key.wipe()141        #expect(key.privateKey == Bytes(repeating: 0, count: 32))142        #expect(copy.privateKey?.contains { $0 != 0 } == true)143    }144145    @Test func derivationAlongAPathIsUnchangedByTheErasureOfItsIntermediates() throws {146        let master = try ExtendedKey.master(seed: Bytes((0..<64).map { UInt8($0) }))147        let path = DerivationPath("m/44'/60'/0'/0/7")!148        var step = master149        for c in path.indices { step = try step.derive(c) }150        let direct = try master.derive(path)151        #expect(direct.privateKey == step.privateKey && direct.chainCode == step.chainCode && direct.publicKey == step.publicKey)152        // the starting key is not erased by a derivation from it153        #expect(master.privateKey?.contains { $0 != 0 } == true)154        #expect(try master.derive(DerivationPath([])).privateKey == master.privateKey)155    }156}157
Files main
Menu

Theme