SPB Git

Repository Public

FoundationTests.swift 11.3 KB 179 lines swift

1// SP Wallet Core2// File: Tests/SPWalletCoreTests/FoundationTests.swift3// Description: Exact amounts, encodings, the API client's request contract (cookie, CSRF, idempotency, errors, session events).4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import Foundation8import Testing9@testable import SPWalletCore1011@Suite struct BaseUnitsTests {12    @Test func parseAndFormatMirrorTheBackend() throws {13        #expect(try BaseUnits.parse("1.5", decimals: 6).description == "1500000")14        #expect(try BaseUnits.parse("1,5", decimals: 6).description == "1500000")15        #expect(try BaseUnits.parse("0.000001", decimals: 6).description == "1")16        #expect(try BaseUnits.parse("12", decimals: 0).description == "12")17        #expect(try BaseUnits.parse("1.2300", decimals: 2).description == "123")18        #expect(try BaseUnits.parse("1.", decimals: 18).description == "1000000000000000000")19        #expect(try BaseUnits.parse("0", decimals: 18).isZero)20        #expect(try BaseUnits("1500000").formatted(decimals: 6) == "1.5")21        #expect(try BaseUnits("1").formatted(decimals: 18) == "0.000000000000000001")22        #expect(try BaseUnits("1000000000000000000").formatted(decimals: 18) == "1")23        #expect(BaseUnits.zero.formatted(decimals: 8) == "0")24    }25    @Test func refusesWhatTheBackendRefuses() {26        #expect(throws: AmountError.tooManyDecimals) { try BaseUnits.parse("1.0000001", decimals: 6) }27        #expect(throws: AmountError.invalid) { try BaseUnits.parse("", decimals: 6) }28        #expect(throws: AmountError.invalid) { try BaseUnits.parse(".5", decimals: 6) }29        #expect(throws: AmountError.invalid) { try BaseUnits.parse("-1", decimals: 6) }30        #expect(throws: AmountError.invalid) { try BaseUnits.parse("1e3", decimals: 6) }31        #expect(throws: AmountError.invalid) { try BaseUnits.parse("1.2.3", decimals: 6) }32        #expect(throws: AmountError.invalid) { try BaseUnits.parse("1 000", decimals: 6) }33        #expect(throws: AmountError.overflow) { try BaseUnits.parse(String(repeating: "9", count: 60), decimals: 36) }34        #expect(throws: AmountError.invalid) { try BaseUnits.parse(String(repeating: "9", count: 61), decimals: 0) } // the backend reads at most 60 integer digits35        #expect(throws: AmountError.invalid) { try BaseUnits("01") }36        #expect(throws: AmountError.invalid) { try BaseUnits("1.0") }37        #expect(throws: AmountError.negativeResult) { try BaseUnits(1).subtracting(BaseUnits(2)) }38    }39    @Test func arithmeticIsExactBeyond64Bits() throws {40        let a = try BaseUnits("340282366920938463463374607431768211455") // 2^128 − 141        let b = try BaseUnits("1")42        #expect((a + b).description == "340282366920938463463374607431768211456")43        #expect(try (a + b).subtracting(b) == a)44        #expect(a.multiplied(by: 1000).description == "340282366920938463463374607431768211455000")45        #expect(a.multiplied(by: 1000).divided(by: 1000) == a)46        #expect(try BaseUnits("999999999") < BaseUnits("1000000000"))47        #expect(BaseUnits.max256.description.count == 78)48        #expect(try BaseUnits("1000000000000000000000").subtracting(BaseUnits("1")).description == "999999999999999999999")49    }50}5152@Suite struct EncodingTests {53    @Test func base64URLRoundTripAndStrictness() {54        let d = Data([0xfb, 0xff, 0x00, 0x01])55        #expect(d.base64URL == "-_8AAQ")56        #expect(Data(base64URL: "-_8AAQ") == d)57        #expect(Data(base64URL: "+/8AAQ") == nil)58        #expect(Data(hex: "0xfbff0001") == d)59        #expect(Data(hex: "abc") == nil)60        #expect(d.hex == "fbff0001")61    }62}6364@Suite struct APIClientTests {65    @Test func readsSendTheCookieAndNoCSRFHeaders() async throws {66        let (client, t, _) = MockTransport.client()67        t.enqueue(json: #"{"setupRequired":false,"authenticated":true}"#)68        let s = try await AuthAPI(client).state()69        #expect(s.authenticated)70        let r = try #require(t.last)71        #expect(r.method == "GET" && r.path == "/api/v1/auth/state")72        #expect(r.headers["Cookie"] == "__Host-spw=test-session-token")73        #expect(r.headers["Origin"] == nil && r.headers["X-SPW-CSRF"] == nil)74    }75    @Test func writesCarryOriginCSRFAndIdempotencyKey() async throws {76        let (client, t, _) = MockTransport.client()77        t.enqueue(status: 422, json: #"{"error":"policy","message":"amount above the per-transfer limit"}"#)78        let key = APIClient.newIdempotencyKey()79        await #expect(throws: APIError.self) {80            _ = try await TransfersAPI(client).draft(TransferRequest(network: "base", asset: "native", to: "0xabc", amount: "1"), idempotencyKey: key)81        }82        let r = try #require(t.last)83        #expect(r.method == "POST" && r.path == "/api/v1/transfers/proposals")84        #expect(r.headers["Origin"] == "https://wallet.example.test")85        #expect(r.headers["X-SPW-CSRF"] == "1")86        #expect(r.headers["Idempotency-Key"] == key)87        #expect(key.range(of: "^[A-Za-z0-9-]{16,64}$", options: .regularExpression) != nil)88        #expect(r.body?["amount"]?.stringValue == "1")89    }90    @Test func serverErrorsKeepCodeMessageAndData() async throws {91        let (client, t, _) = MockTransport.client()92        t.enqueue(status: 409, json: #"{"error":"quote_moved","message":"the price moved","data":{"deviationBps":-51}}"#)93        do { let _: OKResponse = try await client.post("/swap/prepare"); Issue.record("expected an error") }94        catch let e as APIError {95            #expect(e.status == 409 && e.code == "quote_moved" && e.message == "the price moved")96            #expect(e.data?["deviationBps"]?.intValue == -51)97        }98    }99    @Test func unauthenticatedErasesTheTokenAndEmitsAnEvent() async throws {100        let (client, t, store) = MockTransport.client()101        let events = await client.events()102        t.enqueue(status: 401, json: #"{"error":"unauthenticated","message":"authentication required"}"#)103        await #expect(throws: APIError.self) { _ = try await WalletAPI(client).portfolio() }104        #expect(store.load() == nil)105        var it = events.makeAsyncIterator()106        #expect(await it.next() == .unauthenticated)107    }108    @Test func loginStoresOnlyTheConfiguredCookie() async throws {109        let (client, t, store) = MockTransport.client(token: nil)110        t.enqueue(json: #"{"ok":true}"#, headers: ["Set-Cookie": "__Host-spw=abc123; Path=/; HttpOnly; Secure; SameSite=Strict; Max-Age=43200"])111        let _: OKResponse = try await client.post("/auth/login/verify")112        #expect(store.load() == "abc123")113        t.enqueue(json: #"{"ok":true}"#, headers: ["Set-Cookie": "other=zzz; Path=/"])114        let _: OKResponse = try await client.post("/x")115        #expect(store.load() == "abc123")116    }117    @Test func offlineIsItsOwnError() async throws {118        struct Down: HTTPTransport { func send(_ r: URLRequest) async throws -> (Data, HTTPURLResponse) { throw URLError(.notConnectedToInternet) } }119        let cfg = APIConfiguration(origin: URL(string: "https://wallet.example.test")!, rpId: "wallet.example.test", userAgent: "t")120        let client = APIClient(configuration: cfg, tokens: InMemoryTokenStore("x"), transport: Down())121        do { _ = try await WalletAPI(client).networks(); Issue.record("expected offline") }122        catch let e as APIError { #expect(e.isOffline) }123    }124    @Test func pathSegmentsCannotChangeTheRoute() {125        #expect(APIClient.segment("a/b?c#d%") == "a%2Fb%3Fc%23d%25")126    }127}128129@Suite struct ApprovalBindingTests {130    static let intentJSON: JSONValue = [131        "v": 1, "proposalId": "6f1c2f0e-5a3b-4c44-9d0a-0f6f0c1d2e3f", "keyId": "spw-0123456789abcdef", "network": "base", "chainRef": "8453",132        "asset": "native", "symbol": "ETH", "decimals": 18, "amount": "1000000000000000", "from": "0x1111111111111111111111111111111111111111",133        "to": "0x2222222222222222222222222222222222222222", "maxFee": "21000000000000", "createdAt": 1795000000, "expiresAt": 1795000120, "policyVersion": 4,134        "evm": ["nonce": 7, "gasLimit": "21000", "maxFeePerGas": "1000000000", "maxPriorityFeePerGas": "1000000"],135    ]136    @Test func aMatchingChallengeVerifies() throws {137        let intent = try Intent(served: Self.intentJSON)138        let digest = try intent.approvalDigest()139        let ok = PasskeyRequestOptions(challenge: digest.base64URL, rpId: "wallet.example.test")140        #expect(try ApprovalBinding.verify(intent, options: ok, rpId: "wallet.example.test").digest == digest)141    }142    @Test func anyOtherChallengeRelyingPartyOrVerificationLevelIsRefused() throws {143        let intent = try Intent(served: Self.intentJSON)144        let digest = try intent.approvalDigest()145        var other = digest; other[0] ^= 1146        #expect(throws: ApprovalError.challengeMismatch) { try ApprovalBinding.verify(intent, options: .init(challenge: other.base64URL, rpId: "wallet.example.test"), rpId: "wallet.example.test") }147        #expect(throws: ApprovalError.wrongRelyingParty("evil.example")) { try ApprovalBinding.verify(intent, options: .init(challenge: digest.base64URL, rpId: "evil.example"), rpId: "wallet.example.test") }148        #expect(throws: ApprovalError.userVerificationNotRequired) { try ApprovalBinding.verify(intent, options: .init(challenge: digest.base64URL, rpId: "wallet.example.test", userVerification: "preferred"), rpId: "wallet.example.test") }149    }150    @Test func anUnknownFieldIsARefusalNotAnOmission() throws {151        guard case .object(var o) = Self.intentJSON else { return }152        o["drain"] = "1"153        #expect(throws: ApprovalError.self) { try Intent(served: .object(o)) }154        guard case .object(var e) = Self.intentJSON["evm"]! else { return }155        e["data"] = "0xdeadbeef"156        var o2 = Self.intentJSON.objectValue!; o2["evm"] = .object(e)157        #expect(throws: ApprovalError.self) { try Intent(served: .object(o2)) }158    }159    @Test func changingAnyFieldChangesTheDigest() throws {160        let base = try Intent(served: Self.intentJSON).approvalDigest()161        for (k, v) in [("amount", JSONValue.string("1000000000000001")), ("to", "0x3333333333333333333333333333333333333333"), ("maxFee", "21000000000001"), ("expiresAt", 1795000121), ("network", "arbitrum")] {162            var o = Self.intentJSON.objectValue!; o[k] = v163            #expect(try Intent(served: .object(o)).approvalDigest() != base, "field \(k)")164        }165    }166    @Test func theIntentMustBeTheProposalReviewed() throws {167        let intent = try Intent(served: Self.intentJSON)168        func proposal(amount: String = "1000000000000000", to: String = "0x2222222222222222222222222222222222222222") throws -> Proposal {169            try JSONValue.object(["id": "6f1c2f0e-5a3b-4c44-9d0a-0f6f0c1d2e3f", "state": "draft", "network": "base", "asset": "native", "symbol": "ETH", "decimals": 18,170                                  "amount": .string(amount), "amountDisplay": "0.001", "to": .string(to)]).decode()171        }172        let now = Date(timeIntervalSince1970: 1795000010)173        try TransfersAPI.check(intent: intent, against: proposal(), now: now)174        #expect(throws: ApprovalError.inconsistent("amount")) { try TransfersAPI.check(intent: intent, against: proposal(amount: "2"), now: now) }175        #expect(throws: ApprovalError.inconsistent("destination")) { try TransfersAPI.check(intent: intent, against: proposal(to: "0x4444444444444444444444444444444444444444"), now: now) }176        #expect(throws: ApprovalError.expired) { try TransfersAPI.check(intent: intent, against: proposal(), now: Date(timeIntervalSince1970: 1795000121)) }177    }178}179
Files main
Menu

Theme