SPB Git

Repository Public

FlowModelTests.swift 20.4 KB 445 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : MacLustr Identity9// File             : sdk/swift/Tests/MacLustrIdentityCoreTests/FlowModelTests.swift10// Module           : MacLustrIdentityCoreTests11// Repository       : https://git.spboucher.ai/maclustr-identity12// Project Website  : https://identity.spboucher.ai13// Created          : 2026-12-0114// Last Modified    : 2026-12-0115//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: admin@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// =============================================================================8788import XCTest89@testable import MacLustrIdentityCore9091/// State machine transitions with a scripted transport.92@MainActor93final class FlowModelTests: XCTestCase {94    private func makeModel(_ t: MockTransport, language: IdentityLanguage? = nil) -> VerificationFlowModel {95        let m = VerificationFlowModel(client: IdentityClient(session: testSession, transport: t, retryPolicy: .none), language: language, sleeper: { _ in await Task.yield() })96        m.pollJitter = 097        return m98    }99100    /// Waits until the model reaches a step (polling runs in its own task).101    private func wait(_ m: VerificationFlowModel, for expected: FlowStep, file: StaticString = #filePath, line: UInt = #line) async {102        for _ in 0..<2000 {103            if m.step == expected { return }104            try? await Task.sleep(nanoseconds: 1_000_000)105        }106        XCTFail("step is \(m.step), expected \(expected)", file: file, line: line)107    }108109    private let jpeg = Data([0xFF, 0xD8, 0xFF, 0xD9])110    private let liveAwaitingDocument = Fixture.data("flow_live_awaiting_selfie", patch: ["status": "awaiting_document", "uploaded": [String: Bool]()])111    private let liveVerified = Fixture.data("flow_live_processing", patch: ["status": "verified", "result": ["status": "verified", "reasons": [[String: Any]](), "verified_at": "2026-12-01T10:05:00.000000-05:00"] as [String: Any]])112113    func testSandboxPathToVerified() async {114        let t = MockTransport()115        t.on("GET", "/", fixture: "flow_created")116        t.on("POST", "/consent", fixture: "flow_awaiting_document")117        t.on("POST", "/sandbox", fixture: "flow_sandbox_verified")118        let m = makeModel(t)119        XCTAssertEqual(m.step, .loading)120        await m.start()121        XCTAssertEqual(m.step, .intro)122        XCTAssertEqual(m.language, .fr)                 // session locale fr-CA123        XCTAssertTrue(m.isSandbox)124        XCTAssertEqual(m.applicationName, "Native Demo")125        XCTAssertEqual(m.resultForDismissal, .canceled)126        m.continueFromIntro()127        XCTAssertEqual(m.step, .method)128        m.selectMethod("document_selfie")129        XCTAssertEqual(m.step, .consent(methodID: "document_selfie"))130        m.declineConsent()131        XCTAssertEqual(m.step, .method)132        m.selectMethod("nope")133        XCTAssertEqual(m.step, .method)134        m.selectMethod("document_selfie")135        await m.acceptConsent()136        XCTAssertEqual(m.step, .sandbox)                // sandbox never captures images137        XCTAssertTrue(m.canWithdraw)138        await m.runSandboxScenario("verified")139        XCTAssertEqual(m.step, .result(.verified))140        XCTAssertEqual(m.resultForDismissal, .completed(status: .verified))141        XCTAssertFalse(m.canWithdraw)142        XCTAssertFalse(m.canDispute)143        XCTAssertNil(m.lastError)144        let consent = try! JSONSerialization.jsonObject(with: t.requests[1].httpBody!) as! [String: Any]145        XCTAssertEqual(consent["text_version"] as? String, "2026-12-01.2")     // echoed from the state, never hardcoded146        XCTAssertEqual(consent["biometric_consent"] as? Bool, true)147        XCTAssertEqual(consent["locale"] as? String, "fr-CA")148        XCTAssertEqual(try! JSONSerialization.jsonObject(with: t.requests[2].httpBody!) as? [String: String], ["scenario": "verified"])149    }150151    func testLiveSelfiePathWithPolling() async {152        let t = MockTransport()153        t.on("GET", "/", fixture: "flow_live_created")154        t.on("POST", "/consent", liveAwaitingDocument)155        t.on("POST", "/document", fixture: "document_accepted_front")156        t.on("POST", "/document", fixture: "document_accepted_back")157        t.on("POST", "/selfie/challenge", fixture: "challenge")158        t.on("POST", "/selfie", fixture: "selfie_accepted")159        t.on("POST", "/submit", fixture: "flow_live_processing")160        let m = makeModel(t)161        await m.start()162        XCTAssertFalse(m.isSandbox)163        m.continueFromIntro()164        m.selectMethod("document_selfie")165        await m.acceptConsent()166        XCTAssertEqual(m.step, .documentFront)167        let front = await m.uploadDocument(side: .front, image: jpeg)168        XCTAssertEqual(front, .accepted)169        XCTAssertEqual(m.step, .documentBack)170        XCTAssertEqual(m.state?.status, .awaitingSelfie)171        let back = await m.uploadDocument(side: .back, image: jpeg)172        XCTAssertEqual(back, .accepted)173        XCTAssertEqual(m.step, .selfie)174        let challenge = try! await m.requestChallenge(accessible: false)175        XCTAssertEqual(challenge.steps.count, 2)176        // Polling: two "processing" answers, then the decision.177        t.on("GET", "/", fixture: "flow_live_processing")178        t.on("GET", "/", fixture: "flow_live_processing")179        t.on("GET", "/", liveVerified)180        let ok = await m.uploadSelfie(challengeID: challenge.challengeID, frames: Array(repeating: jpeg, count: 8))181        XCTAssertTrue(ok)182        await wait(m, for: .result(.verified))183        XCTAssertEqual(m.resultForDismissal, .completed(status: .verified))184        XCTAssertEqual(t.count("POST /submit"), 1)185        XCTAssertGreaterThanOrEqual(t.count("GET /"), 4)186        XCTAssertEqual(Array(t.log.prefix(7)), ["GET /", "POST /consent", "POST /document", "POST /document", "POST /selfie/challenge", "POST /selfie", "POST /submit"])187    }188189    func testDocumentOnlyMethodSkipsBackAndSelfie() async {190        let single = try! JSONSerialization.jsonObject(with: Fixture.data("flow_live_created")) as! [String: Any]191        let review = (single["methods"] as! [[String: Any]])[1]192        let t = MockTransport()193        t.on("GET", "/", Fixture.data("flow_live_created", patch: ["methods": [review]]))194        t.on("POST", "/consent", Fixture.data("flow_live_awaiting_selfie", patch: ["status": "awaiting_document", "uploaded": [String: Bool](), "method": "document_review", "methods": [review]]))195        t.on("POST", "/document", Fixture.data("document_accepted_front", patch: ["status": "awaiting_document"]))196        t.on("POST", "/submit", Fixture.data("flow_live_processing", patch: ["method": "document_review", "methods": [review]]))197        let m = makeModel(t)198        await m.start()199        m.continueFromIntro()200        XCTAssertEqual(m.step, .consent(methodID: "document_review"))       // single method: no choice screen201        m.declineConsent()202        XCTAssertEqual(m.step, .intro)203        m.continueFromIntro()204        await m.acceptConsent()205        XCTAssertNil((try! JSONSerialization.jsonObject(with: t.requests[1].httpBody!) as! [String: Any])["biometric_consent"])206        await m.uploadDocument(side: .front, image: jpeg)207        XCTAssertEqual(m.step, .documentBack)208        t.on("GET", "/", Fixture.data("flow_sandbox_manual_review", patch: ["livemode": true]))209        await m.skipDocumentBack()210        await wait(m, for: .result(.manualReview))211        XCTAssertEqual(m.resultForDismissal, .completed(status: .manualReview))212        XCTAssertEqual(t.count("POST /selfie/challenge"), 0)213    }214215    func testRejectedDocumentStaysOnTheStep() async {216        let t = MockTransport()217        t.on("GET", "/", liveAwaitingDocument)218        t.on("POST", "/document", fixture: "document_rejected_quality")219        let m = makeModel(t)220        await m.start()221        XCTAssertEqual(m.step, .documentFront)          // resumed directly on the capture222        let r = await m.uploadDocument(side: .front, image: jpeg)223        XCTAssertEqual(r, .rejected(issues: ["image_blurry", "image_too_dark", "low_contrast"]))224        XCTAssertEqual(m.step, .documentFront)225        XCTAssertNil(m.lastError)226    }227228    func testUploadErrorIsRecoverable() async {229        let t = MockTransport()230        t.on("GET", "/", liveAwaitingDocument)231        t.on("POST", "/document", fixture: "error_unsupported_file_type", status: 400)232        t.fail("POST", "/document", URLError(.timedOut))233        t.on("POST", "/document", fixture: "document_accepted_front")234        let m = makeModel(t)235        await m.start()236        var r = await m.uploadDocument(side: .front, image: jpeg)237        XCTAssertEqual(r, .failed)238        XCTAssertEqual(m.lastError?.code, "unsupported_file_type")239        XCTAssertEqual(m.step, .documentFront)240        r = await m.uploadDocument(side: .front, image: jpeg)241        XCTAssertEqual(r, .failed)242        XCTAssertTrue(m.lastError?.isRetryable == true)243        r = await m.uploadDocument(side: .front, image: jpeg)244        XCTAssertEqual(r, .accepted)245        XCTAssertNil(m.lastError)246        XCTAssertFalse(m.isBusy)247    }248249    func testRetryWhenTheServiceAsksForANewCapture() async {250        let t = MockTransport()251        t.on("GET", "/", fixture: "flow_live_processing")           // resume while processing252        t.on("GET", "/", fixture: "flow_live_processing")253        t.on("GET", "/", Fixture.data("flow_live_processing", patch: ["status": "awaiting_document", "uploaded": [String: Bool](), "selfie_done": false, "attempts_left": 2]))254        let m = makeModel(t)255        await m.start()256        XCTAssertEqual(m.step, .processing)257        XCTAssertEqual(m.resultForDismissal, .completed(status: .processing))258        await wait(m, for: .documentFront)259        XCTAssertTrue(m.retryRequested)260        XCTAssertEqual(m.state?.attemptsLeft, 2)261        t.on("POST", "/document", fixture: "document_accepted_front")262        await m.uploadDocument(side: .front, image: jpeg)263        XCTAssertFalse(m.retryRequested)264        XCTAssertEqual(m.step, .documentBack)265    }266267    func testExpiryDuringTheFlow() async {268        let t = MockTransport()269        t.on("GET", "/", fixture: "flow_created")270        t.on("POST", "/consent", fixture: "error_invalid_session_state", status: 409)271        let m = makeModel(t)272        await m.start()273        m.continueFromIntro()274        m.selectMethod("document_review")275        t.on("GET", "/", Fixture.data("flow_created", patch: ["status": "expired"]))276        await m.acceptConsent()277        XCTAssertEqual(m.step, .result(.expired))278        XCTAssertEqual(m.resultForDismissal, .completed(status: .expired))279    }280281    func testResumeOnExpiredSession() async {282        let t = MockTransport()283        t.on("GET", "/", Fixture.data("flow_created", patch: ["status": "expired"]))284        let m = makeModel(t)285        await m.start()286        XCTAssertEqual(m.step, .result(.expired))287    }288289    func testWithdrawal() async {290        let t = MockTransport()291        t.on("GET", "/", liveAwaitingDocument)292        t.on("POST", "/withdraw", fixture: "withdraw")293        let m = makeModel(t)294        await m.start()295        XCTAssertTrue(m.canWithdraw)296        await m.withdraw()297        XCTAssertEqual(m.step, .result(.cancelled))298        XCTAssertEqual(m.resultForDismissal, .canceled)299        XCTAssertFalse(m.canWithdraw)300    }301302    func testWithdrawalRefusedResynchronises() async {303        let t = MockTransport()304        t.on("GET", "/", liveAwaitingDocument)305        t.on("POST", "/withdraw", fixture: "error_session_not_cancellable", status: 409)306        let m = makeModel(t)307        await m.start()308        t.on("GET", "/", fixture: "flow_sandbox_rejected")309        await m.withdraw()310        XCTAssertEqual(m.step, .result(.rejected))311        XCTAssertEqual(m.resultForDismissal, .completed(status: .rejected))312    }313314    func testInvalidSecretFailsTheFlow() async {315        let t = MockTransport()316        t.on("GET", "/", fixture: "error_invalid_client_secret", status: 401)317        let m = makeModel(t)318        await m.start()319        guard case .failed(let e) = m.step else { return XCTFail("\(m.step)") }320        XCTAssertEqual(e.code, "invalid_client_secret")321        XCTAssertEqual(m.resultForDismissal, .failed(e))322    }323324    func testNetworkFailureAtStartThenRetry() async {325        let t = MockTransport()326        t.fail("GET", "/", URLError(.notConnectedToInternet))327        t.on("GET", "/", fixture: "flow_created")328        let m = makeModel(t, language: .en)329        await m.start()330        guard case .failed(let e) = m.step, e.isRetryable else { return XCTFail("\(m.step)") }331        await m.start()332        XCTAssertEqual(m.step, .intro)333        XCTAssertEqual(m.language, .en)                 // forced language wins over the session locale334    }335336    func testPollingSurvivesTransientErrors() async {337        let t = MockTransport()338        t.on("GET", "/", fixture: "flow_live_processing")339        t.fail("GET", "/", URLError(.networkConnectionLost))340        t.on("GET", "/", status: 503, Data("busy".utf8))341        t.on("GET", "/", liveVerified)342        let m = makeModel(t)343        await m.start()344        await wait(m, for: .result(.verified))345        XCTAssertEqual(t.count("GET /"), 4)346    }347348    func testPollingBackoffAndSlowNotice() async {349        let t = MockTransport()350        for _ in 0..<7 { t.on("GET", "/", fixture: "flow_live_processing") }351        t.on("GET", "/", liveVerified)352        final class Delays: @unchecked Sendable {353            private var stored: [TimeInterval] = []354            private let lock = NSLock()355            func add(_ d: TimeInterval) { lock.lock(); stored.append(d); lock.unlock() }356            var values: [TimeInterval] { lock.lock(); defer { lock.unlock() }; return stored }357        }358        let delays = Delays()359        let m = VerificationFlowModel(client: IdentityClient(session: testSession, transport: t, retryPolicy: .none)) { d in360            delays.add(d)361            await Task.yield()362        }363        m.slowProcessingAfter = 10364        m.pollJitter = 0365        await m.start()366        await wait(m, for: .result(.verified))367        XCTAssertEqual(delays.values, [1.0, 1.5, 2.25, 3.375, 5.0625, 7.59375, 8.0])368        XCTAssertTrue(m.processingIsSlow)369    }370371    func testStopCancelsPolling() async {372        let t = MockTransport()373        t.on("GET", "/", fixture: "flow_live_processing")374        let m = VerificationFlowModel(client: IdentityClient(session: testSession, transport: t, retryPolicy: .none)) { _ in try await Task.sleep(nanoseconds: 5_000_000) }375        await m.start()376        try? await Task.sleep(nanoseconds: 30_000_000)377        m.stop()378        try? await Task.sleep(nanoseconds: 20_000_000)379        let n = t.count("GET /")380        try? await Task.sleep(nanoseconds: 50_000_000)381        XCTAssertEqual(t.count("GET /"), n)382        XCTAssertGreaterThan(n, 1)383    }384385    func testDisputeAfterRejection() async {386        let t = MockTransport()387        t.on("GET", "/", fixture: "flow_sandbox_rejected")388        t.on("POST", "/dispute", fixture: "error_invalid_message", status: 400)389        t.on("POST", "/dispute", fixture: "dispute_created")390        let m = makeModel(t)391        await m.start()392        XCTAssertEqual(m.step, .result(.rejected))393        XCTAssertTrue(m.canDispute)394        var ok = await m.dispute(message: "x")395        XCTAssertFalse(ok)396        XCTAssertEqual(m.lastError?.code, "invalid_message")397        ok = await m.dispute(message: "  My document is not expired.  ")398        XCTAssertTrue(ok)399        XCTAssertTrue(m.disputeSent)400        XCTAssertFalse(m.canDispute)401        XCTAssertEqual(try! JSONSerialization.jsonObject(with: t.requests.last!.httpBody!) as? [String: String], ["message": "My document is not expired."])402    }403404    func testChallengeErrorIsThrownAndRecorded() async {405        let t = MockTransport()406        t.on("GET", "/", fixture: "flow_live_awaiting_selfie")407        t.on("POST", "/selfie/challenge", status: 429, Data(#"{"error":{"type":"rate_limit_error","code":"too_many_challenges","message":"Too many."}}"#.utf8))408        t.on("POST", "/selfie", fixture: "error_invalid_challenge", status: 409)409        let m = makeModel(t)410        await m.start()411        XCTAssertEqual(m.step, .selfie)412        do { _ = try await m.requestChallenge(accessible: true); XCTFail() } catch {413            XCTAssertEqual((error as? IdentityError)?.code, "too_many_challenges")414        }415        XCTAssertEqual(m.lastError?.code, "too_many_challenges")416        let ok = await m.uploadSelfie(challengeID: "chl_x", frames: [jpeg])417        XCTAssertFalse(ok)418        XCTAssertEqual(m.lastError?.code, "invalid_challenge")419        XCTAssertEqual(m.step, .selfie)420    }421422    func testResumePositions() async {423        func step(_ data: Data) async -> FlowStep {424            let t = MockTransport()425            t.on("GET", "/", data)426            let m = makeModel(t)427            await m.start()428            m.stop()429            return m.step430        }431        var s = await step(Fixture.data("flow_awaiting_document"))432        XCTAssertEqual(s, .sandbox)433        s = await step(Fixture.data("flow_live_awaiting_selfie", patch: ["status": "awaiting_document", "uploaded": ["front": true], "method": "document_review"]))434        XCTAssertEqual(s, .documentBack)435        s = await step(Fixture.data("flow_live_awaiting_selfie"))436        XCTAssertEqual(s, .selfie)437        s = await step(Fixture.data("flow_sandbox_manual_review"))438        XCTAssertEqual(s, .result(.manualReview))439        s = await step(Fixture.data("flow_cancelled"))440        XCTAssertEqual(s, .result(.cancelled))441        s = await step(Fixture.data("flow_created", patch: ["status": "brand_new_status"]))442        XCTAssertEqual(s, .result(.unknown("brand_new_status")))443    }444}445
Files main
Menu

Theme