SPB Git

Repository Public

LiveStackTests.swift 6.5 KB 115 lines swift

1// SP Wallet Core2// File: Tests/SPWalletLiveTests/LiveStackTests.swift3// Description: End-to-end tests against a THROWAWAY local stack (Scripts/dev-stack.sh up): real API, real isolated signer process,4//              random keys, broadcast off. They go through owner setup, passkey login, the base reads, and the refusals that5//              protect the owner. Skipped unless SPW_LIVE_ORIGIN is set. Never pointed at production (the software authenticator6//              refuses it).7//8// Author: Simon-Pierre Boucher9// Contact: contact@spboucher.ai10import Foundation11import Testing12import SPWalletCore13import SPWalletTestSupport1415enum Live {16    static let origin = ProcessInfo.processInfo.environment["SPW_LIVE_ORIGIN"]17    static let dir = ProcessInfo.processInfo.environment["SPW_LIVE_DIR"] ?? "/tmp/spw-native-8750/current"18    static var enabled: Bool { origin != nil }1920    static func configuration() -> APIConfiguration {21        let o = URL(string: origin!)!22        precondition(o.host == "localhost" || o.host == "127.0.0.1", "live tests only run against a local throwaway stack")23        return APIConfiguration(origin: o, rpId: "localhost", userAgent: "SPWalletLiveTests")24    }2526    /** One-time owner setup of the throwaway stack, shared by every suite (two concurrent setups would enrol two different keys). */27    private static let owner = Task<SoftwareAuthenticator, Error> {28        let cfg = configuration()29        let client = APIClient(configuration: cfg, tokens: InMemoryTokenStore())30        let auth = SoftwareAuthenticator(origin: cfg.originHeader, file: URL(fileURLWithPath: dir).appendingPathComponent("software-passkey.json"))31        let token = try String(contentsOfFile: dir + "/setup-token", encoding: .utf8).trimmingCharacters(in: .whitespacesAndNewlines)32        try await DevStackSetup.ensureOwner(client: client, authenticator: auth, setupToken: token)33        return auth34    }3536    /** A fresh client with its own session, signed in with the stack's software passkey. */37    static func make() async throws -> (APIClient, SoftwareAuthenticator) {38        let auth = try await owner.value39        let client = APIClient(configuration: configuration(), tokens: InMemoryTokenStore())40        try await AuthAPI(client).login(with: auth)41        return (client, auth)42    }43}4445@Suite(.enabled(if: Live.enabled), .serialized) struct LiveStackTests {46    @Test func loginThenBaseReads() async throws {47        let (client, _) = try await Live.make()48        #expect(try await AuthAPI(client).state().authenticated)49        let wallet = WalletAPI(client)50        let networks = try await wallet.networks()51        #expect(networks.count >= 20)52        #expect(networks.contains { $0.id == "ethereum" && $0.family == "evm" })53        let accounts = try await wallet.accounts()54        #expect(accounts.signerReachable)55        #expect(accounts.accounts.count == networks.count)56        let p = try await wallet.portfolio()57        #expect(p.halted == false)58        #expect(!p.balances.isEmpty)59        _ = try await wallet.activity()60        _ = try await wallet.settings()61        let sec = try await wallet.securityOverview()62        #expect(sec.signer.reachable && sec.broadcast == (Fork.address != nil))63        #expect(sec.devices.count >= 1)64        let journal = try await wallet.audit(limit: 20)65        #expect(journal.intact && journal.events.contains { $0.type == "login.ok" || $0.type == "owner.setup" })66        _ = try await wallet.healthReady()67        #expect(String(decoding: try await wallet.activityCSV(), as: UTF8.self).hasPrefix("time_utc,direction"))68    }6970    @Test func aSessionlessClientIsRefused() async throws {71        let client = APIClient(configuration: Live.configuration(), tokens: InMemoryTokenStore())72        do { _ = try await WalletAPI(client).portfolio(); Issue.record("expected 401") }73        catch let e as APIError { #expect(e.isUnauthenticated) }74    }7576    @Test func aWriteWithoutTheCSRFHeadersIsRefusedByTheServer() async throws {77        let (client, _) = try await Live.make()78        var req = URLRequest(url: URL(string: Live.origin! + "/api/v1/security/emergency-halt")!)79        req.httpMethod = "POST"; req.httpBody = Data("{}".utf8)80        req.setValue("application/json", forHTTPHeaderField: "Content-Type")81        req.setValue(await client.cookieHeader(), forHTTPHeaderField: "Cookie")82        let (_, r) = try await URLSession(configuration: .ephemeral).data(for: req)83        #expect((r as? HTTPURLResponse)?.statusCode == 403)84        #expect(try await WalletAPI(client).portfolio().halted == false)85    }8687    @Test func badDestinationsAndAmountsAreRefusedBeforeAnythingIsSignable() async throws {88        let (client, _) = try await Live.make()89        let t = TransfersAPI(client)90        func code(_ r: TransferRequest) async -> String? {91            do { _ = try await t.draft(r, idempotencyKey: APIClient.newIdempotencyKey()); return nil } catch let e as APIError { return e.code } catch { return "other" }92        }93        let good = "0x52908400098527886E0F7030069857D2E4169EE7"94        #expect(await code(.init(network: "base", asset: "native", to: "0x0000000000000000000000000000000000000000", amount: "0.001")) == "bad_address")95        #expect(await code(.init(network: "base", asset: "native", to: "0x5AAeb6053F3E94C9b9A09f33669435E7Ef1BeAeD", amount: "0.001")) == "bad_address") // mixed case with a wrong checksum96        #expect(await code(.init(network: "base", asset: "native", to: good, amount: "0")) == "bad_amount")97        #expect(await code(.init(network: "base", asset: "native", to: good, amount: "0.0000000000000000001")) == "bad_amount")98        #expect(await code(.init(network: "base", asset: "0x0000000000000000000000000000000000000001", to: good, amount: "1")) == "unsupported_asset")99        let own = try await WalletAPI(client).accounts().accounts.first { $0.network == "base" }!.address100        #expect(await code(.init(network: "base", asset: "native", to: own, amount: "0.001")) == "bad_address")101    }102103    @Test func logoutEndsTheSessionOnTheServer() async throws {104        let (client, _) = try await Live.make()105        let cookie = await client.cookieHeader()106        await AuthAPI(client).logout()107        #expect(await client.hasToken == false)108        // the old cookie is refused by the server, not only forgotten by the client109        var req = URLRequest(url: URL(string: Live.origin! + "/api/v1/portfolio")!)110        req.setValue(cookie, forHTTPHeaderField: "Cookie")111        let (_, r) = try await URLSession(configuration: .ephemeral).data(for: req)112        #expect((r as? HTTPURLResponse)?.statusCode == 401)113    }114}115
Files main
Menu

Theme