SPB Git

Repository Public

SessionAndRequestTests.swift 11.4 KB 207 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/SessionAndRequestTests.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 MacLustrIdentityCore9091final class SessionAndRequestTests: XCTestCase {92    func testHostedURLParsing() throws {93        let s = try IdentitySession(urlString: "  https://identity.spboucher.ai/verify/vs_pdta67efg92yhybjqhz0#vsc_AbC-123_x \n")94        XCTAssertEqual(s.baseURL.absoluteString, "https://identity.spboucher.ai")95        XCTAssertEqual(s.id, "vs_pdta67efg92yhybjqhz0")96        XCTAssertEqual(s.clientSecret, "vsc_AbC-123_x")97        XCTAssertEqual(s.hostedURL.absoluteString, "https://identity.spboucher.ai/verify/vs_pdta67efg92yhybjqhz0#vsc_AbC-123_x")98        XCTAssertEqual(try IdentitySession(url: s.hostedURL), s)99    }100101    func testHostedURLFromCapturedSession() throws {102        struct Created: Decodable { let id: String; let url: String }103        let c = try Fixture.decode(Created.self, "session_created")104        let s = try IdentitySession(urlString: c.url)105        XCTAssertEqual(s.id, c.id)106        XCTAssertEqual(s.baseURL.absoluteString, "http://localhost:8872")107        XCTAssertEqual(s.clientSecret, "vsc_REDACTED")108    }109110    func testInvalidHostedURLs() {111        for bad in ["", "not a url", "https://identity.spboucher.ai/verify/vs_abc", "https://identity.spboucher.ai/verify/vs_abc#", "https://identity.spboucher.ai/verify/vs_abc#secret",112                    "https://identity.spboucher.ai/other/vs_abc#vsc_x", "https://identity.spboucher.ai/verify/abc#vsc_x", "https://identity.spboucher.ai/verify/vs_abc/extra#vsc_x",113                    "http://identity.spboucher.ai/verify/vs_abc#vsc_x", "ftp://localhost/verify/vs_abc#vsc_x", "https://user:pw@identity.spboucher.ai/verify/vs_abc#vsc_x",114                    "https://identity.spboucher.ai/verify/vs_a%2Fb#vsc_x", "https://identity.spboucher.ai/verify/vs_abc#vsc_x y"] {115            XCTAssertThrowsError(try IdentitySession(urlString: bad), bad) { XCTAssertEqual($0 as? IdentityError, .invalidSessionURL) }116        }117    }118119    func testPlainHTTPOnlyForLoopback() throws {120        XCTAssertNoThrow(try IdentitySession(baseURL: URL(string: "http://localhost:8875")!, sessionID: "vs_a", clientSecret: "vsc_b"))121        XCTAssertNoThrow(try IdentitySession(baseURL: URL(string: "http://127.0.0.1:8875/ignored/path")!, sessionID: "vs_a", clientSecret: "vsc_b"))122        XCTAssertThrowsError(try IdentitySession(baseURL: URL(string: "http://example.com")!, sessionID: "vs_a", clientSecret: "vsc_b"))123        XCTAssertThrowsError(try IdentitySession(sessionID: "vs_a", clientSecret: "mlid_sk_test_x"))124        XCTAssertEqual(try IdentitySession(sessionID: "vs_a", clientSecret: "vsc_b").baseURL.absoluteString, "https://identity.spboucher.ai")125    }126127    func testDescriptionNeverPrintsTheSecret() {128        XCTAssertFalse("\(testSession)".contains("secret456"))129        XCTAssertFalse(String(reflecting: testSession).contains("secret456"))130        XCTAssertFalse(String(describing: IdentityClient(session: testSession, transport: MockTransport()).session).contains("secret456"))131    }132133    func testMultipartEncoding() {134        var form = MultipartForm(boundary: "BOUNDARY")135        form.addField(name: "side", value: "front")136        form.addFile(name: "file", filename: "a\"b.jpg", contentType: "image/jpeg", data: Data([0xFF, 0xD8, 0xFF, 0x00, 0x0D, 0x0A]))137        let expected = "--BOUNDARY\r\nContent-Disposition: form-data; name=\"side\"\r\n\r\nfront\r\n"138            + "--BOUNDARY\r\nContent-Disposition: form-data; name=\"file\"; filename=\"a%22b.jpg\"\r\nContent-Type: image/jpeg\r\n\r\n"139        var bytes = Data(expected.utf8)140        bytes.append(Data([0xFF, 0xD8, 0xFF, 0x00, 0x0D, 0x0A]))141        bytes.append(Data("\r\n--BOUNDARY--\r\n".utf8))142        XCTAssertEqual(form.finalized(), bytes)143        XCTAssertEqual(form.contentType, "multipart/form-data; boundary=BOUNDARY")144        XCTAssertNotEqual(MultipartForm().boundary, MultipartForm().boundary)145    }146147    func testImageSniffing() {148        XCTAssertEqual(sniffImageContentType(Data([0xFF, 0xD8, 0xFF, 0xE0])), "image/jpeg")149        XCTAssertEqual(sniffImageContentType(Data([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A])), "image/png")150        XCTAssertEqual(sniffImageContentType(Data("RIFF0000WEBP".utf8)), "image/webp")151        XCTAssertNil(sniffImageContentType(Data("<html>".utf8)))152    }153154    func testRequestsCarryTheClientSecretAndNoCookies() async throws {155        let t = MockTransport()156        t.on("GET", "/", fixture: "flow_created")157        t.on("POST", "/consent", fixture: "flow_awaiting_document")158        t.on("POST", "/document", fixture: "document_accepted_front")159        t.on("POST", "/selfie/challenge", fixture: "challenge_accessible")160        t.on("POST", "/selfie", fixture: "selfie_accepted")161        t.on("POST", "/submit", fixture: "flow_live_processing")162        t.on("POST", "/sandbox", fixture: "flow_sandbox_verified")163        t.on("POST", "/withdraw", fixture: "withdraw")164        t.on("POST", "/dispute", fixture: "dispute_created")165        let c = IdentityClient(session: testSession, transport: t, retryPolicy: .none)166        _ = try await c.flowState()167        _ = try await c.consent(method: "document_selfie", textVersion: "2026-12-01.2", biometricConsent: true)168        _ = try await c.uploadDocument(side: .back, image: Data([0xFF, 0xD8, 0xFF, 0xD9]))169        _ = try await c.selfieChallenge(accessible: true)170        _ = try await c.uploadSelfie(challengeID: "chl_1", frames: [Data([0xFF, 0xD8, 0xFF, 1]), Data([0xFF, 0xD8, 0xFF, 2])])171        _ = try await c.submit()172        _ = try await c.sandbox(scenario: "verified")173        _ = try await c.withdraw()174        _ = try await c.dispute(message: "Not expired.")175        XCTAssertEqual(t.log, ["GET /", "POST /consent", "POST /document", "POST /selfie/challenge", "POST /selfie", "POST /submit", "POST /sandbox", "POST /withdraw", "POST /dispute"])176        for r in t.requests {177            XCTAssertEqual(r.value(forHTTPHeaderField: "Authorization"), "Bearer vsc_secret456")178            XCTAssertTrue(r.url!.absoluteString.hasPrefix("https://identity.example/v1/sessions/vs_test123"))179            XCTAssertFalse(r.httpShouldHandleCookies)180            XCTAssertNil(r.url!.fragment)181            XCTAssertNil(r.url!.query)182        }183        let consent = try JSONSerialization.jsonObject(with: t.requests[1].httpBody!) as! [String: Any]184        XCTAssertEqual(consent["method"] as? String, "document_selfie")185        XCTAssertEqual(consent["accepted"] as? Bool, true)186        XCTAssertEqual(consent["biometric_consent"] as? Bool, true)187        XCTAssertEqual(consent["text_version"] as? String, "2026-12-01.2")188        let doc = String(decoding: t.requests[2].httpBody!, as: UTF8.self)189        XCTAssertTrue(t.requests[2].value(forHTTPHeaderField: "Content-Type")!.hasPrefix("multipart/form-data; boundary=mlid-"))190        XCTAssertTrue(doc.contains("name=\"side\"\r\n\r\nback\r\n"))191        XCTAssertTrue(doc.contains("name=\"file\"; filename=\"back.jpg\"\r\nContent-Type: image/jpeg"))192        XCTAssertEqual(try JSONSerialization.jsonObject(with: t.requests[3].httpBody!) as? [String: Bool], ["accessible": true])193        let selfie = String(decoding: t.requests[4].httpBody!, as: UTF8.self)194        XCTAssertTrue(selfie.contains("name=\"challenge_id\"\r\n\r\nchl_1\r\n"))195        XCTAssertEqual(selfie.components(separatedBy: "name=\"frames\"; filename=\"f0").count - 1, 2)196        XCTAssertLessThan(selfie.range(of: "f00.jpg")!.lowerBound, selfie.range(of: "f01.jpg")!.lowerBound)197    }198199    func testNonBiometricConsentOmitsTheBiometricFlag() async throws {200        let t = MockTransport()201        t.on("POST", "/consent", fixture: "flow_awaiting_document")202        _ = try await IdentityClient(session: testSession, transport: t, retryPolicy: .none).consent(method: "document_review", textVersion: "v", biometricConsent: false)203        let body = try JSONSerialization.jsonObject(with: t.requests[0].httpBody!) as! [String: Any]204        XCTAssertNil(body["biometric_consent"])205    }206}207
Files main
Menu

Theme