Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : MacLustr Identity9// File : sdk/swift/Tests/MacLustrIdentityCoreTests/IntegrationTests.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/// End-to-end tests against a local backend. Skipped unless MLID_TEST_BASE_URL and MLID_TEST_API_KEY are set.92/// MLID_TEST_API_KEY must be a sandbox key (`mlid_sk_test_…`); optional MLID_TEST_LIVE_API_KEY (dev database with93/// open compliance gates) and MLID_TEST_FIXTURES (path to tests/fixtures) enable the upload test.94@MainActor95final class IntegrationTests: XCTestCase {96 /// Test-only helper standing in for the integrating app's backend. A mobile app never holds an API key:97 /// this is deliberately not part of the SDK.98 private func createSession(key: String, policy: String? = nil) async throws -> IdentitySession {99 let base = ProcessInfo.processInfo.environment["MLID_TEST_BASE_URL"]!100 var req = URLRequest(url: URL(string: base + "/v1/verification-sessions")!)101 req.httpMethod = "POST"102 req.setValue("Bearer " + key, forHTTPHeaderField: "Authorization")103 req.setValue("application/json", forHTTPHeaderField: "Content-Type")104 var body: [String: Any] = ["purpose": "sdk_integration_test", "external_user_id": "swift_" + UUID().uuidString.prefix(8), "locale": "en-CA"]105 if let policy { body["verification_policy"] = policy }106 req.httpBody = try JSONSerialization.data(withJSONObject: body)107 let (data, response) = try await URLSession.shared.data(for: req)108 XCTAssertEqual((response as? HTTPURLResponse)?.statusCode, 200, String(decoding: data, as: UTF8.self))109 struct Created: Decodable { let id: String; let client_secret: String; let url: String }110 let c = try JSONDecoder().decode(Created.self, from: data)111 let session = try IdentitySession(urlString: c.url)112 XCTAssertEqual(session.id, c.id)113 XCTAssertEqual(session.clientSecret, c.client_secret)114 return session115 }116117 private func env(_ name: String) throws -> String {118 guard let v = ProcessInfo.processInfo.environment[name], !v.isEmpty else { throw XCTSkip("\(name) is not set") }119 return v120 }121122 private func wait(_ m: VerificationFlowModel, until: (FlowStep) -> Bool) async {123 for _ in 0..<600 { if until(m.step) { return }; try? await Task.sleep(nanoseconds: 50_000_000) }124 }125126 func testSandboxSessionReachesVerified() async throws {127 _ = try env("MLID_TEST_BASE_URL")128 let session = try await createSession(key: try env("MLID_TEST_API_KEY"))129 let m = VerificationFlowModel(client: IdentityClient(session: session))130 await m.start()131 XCTAssertEqual(m.step, .intro)132 XCTAssertEqual(m.language, .en)133 XCTAssertTrue(m.isSandbox)134 m.continueFromIntro()135 XCTAssertEqual(m.step, .method)136 m.selectMethod("document_selfie")137 await m.acceptConsent()138 XCTAssertEqual(m.step, .sandbox)139 // The sandbox never accepts images.140 do { _ = try await m.client.uploadDocument(side: .front, image: Data([0xFF, 0xD8, 0xFF, 0xD9])); XCTFail("upload accepted") } catch {141 XCTAssertEqual((error as? IdentityError)?.code, "sandbox_no_real_documents")142 }143 // The flow state of the current service: consent version echoed as received, new fields present.144 let version = try XCTUnwrap(m.methods.first?.consentText(.en)?.version)145 XCTAssertFalse(version.isEmpty)146 XCTAssertEqual(m.state?.maxAttempts, 3)147 XCTAssertEqual(m.state?.lastIssue, [])148 XCTAssertEqual(m.state?.document.front, "required")149 XCTAssertFalse(m.state?.document.backRequiredFor.isEmpty ?? true)150 await m.runSandboxScenario("verified")151 XCTAssertEqual(m.step, .result(.verified))152 XCTAssertEqual(m.state?.result?.reasons.first?.code, "simulated")153 XCTAssertEqual(m.resultForDismissal, .completed(status: .verified))154 }155156 func testSandboxRejectedThenDispute() async throws {157 _ = try env("MLID_TEST_BASE_URL")158 let session = try await createSession(key: try env("MLID_TEST_API_KEY"))159 let m = VerificationFlowModel(client: IdentityClient(session: session))160 await m.start()161 m.continueFromIntro()162 m.selectMethod("document_review")163 await m.acceptConsent()164 await m.runSandboxScenario("rejected")165 XCTAssertEqual(m.step, .result(.rejected))166 XCTAssertTrue(m.canDispute)167 let ok = await m.dispute(message: "Integration test dispute.")168 XCTAssertTrue(ok)169 // A second dispute (retry after a lost answer) is answered `dispute_exists`: still reported as sent.170 do { _ = try await m.client.dispute(message: "Integration test dispute."); XCTFail("second dispute accepted") } catch {171 XCTAssertEqual((error as? IdentityError)?.code, "dispute_exists")172 }173 }174175 /// Withdrawal is allowed while a person reviews the file; afterwards every action finds the session closed.176 func testWithdrawDuringManualReviewThenLateActions() async throws {177 _ = try env("MLID_TEST_BASE_URL")178 let session = try await createSession(key: try env("MLID_TEST_API_KEY"))179 let m = VerificationFlowModel(client: IdentityClient(session: session))180 await m.start()181 m.continueFromIntro()182 m.selectMethod("document_review")183 await m.acceptConsent()184 await m.runSandboxScenario("manual_review")185 XCTAssertEqual(m.step, .result(.manualReview))186 XCTAssertTrue(m.canWithdraw)187 await m.withdraw()188 XCTAssertEqual(m.step, .result(.cancelled))189 XCTAssertEqual(m.resultForDismissal, .canceled)190 // A second device still showing the session: its actions resynchronise on the closed session, without error loops.191 let other = VerificationFlowModel(client: IdentityClient(session: session))192 await other.start()193 XCTAssertEqual(other.step, .result(.cancelled))194 await other.withdraw()195 XCTAssertEqual(other.step, .result(.cancelled))196 do { _ = try await other.client.submit(); XCTFail("submit accepted") } catch {197 XCTAssertTrue((error as? IdentityError)?.isSessionStateConflict == true, "\(error)")198 }199 }200201 /// An oversized body is refused before it is read, with the normalised 413.202 func testPayloadTooLarge() async throws {203 _ = try env("MLID_TEST_BASE_URL")204 let session = try await createSession(key: try env("MLID_TEST_API_KEY"))205 let c = IdentityClient(session: session)206 do { _ = try await c.dispute(message: String(repeating: "x", count: 300 * 1024)); XCTFail("accepted") } catch {207 guard case .api(let e)? = error as? IdentityError else { return XCTFail("\(error)") }208 XCTAssertEqual(e.status, 413)209 XCTAssertEqual(e.code, "payload_too_large")210 XCTAssertFalse(IdentityError.api(e).isRetryable)211 }212 }213214 func testWithdrawAndInvalidSecret() async throws {215 _ = try env("MLID_TEST_BASE_URL")216 let session = try await createSession(key: try env("MLID_TEST_API_KEY"))217 let m = VerificationFlowModel(client: IdentityClient(session: session))218 await m.start()219 m.continueFromIntro()220 m.selectMethod("document_review")221 await m.acceptConsent()222 await m.withdraw()223 XCTAssertEqual(m.step, .result(.cancelled))224 XCTAssertEqual(m.resultForDismissal, .canceled)225 let bad = VerificationFlowModel(client: IdentityClient(session: try IdentitySession(baseURL: session.baseURL, sessionID: session.id, clientSecret: "vsc_wrong")))226 await bad.start()227 guard case .failed(let e) = bad.step else { return XCTFail("\(bad.step)") }228 XCTAssertEqual(e.code, "invalid_client_secret")229 }230231 /// Live mode on a development database: real multipart uploads of the fictional fixture documents.232 func testLiveUploadsUntilProcessing() async throws {233 _ = try env("MLID_TEST_BASE_URL")234 let fixtures = URL(fileURLWithPath: try env("MLID_TEST_FIXTURES"))235 let session = try await createSession(key: try env("MLID_TEST_LIVE_API_KEY"))236 let m = VerificationFlowModel(client: IdentityClient(session: session))237 m.pollInitialDelay = 0.2238 await m.start()239 XCTAssertFalse(m.isSandbox)240 m.continueFromIntro()241 m.selectMethod("document_selfie")242 await m.acceptConsent()243 XCTAssertEqual(m.step, .documentFront)244 let notAnImage = await m.uploadDocument(side: .front, image: Data("<html>".utf8))245 XCTAssertEqual(notAnImage, .failed)246 XCTAssertEqual(m.lastError?.code, "unsupported_file_type")247 let front = await m.uploadDocument(side: .front, image: try Data(contentsOf: fixtures.appendingPathComponent("licence_front_scene.jpg")))248 XCTAssertEqual(front, .accepted)249 var back = await m.uploadDocument(side: .back, image: try Data(contentsOf: fixtures.appendingPathComponent("licence_back_scene.jpg")))250 XCTAssertEqual(back, .accepted)251 XCTAssertEqual(m.step, .selfie)252 // The method can be changed while the selfie is awaited: the service destroys the uploads and the capture restarts.253 XCTAssertTrue(m.canChangeMethod)254 m.changeMethod()255 m.selectMethod("document_review")256 await m.acceptConsent()257 XCTAssertEqual(m.step, .documentFront, "\(String(describing: m.lastError))")258 XCTAssertEqual(m.state?.method, "document_review")259 XCTAssertEqual(m.state?.uploaded, [:])260 // …and back to the method with a selfie.261 m.changeMethod()262 m.selectMethod("document_selfie")263 await m.acceptConsent()264 XCTAssertEqual(m.step, .documentFront)265 let again = await m.uploadDocument(side: .front, image: try Data(contentsOf: fixtures.appendingPathComponent("licence_front_scene.jpg")))266 XCTAssertEqual(again, .accepted)267 back = await m.uploadDocument(side: .back, image: try Data(contentsOf: fixtures.appendingPathComponent("licence_back_scene.jpg")))268 XCTAssertEqual(back, .accepted)269 XCTAssertEqual(m.step, .selfie)270 let accessible = try await m.requestChallenge(accessible: true)271 XCTAssertEqual(accessible.frames.min, 3) // three frames are enough for the accessible alternative272 XCTAssertTrue(accessible.steps.isEmpty)273 let challenge = try await m.requestChallenge(accessible: false)274 XCTAssertEqual(challenge.steps.count, 2)275 XCTAssertEqual(challenge.frames.min, 8)276 let frame = try Data(contentsOf: fixtures.appendingPathComponent("a2.jpg"))277 let ok = await m.uploadSelfie(challengeID: challenge.challengeID, frames: Array(repeating: frame, count: challenge.frames.min))278 XCTAssertTrue(ok, "\(String(describing: m.lastError))")279 XCTAssertEqual(m.step, .processing) // no worker runs in this setup: the session stays in analysis280 XCTAssertEqual(m.resultForDismissal, .completed(status: .processing))281 await m.withdraw() // clean up: destroys the uploaded fixtures282 XCTAssertEqual(m.step, .result(.cancelled))283 }284}285