SPB Git

Repository Public

StorageTests.swift 10.0 KB 249 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Tests/QyvoraStorageTests/StorageTests.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 Testing4445@testable import QyvoraStorage4647func temporaryStore() throws -> FileStore {48    let root = FileManager.default.temporaryDirectory.appendingPathComponent("qyvora-storage-\(UUID().uuidString)", isDirectory: true)49    return try FileStore(root: root)50}5152@Suite struct FileStoreTests {53    @Test func writeReadAndPreviousGeneration() throws {54        let store = try temporaryStore()55        defer { try? FileManager.default.removeItem(at: store.root) }56        #expect(!store.exists("a.bin"))57        #expect(throws: StorageError.notFound) { _ = try store.read("a.bin") }5859        try store.write([1, 2, 3], to: "a.bin")60        #expect(try store.read("a.bin") == [1, 2, 3])61        #expect(!store.previousExists("a.bin"))6263        try store.write([4, 5], to: "a.bin")64        #expect(try store.read("a.bin") == [4, 5])65        #expect(try store.readPrevious("a.bin") == [1, 2, 3])6667        try store.write([6], to: "a.bin", keepPrevious: false)68        #expect(try store.read("a.bin") == [6])69        #expect(try store.readPrevious("a.bin") == [1, 2, 3])7071        try store.write([7], to: "a.bin")72        #expect(try store.readPrevious("a.bin") == [6])73    }7475    @Test func noTemporaryFileIsLeftBehind() throws {76        let store = try temporaryStore()77        defer { try? FileManager.default.removeItem(at: store.root) }78        for i in 0..<5 { try store.write(Bytes(repeating: UInt8(i), count: 100), to: "v") }79        let names = try FileManager.default.contentsOfDirectory(atPath: store.root.path).sorted()80        #expect(names == ["v", "v.previous"])81    }8283    @Test func removeDeletesBothGenerations() throws {84        let store = try temporaryStore()85        defer { try? FileManager.default.removeItem(at: store.root) }86        try store.write([1], to: "x")87        try store.write([2], to: "x")88        try store.removePrevious("x")89        #expect(store.exists("x") && !store.previousExists("x"))90        try store.write([3], to: "x")91        try store.remove("x")92        #expect(!store.exists("x") && !store.previousExists("x"))93        try store.remove("x")94    }9596    @Test func invalidNamesAreRejected() throws {97        let store = try temporaryStore()98        defer { try? FileManager.default.removeItem(at: store.root) }99        for name in ["", "a/b", "..", ".", "../escape"] {100            #expect(throws: StorageError.invalidName) { try store.write([1], to: name) }101        }102    }103104    @Test func directoryIsExcludedFromBackup() throws {105        let store = try temporaryStore()106        defer { try? FileManager.default.removeItem(at: store.root) }107        try store.write([1], to: "f")108        let values = try store.url(for: "f").resourceValues(forKeys: [.isExcludedFromBackupKey])109        #expect(values.isExcludedFromBackup == true)110    }111}112113@Suite struct SettingsStoreTests {114    struct Settings: Codable, Equatable {115        var network: String116        var autoLockSeconds: Int117    }118119    @Test func roundTripAndCorruption() throws {120        let files = try temporaryStore()121        defer { try? FileManager.default.removeItem(at: files.root) }122        let store = SettingsStore(fileStore: files)123        #expect(try store.load(Settings.self) == nil)124        let value = Settings(network: "testnet", autoLockSeconds: 60)125        try store.save(value)126        #expect(try store.load(Settings.self) == value)127        try files.write(Bytes("{not json".utf8), to: "settings.json")128        #expect(throws: StorageError.invalidData) { _ = try store.load(Settings.self) }129        try store.remove()130        #expect(try store.load(Settings.self) == nil)131    }132}133134@Suite struct KeychainDoubleTests {135    @Test func setGetDeleteAndBiometry() throws {136        let keychain = InMemoryKeychainStore()137        #expect(throws: StorageError.notFound) { _ = try keychain.get(account: "k", prompt: nil) }138        try keychain.set([9, 9], account: "k", access: .passcodeSetThisDeviceOnly)139        try keychain.set([7], account: "bio", access: .biometryCurrentSet)140        #expect(try keychain.get(account: "k", prompt: nil) == [9, 9])141        #expect(try keychain.get(account: "bio", prompt: "unlock") == [7])142        #expect(keychain.accounts == ["bio", "k"])143144        keychain.setBiometryPasses(false)145        #expect(throws: StorageError.authenticationFailed) { _ = try keychain.get(account: "bio", prompt: "unlock") }146        #expect(try keychain.get(account: "k", prompt: nil) == [9, 9])147        #expect(keychain.contains(account: "bio"))148149        keychain.setBiometryPasses(true)150        keychain.invalidateBiometricItems()151        #expect(!keychain.contains(account: "bio"))152        try keychain.delete(account: "k")153        try keychain.delete(account: "k")154        #expect(keychain.accounts.isEmpty)155    }156}157158@Suite struct SecureEnclaveDoubleTests {159    @Test func wrapUnwrapRoundTrip() throws {160        let enclave = SoftwareEnclaveKey()161        let secret = SystemRandom.bytes(32)162        let a = try enclave.wrap(secret)163        let b = try enclave.wrap(secret)164        #expect(a != b)165        #expect(a.count == 1 + 65 + 12 + 32 + 16)166        #expect(try enclave.unwrap(a) == secret)167        #expect(try enclave.unwrap(b) == secret)168    }169170    @Test func everyCorruptedByteIsRejected() throws {171        let enclave = SoftwareEnclaveKey()172        let blob = try enclave.wrap(SystemRandom.bytes(32))173        for i in 0..<blob.count {174            var bad = blob175            bad[i] ^= 0x01176            #expect(throws: StorageError.invalidData) { _ = try enclave.unwrap(bad) }177        }178        #expect(throws: StorageError.invalidData) { _ = try enclave.unwrap(Bytes(blob.dropLast())) }179        #expect(throws: StorageError.invalidData) { _ = try enclave.unwrap([]) }180    }181182    @Test func anotherKeyCannotUnwrapAndDestroyIsFinal() throws {183        let a = SoftwareEnclaveKey(), b = SoftwareEnclaveKey()184        let blob = try a.wrap([1, 2, 3])185        #expect(throws: StorageError.invalidData) { _ = try b.unwrap(blob) }186        try a.destroy()187        #expect(throws: StorageError.notFound) { _ = try a.unwrap(blob) }188    }189190    @Test func unavailableEnclaveReportsIt() {191        let none = SoftwareEnclaveKey(available: false)192        #expect(!none.isAvailable)193        #expect(throws: StorageError.secureEnclaveUnavailable) { _ = try none.wrap([1]) }194        _ = SystemSecureEnclaveKey(keychain: InMemoryKeychainStore()).isAvailable195    }196}197198@Suite struct BinaryCodingTests {199    @Test func writerReaderRoundTrip() throws {200        var w = ByteWriter()201        w.u8(0xab)202        w.u16(0x1234)203        w.u32(0xdead_beef)204        w.u64(0x0102_0304_0506_0708)205        w.prefixed8([1, 2])206        w.prefixed16([3])207        w.prefixed32([4, 5, 6])208        w.raw([7])209        var r = ByteReader(w.bytes)210        #expect(try r.u8() == 0xab)211        #expect(try r.u16() == 0x1234)212        #expect(try r.u32() == 0xdead_beef)213        #expect(try r.u64() == 0x0102_0304_0506_0708)214        #expect(try r.prefixed8() == [1, 2])215        #expect(try r.prefixed16() == [3])216        #expect(try r.prefixed32(max: 10) == [4, 5, 6])217        #expect(throws: ByteReaderError.trailingBytes) { try r.finish() }218        #expect(try r.raw(1) == [7])219        try r.finish()220        #expect(throws: ByteReaderError.truncated) { _ = try r.u8() }221    }222223    @Test func lengthLimitsAndTruncation() {224        var r = ByteReader([0, 0, 0, 9, 1])225        #expect(throws: ByteReaderError.lengthOutOfRange) { _ = try r.prefixed32(max: 8) }226        var s = ByteReader([0, 0, 0, 9, 1])227        #expect(throws: ByteReaderError.truncated) { _ = try s.prefixed32(max: 100) }228        var t = ByteReader([0xff, 0xff, 0xff, 0xff])229        #expect(throws: ByteReaderError.lengthOutOfRange) { _ = try t.prefixed32(max: 1 << 20) }230    }231232    @Test func base64URL() {233        #expect(Base64URL.encode([]) == "")234        #expect(Base64URL.encode(Bytes("f".utf8)) == "Zg")235        #expect(Base64URL.encode(Bytes("fo".utf8)) == "Zm8")236        #expect(Base64URL.encode(Bytes("foobar".utf8)) == "Zm9vYmFy")237        #expect(Base64URL.encode([0xfb, 0xff]) == "-_8")238        for n in 0..<70 {239            let b = SystemRandom.bytes(n)240            #expect(Base64URL.decode(Base64URL.encode(b)) == b)241            #expect(Base64URL.encode(b) == Data(b).base64EncodedString()242                .replacingOccurrences(of: "+", with: "-").replacingOccurrences(of: "/", with: "_").replacingOccurrences(of: "=", with: ""))243        }244        for bad in ["Zg==", "Z", "Zh", "Zm9", "Zm+v", "Zm 8", "Zm8\n", "é"] {245            #expect(Base64URL.decode(bad) == nil, "\(bad)")246        }247    }248}249
Files main
Menu

Theme