Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : MacLustr Storage Node9// File : MacLustrStorageNodeTests/StorageEngineTests.swift10// Description : Unit tests of the MacLustr Mobile Storage Engine and of11// the protocol helpers: real files, real SQLite, real12// hashes.13// Module : MacLustrStorageNodeTests14// Repository : https://git.spboucher.ai/maclustr-storage-ios15// Project Website : https://storage.spboucher.ai16// Created : 2026-12-0117// Last Modified : 2026-12-0118//19// =============================================================================20// AUTHOR & PROFESSIONAL AFFILIATION21// =============================================================================22//23// Author : Simon-Pierre Boucher24// Position : Professor of Finance25// Institution : Université du Québec en Outaouais (UQO)26// Department : Département des sciences administratives27// Organization : SP Boucher28//29// Website : https://spboucher.ai30// Git : https://git.spboucher.ai31//32// =============================================================================33// OFFICIAL CONTACT DIRECTORY34// =============================================================================35//36// General : info@spboucher.ai37// Professional : contact@spboucher.ai38// Direct : simon@spboucher.ai39// Research : research@spboucher.ai40// Development : dev@spboucher.ai41// Support : support@spboucher.ai42// Security/Admin : admin@spboucher.ai43// Notifications : notifications@spboucher.ai44//45// Preferred Contact: admin@spboucher.ai46//47// =============================================================================48// COPYRIGHT & INTELLECTUAL PROPERTY49// =============================================================================50//51// Copyright (c) 202652// Simon-Pierre Boucher53//54// All rights reserved where applicable.55//56// This file is governed by the applicable project license,57// copyright notices, institutional agreements and relevant law.58//59// Unless expressly authorized by the applicable license or60// rights holder, copying, redistribution, sublicensing,61// publication and commercial exploitation are not permitted.62//63// Existing third-party rights and notices remain unaffected.64//65// =============================================================================66// CONFIDENTIALITY & SECURITY67// =============================================================================68//69// Classification : Public70// Distribution : Public repository; use is governed by the project license71// Security Contact : admin@spboucher.ai72//73// Access to this source does not independently grant permission74// to redistribute or disclose confidential materials.75//76// Do not embed credentials, private keys, access tokens,77// certificates or confidential personal information.78//79// =============================================================================80// LICENSE & MAINTENANCE81// =============================================================================82//83// License : None specified (no license file in this repository)84// Maintainer : Simon-Pierre Boucher85// Technical Contact: dev@spboucher.ai86//87// =============================================================================88// END OF SP BOUCHER SOURCE HEADER89// =============================================================================9091import XCTest92import CryptoKit93@testable import MacLustrStorageNode9495final class StorageEngineTests: XCTestCase {96 private var root: URL!9798 override func setUpWithError() throws {99 root = FileManager.default.temporaryDirectory.appendingPathComponent("mse-test-\(UUID().uuidString)", isDirectory: true)100 try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)101 }102 override func tearDownWithError() throws { try? FileManager.default.removeItem(at: root) }103104 private func random(_ n: Int) -> Data { var d = Data(count: n); _ = d.withUnsafeMutableBytes { SecRandomCopyBytes(kSecRandomDefault, n, $0.baseAddress!) }; return d }105 private func sha(_ d: Data) -> String { SHA256.hash(data: d).map { String(format: "%02x", $0) }.joined() }106 private func incoming(_ store: FragmentStore, _ data: Data, task: String = UUID().uuidString) throws -> URL {107 let url = store.incomingPath(task: task); try data.write(to: url); return url108 }109110 func testCommitStoresVerifiesAndDeduplicates() async throws {111 let store = try FragmentStore(root: root)112 let data = random(3 << 20), id = sha(data)113 try await store.commit(temp: try incoming(store, data), id: id, expectedSize: Int64(data.count))114 let held = await store.has(id); XCTAssertTrue(held)115 XCTAssertEqual(try Data(contentsOf: store.path(for: id)), data)116 // Same content again: accepted, nothing duplicated, temporary file removed.117 let again = try incoming(store, data)118 try await store.commit(temp: again, id: id, expectedSize: Int64(data.count))119 let usage = await store.usage()120 XCTAssertEqual(usage.count, 1); XCTAssertEqual(usage.bytes, Int64(data.count))121 XCTAssertFalse(FileManager.default.fileExists(atPath: again.path))122 }123124 func testCorruptArrivalIsRejectedAndLeavesNothing() async throws {125 let store = try FragmentStore(root: root)126 let data = random(1 << 20), id = sha(data)127 var bad = data; bad[100] ^= 0xFF128 let temp = try incoming(store, bad)129 do { try await store.commit(temp: temp, id: id, expectedSize: Int64(bad.count)); XCTFail("corrupt fragment accepted") }130 catch let e as FragmentStore.StoreError { XCTAssertEqual(e, .digestMismatch) }131 let held = await store.has(id); XCTAssertFalse(held)132 XCTAssertFalse(FileManager.default.fileExists(atPath: temp.path))133 do { try await store.commit(temp: try incoming(store, data), id: id, expectedSize: 5); XCTFail("wrong size accepted") }134 catch let e as FragmentStore.StoreError { XCTAssertEqual(e, .sizeMismatch) }135 }136137 func testPossessionProofMatchesCoordinatorFormula() async throws {138 let store = try FragmentStore(root: root)139 let data = random(2 << 20), id = sha(data)140 try await store.commit(temp: try incoming(store, data), id: id, expectedSize: Int64(data.count))141 let nonce = random(16), nonceHex = nonce.map { String(format: "%02x", $0) }.joined()142 let proof = try await store.proof(id: id, nonceHex: nonceHex)143 XCTAssertEqual(proof, sha(nonce + data)) // SHA-256(nonce ‖ fragment), as computed by the coordinator144 }145146 func testCorruptionAtRestIsFoundByScrubAndNeverReturned() async throws {147 let store = try FragmentStore(root: root)148 let a = random(1 << 20), b = random(1 << 20)149 try await store.commit(temp: try incoming(store, a), id: sha(a), expectedSize: Int64(a.count))150 try await store.commit(temp: try incoming(store, b), id: sha(b), expectedSize: Int64(b.count))151 let h = try FileHandle(forWritingTo: store.path(for: sha(a))); try h.seek(toOffset: 4096); try h.write(contentsOf: Data([1, 2, 3, 4])); try h.close()152 do { _ = try await store.verifiedFile(id: sha(a)); XCTFail("corrupt fragment returned") } catch let e as FragmentStore.StoreError { XCTAssertEqual(e, .digestMismatch) }153 let gone = await store.has(sha(a)); XCTAssertFalse(gone)154 let h2 = try FileHandle(forWritingTo: store.path(for: sha(b))); try h2.seek(toOffset: 10); try h2.write(contentsOf: Data([9])); try h2.close()155 let r = await store.scrub(maxBytes: 64 << 20)156 XCTAssertEqual(r.corrupt, [sha(b)])157 let left = await store.usage(); XCTAssertEqual(left.count, 0)158 }159160 func testRecoveryAfterInterruption() async throws {161 let a = random(1 << 20), b = random(1 << 20), c = random(1 << 20)162 do {163 let store = try FragmentStore(root: root)164 try await store.commit(temp: try incoming(store, a), id: sha(a), expectedSize: Int64(a.count))165 try await store.commit(temp: try incoming(store, b), id: sha(b), expectedSize: Int64(b.count))166 // Simulated crash states: an indexed fragment whose file vanished, a complete file never indexed,167 // a garbage file under a fragment name, a partial download nobody owns.168 try FileManager.default.removeItem(at: store.path(for: sha(a)))169 let dir = store.path(for: sha(c)).deletingLastPathComponent()170 try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)171 try c.write(to: store.path(for: sha(c)))172 let fake = String(repeating: "ab", count: 32)173 try FileManager.default.createDirectory(at: store.path(for: fake).deletingLastPathComponent(), withIntermediateDirectories: true)174 try Data("garbage".utf8).write(to: store.path(for: fake))175 try Data("partial".utf8).write(to: store.incomingPath(task: "dead-task"))176 try Data("partial".utf8).write(to: store.incomingPath(task: "live-task"))177 }178 let store = try FragmentStore(root: root) // "relaunch"179 let report = await store.recover(keepIncoming: ["live-task"])180 XCTAssertEqual(report.droppedRows, 1); XCTAssertEqual(report.adopted, 1); XCTAssertEqual(report.removedCorrupt, 1); XCTAssertEqual(report.clearedTemporary, 1)181 let ids = await store.ids()182 XCTAssertEqual(Set(ids), [sha(b), sha(c)])183 XCTAssertTrue(FileManager.default.fileExists(atPath: store.incomingPath(task: "live-task").path))184 let second = await store.recover(keepIncoming: ["live-task"])185 XCTAssertEqual(second, FragmentStore.RecoveryReport()) // idempotent186 }187188 func testDeleteAndWipe() async throws {189 let store = try FragmentStore(root: root)190 let a = random(1 << 19), b = random(1 << 19)191 try await store.commit(temp: try incoming(store, a), id: sha(a), expectedSize: Int64(a.count))192 try await store.commit(temp: try incoming(store, b), id: sha(b), expectedSize: Int64(b.count))193 await store.delete(sha(a))194 XCTAssertFalse(FileManager.default.fileExists(atPath: store.path(for: sha(a)).path))195 let freed = await store.wipe()196 XCTAssertEqual(freed, Int64(b.count))197 let u = await store.usage(); XCTAssertEqual(u.count, 0)198 }199200 func testFragmentsAreExcludedFromBackupAndOutsideCaches() throws {201 let store = try FragmentStore(root: root)202 _ = store203 XCTAssertEqual(try root.resourceValues(forKeys: [.isExcludedFromBackupKey]).isExcludedFromBackup, true)204 let production = try FileManager.default.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)205 XCTAssertFalse(production.path.contains("/Caches"))206 }207208 func testCapacityRules() {209 let gb = Format.gb210 XCTAssertEqual(CapacityMonitor.defaultReserve(total: 64 * gb), 20 * gb) // 20 GB wins on a 64 GB device211 XCTAssertEqual(CapacityMonitor.defaultReserve(total: 512 * gb), 51 * gb + gb / 5) // 10 % wins on a 512 GB device212 var cap = Capacity(total: 256 * gb, free: 100 * gb, reserve: 25 * gb, quota: 50 * gb, used: 10 * gb, fragments: 0)213 XCTAssertEqual(cap.writable, 40 * gb) // bounded by the quota214 cap.free = 30 * gb; XCTAssertEqual(cap.writable, 5 * gb) // bounded by free space above the reserve215 cap.free = 20 * gb; XCTAssertEqual(cap.writable, 0) // under the reserve: writes suspended216 XCTAssertEqual(CapacityMonitor.options(maxAllocatable: 60 * gb), [1, 2, 5, 10, 25, 50].map { Int64($0) * gb })217 XCTAssertEqual(CapacityMonitor.options(maxAllocatable: gb / 2), [])218 XCTAssertEqual(CapacityMonitor.options(maxAllocatable: 1100 * gb).last, 1000 * gb)219 }220221 func testPairingInputParsing() {222 XCTAssertEqual(NodeEngine.parsePairing("msp1://pair?h=storage.spboucher.ai&c=ABCD-EFGH-JKMN")?.code, "ABCD-EFGH-JKMN")223 XCTAssertEqual(NodeEngine.parsePairing(" abcd efgh jkmn ")?.code, "ABCDEFGHJKMN")224 XCTAssertEqual(NodeEngine.parsePairing("abcd-efgh-jkmn")?.host, "storage.spboucher.ai")225 XCTAssertNil(NodeEngine.parsePairing("msp1://pair?h=evil.example.com&c=ABCD-EFGH-JKMN")) // a QR code cannot point the app at another host226 XCTAssertNil(NodeEngine.parsePairing("ABCD-EFGH"))227 XCTAssertNil(NodeEngine.parsePairing("https://storage.spboucher.ai/"))228 }229230 func testCanonicalRequestAndSignatureVerify() throws {231 let body = Data(#"{"a":1}"#.utf8)232 let msg = MSPClient.canonical(method: "post", path: "/msp/1/heartbeat", timestamp: "1796140000", nonce: "abcDEF123456_-xy", body: body)233 XCTAssertEqual(String(data: msg, encoding: .utf8), "MSP1\nPOST\n/msp/1/heartbeat\n1796140000\nabcDEF123456_-xy\n" + sha(body))234 // A software P-256 key signs the way the device key does; the signature verifies against the X9.63 public key.235 let attrs: [String: Any] = [kSecAttrKeyType as String: kSecAttrKeyTypeECSECPrimeRandom, kSecAttrKeySizeInBits as String: 256]236 let key = try XCTUnwrap(SecKeyCreateRandomKey(attrs as CFDictionary, nil))237 let sig = try XCTUnwrap(Data(base64Encoded: try DeviceIdentity.sign(msg, with: key)))238 let pub = try XCTUnwrap(SecKeyCopyPublicKey(key)), raw = try XCTUnwrap(SecKeyCopyExternalRepresentation(pub, nil) as Data?)239 XCTAssertEqual(raw.count, 65); XCTAssertEqual(raw.first, 4)240 let verifier = try P256.Signing.PublicKey(x963Representation: raw)241 XCTAssertTrue(verifier.isValidSignature(try P256.Signing.ECDSASignature(derRepresentation: sig), for: msg))242 }243}244