SPB Git

Repository Public

Harness.swift 14.8 KB 313 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : SP Vault9// File             : apple/SharedVaultKit/Tests/SharedVaultKitClientTests/Harness.swift10// Module           : SharedVaultKitClientTests11// Repository       : https://git.spboucher.ai/sp-vault12// Project Website  : https://vault.spboucher.ai13// Created          : 2026-11-1914// Last Modified    : 2026-11-1915//16// =============================================================================17// AUTHOR & PROFESSIONAL AFFILIATION18// =============================================================================19//20// Author           : Simon-Pierre Boucher21// Position         : Professor of Finance22// Institution      : Université du Québec en Outaouais (UQO)23// Department       : Département des sciences administratives24// Organization     : SP Boucher25//26// Website          : https://spboucher.ai27// Git              : https://git.spboucher.ai28//29// =============================================================================30// OFFICIAL CONTACT DIRECTORY31// =============================================================================32//33// General          : info@spboucher.ai34// Professional     : contact@spboucher.ai35// Direct           : simon@spboucher.ai36// Research         : research@spboucher.ai37// Development      : dev@spboucher.ai38// Support          : support@spboucher.ai39// Security/Admin   : admin@spboucher.ai40// Notifications    : notifications@spboucher.ai41//42// Preferred Contact: support@spboucher.ai43//44// =============================================================================45// COPYRIGHT & INTELLECTUAL PROPERTY46// =============================================================================47//48// Copyright (c) 202649// Simon-Pierre Boucher50//51// All rights reserved where applicable.52//53// This file is governed by the applicable project license,54// copyright notices, institutional agreements and relevant law.55//56// Unless expressly authorized by the applicable license or57// rights holder, copying, redistribution, sublicensing,58// publication and commercial exploitation are not permitted.59//60// Existing third-party rights and notices remain unaffected.61//62// =============================================================================63// CONFIDENTIALITY & SECURITY64// =============================================================================65//66// Classification   : Public67// Distribution     : Public repository; use is governed by the project license68// Security Contact : admin@spboucher.ai69//70// Access to this source does not independently grant permission71// to redistribute or disclose confidential materials.72//73// Do not embed credentials, private keys, access tokens,74// certificates or confidential personal information.75//76// =============================================================================77// LICENSE & MAINTENANCE78// =============================================================================79//80// License          : None specified (no license file in this repository)81// Maintainer       : Simon-Pierre Boucher82// Technical Contact: dev@spboucher.ai83//84// =============================================================================85// END OF SP BOUCHER SOURCE HEADER86// =============================================================================8788// Test harness: a real server process, a real PostgreSQL database, a software WebAuthn authenticator and a89// recording transport. Nothing in the server is stubbed or bypassed. Swift port of tests/harness.ts.90import CryptoKit91import Foundation92import XCTest93@testable import SharedVaultKit9495enum TestEnv {96    static let port = 877197    static let origin = "http://localhost:\(port)"98    static let database = "sp_vault_swift_test"99    static let databaseURL = "postgres://127.0.0.1/\(database)"100    static let testsDir = URL(fileURLWithPath: #filePath).deletingLastPathComponent()101    static let packageDir = testsDir.deletingLastPathComponent().deletingLastPathComponent()102    static let repoRoot = packageDir.deletingLastPathComponent().deletingLastPathComponent()103    static let toolsDir = packageDir.appendingPathComponent("Tests/Tools")104    static var path: String { "/opt/homebrew/bin:/usr/local/bin:" + (ProcessInfo.processInfo.environment["PATH"] ?? "/usr/bin:/bin") }105    static var environment: [String: String] {106        var e = ProcessInfo.processInfo.environment107        e["PATH"] = path108        return e109    }110}111112struct ShellError: Error, CustomStringConvertible { let description: String }113114/// Runs a tool found on PATH and returns its standard output.115@discardableResult116func runTool(_ tool: String, _ args: [String], input: Data? = nil, cwd: URL? = nil, env: [String: String] = [:]) throws -> String {117    let p = Process()118    p.executableURL = URL(fileURLWithPath: "/usr/bin/env")119    p.arguments = [tool] + args120    p.environment = TestEnv.environment.merging(env) { $1 }121    if let cwd { p.currentDirectoryURL = cwd }122    let out = Pipe(), err = Pipe(), inp = Pipe()123    p.standardOutput = out; p.standardError = err; p.standardInput = inp124    try p.run()125    if let input { inp.fileHandleForWriting.write(input) }126    try? inp.fileHandleForWriting.close()127    let data = out.fileHandleForReading.readDataToEndOfFile()128    let errData = err.fileHandleForReading.readDataToEndOfFile()129    p.waitUntilExit()130    guard p.terminationStatus == 0 else { throw ShellError(description: "\(tool) failed (\(p.terminationStatus)): \(String(decoding: errData, as: UTF8.self).prefix(400))") }131    return String(decoding: data, as: UTF8.self)132}133134/// One statement (or several) against the test database; returns unaligned, tuples-only output.135@discardableResult136func psql(_ sql: String) throws -> String {137    try runTool("psql", ["-h", "127.0.0.1", "-d", TestEnv.database, "-X", "-q", "-At", "-v", "ON_ERROR_STOP=1", "-f", "-"], input: Data(sql.utf8))138        .trimmingCharacters(in: .whitespacesAndNewlines)139}140141/// The real API server, started once per test process (like `startServer()` in tests/harness.ts).142final class Server: NSObject, XCTestObservation, @unchecked Sendable {143    static let shared = Server()144    private let lock = NSLock()145    private var process: Process?146    private var dataDir: URL?147    private var startError: Error?148    private var started = false149150    func ensureStarted() throws {151        lock.lock(); defer { lock.unlock() }152        if let startError { throw startError }153        if started { return }154        do { try start() } catch { startError = error; throw error }155        started = true156    }157158    private func start() throws {159        // a server left over by a crashed run still holds the port: stop it by PID160        if let pids = try? runTool("lsof", ["-ti", "tcp:\(TestEnv.port)", "-sTCP:LISTEN"]) {161            for pid in pids.split(separator: "\n").compactMap({ Int32($0) }) { kill(pid, SIGTERM) }162            if !pids.isEmpty { Thread.sleep(forTimeInterval: 0.5) }163        }164        _ = try? runTool("createdb", ["-h", "127.0.0.1", TestEnv.database])165        try psql("drop schema public cascade; create schema public;")166        let dir = FileManager.default.temporaryDirectory.appendingPathComponent("spv-swift-test-\(UUID().uuidString)")167        try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)168        dataDir = dir169        let p = Process()170        p.executableURL = TestEnv.repoRoot.appendingPathComponent("node_modules/.bin/tsx")171        p.arguments = ["services/api/src/index.ts"]172        p.currentDirectoryURL = TestEnv.repoRoot173        p.environment = TestEnv.environment.merging([174            "DATABASE_URL": TestEnv.databaseURL, "PORT": String(TestEnv.port), "SPV_ORIGIN": TestEnv.origin, "SPV_RP_ID": "localhost",175            "SPV_DATA_DIR": dir.path, "SPV_LOG_LEVEL": "warn", "SPV_RATE_SCALE": "50",176            "SPV_BREACH_UPSTREAM": "\(TestEnv.origin)/api/health/ready?", // same stub as tests/harness.ts: no outside request177        ]) { $1 }178        p.standardInput = FileHandle.nullDevice179        p.standardOutput = FileHandle.nullDevice180        // the server's own log goes to a file: an inherited stderr would keep a calling pipeline open if this process dies181        let logURL = dir.appendingPathComponent("server.log")182        FileManager.default.createFile(atPath: logURL.path, contents: nil)183        p.standardError = try FileHandle(forWritingTo: logURL)184        try p.run()185        process = p186        XCTestObservationCenter.shared.addTestObserver(self)187        for _ in 0..<150 {188            if (try? runTool("curl", ["-fsS", "-o", "/dev/null", "\(TestEnv.origin)/api/health/ready"])) != nil { return }189            if !p.isRunning { throw ShellError(description: "the API server exited during start-up") }190            Thread.sleep(forTimeInterval: 0.15)191        }192        throw ShellError(description: "server did not start")193    }194195    func stop() {196        lock.lock(); defer { lock.unlock() }197        TSHelper.shared.stop()198        if let p = process, p.isRunning {199            p.terminate() // SIGTERM to the PID we started200            p.waitUntilExit()201        }202        process = nil203        if let dataDir { try? FileManager.default.removeItem(at: dataDir) }204        started = false205    }206207    func testBundleDidFinish(_ testBundle: Bundle) { stop() }208}209210func makeInvite() throws -> String {211    let token = SPV1.b64u(SPV1.random(24))212    let hash = SPV1.b64u(SPV1.sha256(SPV1.utf8(token)))213    try psql("insert into invites (token_hash, label, expires_at) values ('\(hash)', 'test', now() + interval '1 hour')")214    return token215}216217// ── transport that records everything it sends and can go offline ───────────────────────────────────────────218final class TestTransport: VaultTransport, @unchecked Sendable {219    private let inner = URLSessionTransport(baseURL: URL(string: TestEnv.origin)!)220    private let lock = NSLock()221    private var _offline = false222    private var _log: [String] = []223    private var _paths: [String] = []224225    var offline: Bool {226        get { lock.lock(); defer { lock.unlock() }; return _offline }227        set { lock.lock(); _offline = newValue; lock.unlock() }228    }229    /// path + body of every request (binary bodies as "<binary>"), like `NodeTransport.log`.230    var sent: String { lock.lock(); defer { lock.unlock() }; return _log.joined(separator: "\n") }231    var paths: [String] { lock.lock(); defer { lock.unlock() }; return _paths }232233    func send(_ method: String, _ path: String, body: JSONValue?, options: TransportOptions) async throws -> Data {234        if offline { throw ApiError.offline }235        lock.withLock {236            _log.append(path + (options.binary != nil ? "<binary>" : (body?.serializedString() ?? "")) + options.headers.map { "\($0)=\($1)" }.joined())237            _paths.append("\(method) \(path)")238        }239        return try await inner.send(method, path, body: body, options: options)240    }241242    func setBearerToken(_ token: String?) async { await inner.setBearerToken(token) }243}244245// ── devices ─────────────────────────────────────────────────────────────────────────────────────────────────246struct Dev: Sendable {247    let engine: VaultEngine248    let api: TestTransport249    let store: any LocalStore250    let keyStore: any DeviceKeyStore251    let auth: SoftwarePasskeys252}253254func device(auth: SoftwarePasskeys = SoftwarePasskeys(), platform: String = "Test device", store: any LocalStore = MemoryStore(), keyStore: any DeviceKeyStore = InMemoryKeyStore()) -> Dev {255    let api = TestTransport()256    return Dev(engine: VaultEngine(transport: api, store: store, keyStore: keyStore, passkeys: auth, platformLabel: platform), api: api, store: store, keyStore: keyStore, auth: auth)257}258259func newAccount(_ handle: String, store: any LocalStore = MemoryStore(), keyStore: any DeviceKeyStore = InMemoryKeyStore(), platform: String = "Test device") async throws -> (dev: Dev, recoveryKey: String) {260    let d = device(platform: platform, store: store, keyStore: keyStore)261    let rk = try await d.engine.register(invite: try makeInvite(), handle: handle)262    return (d, rk)263}264265/// Enrols a second device of the same account through the pairing flow.266func pair(_ trusted: Dev, platform: String = "Second device") async throws -> Dev {267    let d = device(auth: trusted.auth, platform: platform)268    let s = try await d.engine.signIn()269    guard s == .pending else { throw ShellError(description: "expected a pending session") }270    let offer = try await d.engine.startPairing()271    let req = try await trusted.engine.inspectPairing(code: offer.code)272    guard req.sas == offer.sas else { throw ShellError(description: "SAS mismatch") }273    try await trusted.engine.approvePairing(req)274    guard try await d.engine.checkPairing() == .done else { throw ShellError(description: "pairing did not complete") }275    return d276}277278func personal(_ d: Dev) async throws -> String {279    guard let v = await d.engine.vaults().first else { throw ShellError(description: "no vault") }280    return v.vaultId281}282283let SECRET_TITLE = "Banque Zanzibar-7731", SECRET_PW = "correct-horse-ZQ9-battery", SECRET_USER = "alice.zq9@example.test"284func login(_ title: String = SECRET_TITLE) -> Item {285    var it = SPV1.newItem(.login, title: title)286    it.fields = ["username": SECRET_USER, "password": SECRET_PW, "totp": "JBSWY3DPEHPK3PXP"]287    it.urls = [ItemUrl(url: "https://bank.zanzibar-7731.test/login", match: .domain)]288    it.notes = "note-ZQ9-secret"289    it.tags = ["tag-zq9"]290    return it291}292293/// `assert.rejects` with a predicate on the error.294func assertRejects<T: Sendable>(_ body: () async throws -> T, _ check: (Error) -> Bool = { _ in true }, _ message: String = "", file: StaticString = #filePath, line: UInt = #line) async {295    do { _ = try await body(); XCTFail("expected an error. \(message)", file: file, line: line) }296    catch { XCTAssertTrue(check(error), "unexpected error \(error). \(message)", file: file, line: line) }297}298299/// `XCTUnwrap` for values obtained with `await` (XCTest's autoclosure cannot await).300func unwrap<T>(_ value: T?, file: StaticString = #filePath, line: UInt = #line) throws -> T {301    guard let value else { XCTFail("unexpected nil", file: file, line: line); throw ShellError(description: "unexpected nil") }302    return value303}304305func apiStatus(_ status: Int) -> (Error) -> Bool { { ($0 as? ApiError)?.status == status } }306func apiCode(_ code: String) -> (Error) -> Bool { { ($0 as? ApiError)?.code == code } }307308class ServerTestCase: XCTestCase {309    override func setUpWithError() throws {310        try Server.shared.ensureStarted()311    }312}313
Files main
Menu

Theme