Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : MacLustr SMS Gateway9// File : sdk/swift/Tests/MacLustrSMSTests/MacLustrSMSTests.swift10// Module : MacLustrSMSTests11// Repository : https://git.spboucher.ai/maclustr-sms12// Project Website : https://sms.spboucher.ai13// Created : 2026-11-3014// Last Modified : 2026-11-3015//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 CryptoKit89import XCTest90@testable import MacLustrSMS9192/// Transport simulé : réponses programmées, requêtes enregistrées.93final class StubProtocol: URLProtocol {94 struct Reply { let status: Int; let json: String; let headers: [String: String] }95 nonisolated(unsafe) static var script: [Reply] = []96 nonisolated(unsafe) static var seen: [(request: URLRequest, body: Data?)] = []97 static let lock = NSLock()9899 override class func canInit(with request: URLRequest) -> Bool { true }100 override class func canonicalRequest(for request: URLRequest) -> URLRequest { request }101 override func startLoading() {102 var body = request.httpBody103 if body == nil, let s = request.httpBodyStream {104 s.open(); var d = Data(); var buf = [UInt8](repeating: 0, count: 4096)105 while s.hasBytesAvailable { let n = s.read(&buf, maxLength: buf.count); if n <= 0 { break }; d.append(buf, count: n) }106 s.close(); body = d107 }108 StubProtocol.lock.lock()109 StubProtocol.seen.append((request, body))110 let r = StubProtocol.script.isEmpty ? Reply(status: 200, json: "{}", headers: [:]) : StubProtocol.script.removeFirst()111 StubProtocol.lock.unlock()112 if r.status == 0 { client?.urlProtocol(self, didFailWithError: URLError(.cannotConnectToHost)); return }113 let res = HTTPURLResponse(url: request.url!, statusCode: r.status, httpVersion: "HTTP/1.1", headerFields: r.headers.merging(["Content-Type": "application/json"]) { a, _ in a })!114 client?.urlProtocol(self, didReceive: res, cacheStoragePolicy: .notAllowed)115 client?.urlProtocol(self, didLoad: Data(r.json.utf8))116 client?.urlProtocolDidFinishLoading(self)117 }118 override func stopLoading() {}119}120121final class Slept: @unchecked Sendable { var values: [TimeInterval] = []; let lock = NSLock(); func add(_ v: TimeInterval) { lock.lock(); values.append(v); lock.unlock() } }122123final class UnitTests: XCTestCase {124 let msg = #"{"id":"sms_1","direction":"outbound","status":"queued","to":"+14185550123","from":"+14185550124","text":"x","segments":1,"device_id":"android-01","champ_futur":1}"#125 var slept = Slept()126127 func client(_ script: [StubProtocol.Reply]) -> MacLustrSMS {128 StubProtocol.script = script; StubProtocol.seen = []129 let cfg = URLSessionConfiguration.ephemeral130 cfg.protocolClasses = [StubProtocol.self]131 slept = Slept()132 let s = slept133 return MacLustrSMS(apiKey: "mlsk_test", baseURL: URL(string: "http://stub")!, session: URLSession(configuration: cfg), sleep: { s.add($0) })134 }135 func r(_ status: Int, _ json: String, _ h: [String: String] = [:]) -> StubProtocol.Reply { .init(status: status, json: json, headers: h) }136137 func testSend() async throws {138 let sms = client([r(201, msg)])139 let m = try await sms.send(to: "+14185550123", text: "x", simId: "sim-1", from: "+14185550124")140 XCTAssertEqual(m.id, "sms_1"); XCTAssertEqual(m.status, "queued"); XCTAssertEqual(m.from, "+14185550124"); XCTAssertEqual(m.deviceId, "android-01"); XCTAssertFalse(m.replayed)141 let (req, body) = StubProtocol.seen[0]142 XCTAssertEqual(req.url?.absoluteString, "http://stub/v1/messages")143 XCTAssertEqual(req.value(forHTTPHeaderField: "Authorization"), "Bearer mlsk_test")144 XCTAssertEqual(req.value(forHTTPHeaderField: "Idempotency-Key")?.count, 36)145 let j = try JSONSerialization.jsonObject(with: body!) as! [String: String]146 XCTAssertEqual(j, ["to": "+14185550123", "text": "x", "sim_id": "sim-1", "from": "+14185550124"])147 }148 func testRetriesReuseTheSameIdempotencyKey() async throws {149 let sms = client([r(0, ""), r(503, #"{"error":{"code":"kill_switch_active","message":"x"}}"#), r(429, #"{"error":{"code":"rate_limited","message":"x"}}"#, ["Retry-After": "7"]), r(200, msg, ["Idempotent-Replayed": "true"])])150 let m = try await sms.send(to: "+14185550123", text: "x")151 XCTAssertTrue(m.replayed)152 XCTAssertEqual(StubProtocol.seen.count, 4)153 XCTAssertEqual(Set(StubProtocol.seen.map { $0.request.value(forHTTPHeaderField: "Idempotency-Key") }).count, 1)154 XCTAssertEqual(slept.values, [0.5, 1.0, 7.0])155 }156 func testNoRetryOnClientError() async throws {157 let sms = client([r(422, #"{"error":{"code":"invalid_phone_number","message":"numéro invalide","details":[1]}}"#)])158 do { _ = try await sms.send(to: "123", text: "x"); XCTFail("devait échouer") }159 catch let e as MacLustrSMSError { XCTAssertEqual(e.status, 422); XCTAssertEqual(e.code, "invalid_phone_number"); XCTAssertEqual(e.message, "numéro invalide"); XCTAssertEqual(e.details, .array([.number(1)])) }160 XCTAssertEqual(StubProtocol.seen.count, 1)161 }162 func testGivesUpAndNetworkError() async throws {163 var sms = client(Array(repeating: r(500, "{}"), count: 4))164 do { _ = try await sms.getMessage("sms_1"); XCTFail() } catch let e as MacLustrSMSError { XCTAssertEqual(e.status, 500) }165 XCTAssertEqual(StubProtocol.seen.count, 4)166 sms = client(Array(repeating: r(0, ""), count: 4))167 do { _ = try await sms.queue(); XCTFail() } catch let e as MacLustrSMSError { XCTAssertEqual(e.status, 0); XCTAssertEqual(e.code, "network_error") }168 }169 func testPaginationAndQueryEncoding() async throws {170 let a = msg.replacingOccurrences(of: "sms_1", with: "a"), b = msg.replacingOccurrences(of: "sms_1", with: "b")171 let sms = client([r(200, #"{"data":[\#(a)],"has_more":true,"next_cursor":"c1"}"#), r(200, #"{"data":[\#(b)],"has_more":false,"next_cursor":null}"#)])172 let all = try await sms.allMessages(to: "+14185550123", pageSize: 1)173 XCTAssertEqual(all.map(\.id), ["a", "b"])174 XCTAssertEqual(StubProtocol.seen[1].request.url?.query, "cursor=c1&limit=1&to=%2B14185550123")175 }176 func testWait() async throws {177 var sms = client([r(200, msg.replacingOccurrences(of: "queued", with: "dispatched")), r(200, msg.replacingOccurrences(of: "queued", with: "submitted"))])178 let s = try await sms.wait("sms_1")179 XCTAssertEqual(s.status, "submitted")180 sms = client([r(200, msg.replacingOccurrences(of: "queued", with: "submitted")), r(200, msg.replacingOccurrences(of: "queued", with: "delivered"))])181 let d = try await sms.wait("sms_1", until: .final)182 XCTAssertEqual(d.status, "delivered")183 sms = client([r(200, msg)])184 do { _ = try await sms.wait("sms_1", timeout: 0.5); XCTFail() } catch let e as MacLustrSMSError { XCTAssertEqual(e.code, "wait_timeout"); XCTAssertEqual(e.lastMessage?.status, "queued") }185 }186 func testHealthHasNoAuthorizationHeader() async throws {187 let sms = client([r(200, #"{"status":"ok","version":"1.0.0","time":"2026-11-30T22:00:00.000Z"}"#)])188 let h = try await sms.health()189 XCTAssertEqual(h.status, "ok")190 XCTAssertNil(StubProtocol.seen[0].request.value(forHTTPHeaderField: "Authorization"))191 }192 func testVerificationIsNeverRetried() async throws {193 let ver = #"{"id":"ver_1","to":"+14185550123","status":"pending","attempts":0,"attempts_remaining":5,"message_id":"sms_1","message_status":"queued"}"#194 var sms = client([r(201, ver)])195 let v = try await sms.startVerification(to: "+14185550123", brand: "Lou-Ka", locale: "fr")196 XCTAssertEqual(v.id, "ver_1"); XCTAssertEqual(v.attemptsRemaining, 5); XCTAssertEqual(v.messageStatus, "queued")197 XCTAssertNil(StubProtocol.seen[0].request.value(forHTTPHeaderField: "Idempotency-Key"))198 XCTAssertEqual(try JSONSerialization.jsonObject(with: StubProtocol.seen[0].body!) as? [String: String], ["to": "+14185550123", "brand": "Lou-Ka", "locale": "fr"])199 for first in [r(503, "{}"), r(0, "")] {200 sms = client([first, r(201, ver)])201 do { _ = try await sms.startVerification(to: "+14185550123"); XCTFail() } catch {}202 XCTAssertEqual(StubProtocol.seen.count, 1)203 }204 sms = client([r(429, #"{"error":{"code":"verification_too_soon","message":"x"}}"#, ["Retry-After": "27"]), r(201, ver)])205 do { _ = try await sms.startVerification(to: "+14185550123"); XCTFail() }206 catch let e as MacLustrSMSError { XCTAssertEqual(e.code, "verification_too_soon"); XCTAssertEqual(e.retryAfter, 27) }207 XCTAssertEqual(StubProtocol.seen.count, 1)208 let ok = ver.replacingOccurrences(of: "pending", with: "approved").replacingOccurrences(of: "}", with: #","valid":true}"#)209 sms = client([r(500, "{}"), r(200, ok)])210 do { _ = try await sms.checkVerification(id: "ver_1", code: "123456"); XCTFail() } catch {}211 XCTAssertEqual(StubProtocol.seen.count, 1)212 sms = client([r(200, ok)])213 let c = try await sms.checkVerification(id: "ver_1", code: "123456")214 XCTAssertTrue(c.valid); XCTAssertEqual(StubProtocol.seen[0].request.url?.path, "/v1/verifications/ver_1/check")215 sms = client([r(500, "{}"), r(200, ver)])216 let g = try await sms.verification(id: "ver_1")217 XCTAssertEqual(g.status, "pending"); XCTAssertEqual(StubProtocol.seen.count, 2)218 }219 func testVerifyWebhook() throws {220 let body = Data(#"{"event":"sms.received","id":"evt_1","created_at":"2026-11-30T22:00:00.000Z","data":{"text":"é","from":"+14185550123"}}"#.utf8), secret = "whsec_x"221 func sign(_ ts: Int, _ b: Data) -> String { "v1=" + HMAC<SHA256>.authenticationCode(for: Data("\(ts).".utf8) + b, using: SymmetricKey(data: Data(secret.utf8))).map { String(format: "%02x", $0) }.joined() }222 let ts = Int(Date().timeIntervalSince1970)223 let ev = try MacLustrSMS.verifyWebhook(secret: secret, timestamp: String(ts), body: body, signature: sign(ts, body))224 XCTAssertEqual(ev.event, "sms.received"); XCTAssertEqual(ev.id, "evt_1"); XCTAssertEqual(ev.data["text"]?.stringValue, "é")225 XCTAssertThrowsError(try MacLustrSMS.verifyWebhook(secret: "autre", timestamp: String(ts), body: body, signature: sign(ts, body))) { XCTAssertEqual($0 as? WebhookVerificationError, .invalidSignature) }226 XCTAssertThrowsError(try MacLustrSMS.verifyWebhook(secret: secret, timestamp: String(ts), body: body + Data(" ".utf8), signature: sign(ts, body)))227 XCTAssertThrowsError(try MacLustrSMS.verifyWebhook(secret: secret, timestamp: String(ts), body: body, signature: "v1=00"))228 XCTAssertThrowsError(try MacLustrSMS.verifyWebhook(secret: secret, timestamp: String(ts), body: body, signature: nil))229 XCTAssertThrowsError(try MacLustrSMS.verifyWebhook(secret: secret, timestamp: "abc", body: body, signature: sign(ts, body))) { XCTAssertEqual($0 as? WebhookVerificationError, .invalidTimestamp) }230 let old = ts - 301231 XCTAssertThrowsError(try MacLustrSMS.verifyWebhook(secret: secret, timestamp: String(old), body: body, signature: sign(old, body))) { XCTAssertEqual($0 as? WebhookVerificationError, .timestampOutOfTolerance) }232 XCTAssertNoThrow(try MacLustrSMS.verifyWebhook(secret: secret, timestamp: String(old), body: body, signature: sign(old, body), tolerance: 600))233 }234}235236/// Contre un vrai backend ; le téléphone est SIMULÉ (aucun SMS réel n'est émis). Lancé par sdk/tests-e2e/run.mjs.237final class EndToEndTests: XCTestCase {238 struct Hit: Decodable { let headers: [String: String]; let body: String }239240 func testScenario() async throws {241 let env = ProcessInfo.processInfo.environment242 try XCTSkipUnless(env["MACLUSTR_SMS_E2E"] == "1", "bout en bout : lancer sdk/tests-e2e/run.mjs")243 let sms = MacLustrSMS(), control = env["E2E_CONTROL"]!, to = env["E2E_TO"]!244 let h = try await sms.health()245 XCTAssertEqual(h.status, "ok")246 let hook = try await sms.createWebhook(url: control + "/hook", events: ["sms.delivered", "sms.received"], description: "swift-e2e")247 let secret = try XCTUnwrap(hook.secret)248 XCTAssertTrue(secret.hasPrefix("whsec_"))249 do {250 let m = try await sms.send(to: to, text: "Notification MacLustr (swift)", idempotencyKey: "swift-e2e-1")251 let again = try await sms.send(to: to, text: "Notification MacLustr (swift)", idempotencyKey: "swift-e2e-1")252 XCTAssertEqual(again.id, m.id); XCTAssertTrue(again.replayed)253 let done = try await sms.wait(m.id, timeout: 20, until: .final, interval: 0.2)254 XCTAssertEqual(done.status, "delivered")255 XCTAssertEqual(done.events?.last(where: { $0.detail?["ignored"] == nil })?.to, "delivered")256257 for (num, status, code) in [("12345", 422, "invalid_phone_number"), ("+15145550111", 403, "recipient_not_allowed")] {258 do { _ = try await sms.send(to: num, text: "x"); XCTFail("devait échouer") }259 catch let e as MacLustrSMSError { XCTAssertEqual(e.status, status); XCTAssertEqual(e.code, code) }260 }261 do { _ = try await sms.cancel(m.id); XCTFail() } catch let e as MacLustrSMSError { XCTAssertEqual(e.code, "not_cancellable") }262263 for i in 0..<2 { try await sms.send(to: to, text: "page \(i) (swift)") }264 let page = try await sms.listMessages(limit: 2)265 XCTAssertEqual(page.data.count, 2); XCTAssertTrue(page.hasMore)266 let ids = try await sms.allMessages(pageSize: 2).map(\.id)267 XCTAssertTrue(ids.count >= 3 && Set(ids).count == ids.count && ids.contains(m.id))268269 let text = "Réponse swift \(Date().timeIntervalSince1970)"270 var rq = URLRequest(url: URL(string: control + "/receive")!)271 rq.httpMethod = "POST"; rq.setValue("application/json", forHTTPHeaderField: "Content-Type")272 rq.httpBody = try JSONSerialization.data(withJSONObject: ["from": to, "text": text])273 _ = try await URLSession.shared.data(for: rq)274 var got: Message?275 for _ in 0..<50 where got == nil {276 got = try await sms.inbox(from: to, limit: 20).data.first { $0.text == text }277 if got == nil { try await Task.sleep(nanoseconds: 100_000_000) }278 }279 let inbound = try XCTUnwrap(got)280 XCTAssertEqual(inbound.status, "received"); XCTAssertEqual(inbound.from, to)281 let convs = try await sms.conversations()282 let conv = try XCTUnwrap(convs.data.first { $0.peer == to })283 let thread = try await sms.conversationMessages(conv.id)284 XCTAssertTrue(thread.data.contains { $0.id == inbound.id })285286 // Vérification par code : le code n'est lisible que dans le SMS (ici : celui reçu par l'appareil simulé).287 let vto = env["E2E_VERIFY_TO"]!288 let v = try await sms.startVerification(to: vto, brand: "Tests SDK", locale: "fr")289 XCTAssertEqual(v.status, "pending"); XCTAssertEqual(v.attemptsRemaining, 5)290 do { _ = try await sms.startVerification(to: vto); XCTFail("devait échouer") }291 catch let e as MacLustrSMSError { XCTAssertEqual(e.status, 429); XCTAssertEqual(e.code, "verification_too_soon"); XCTAssertTrue((e.retryAfter ?? 0) > 0 && (e.retryAfter ?? 99) <= 30) }292 var cc = URLComponents(string: control + "/code")!293 cc.percentEncodedQuery = "to=" + vto.replacingOccurrences(of: "+", with: "%2B")294 let (cd, _) = try await URLSession.shared.data(from: cc.url!)295 let code = try XCTUnwrap((try JSONSerialization.jsonObject(with: cd) as? [String: String])?["code"])296 let bad = try await sms.checkVerification(id: v.id, code: String(format: "%06d", (Int(code)! + 1) % 1_000_000))297 XCTAssertFalse(bad.valid); XCTAssertEqual(bad.attemptsRemaining, 4)298 let good = try await sms.checkVerification(id: v.id, code: code)299 XCTAssertTrue(good.valid); XCTAssertEqual(good.status, "approved")300 let again2 = try await sms.checkVerification(id: v.id, code: code)301 XCTAssertFalse(again2.valid)302 let st = try await sms.verification(id: v.id)303 XCTAssertEqual(st.status, "approved")304305 let devs = try await sms.devices()306 let dev = try XCTUnwrap(devs.first)307 XCTAssertTrue(dev.online && dev.sims[0].sendEnabled)308 let one = try await sms.device(dev.id); XCTAssertEqual(one.id, dev.id)309 let sims = try await sms.sims(deviceId: dev.id); XCTAssertEqual(sims[0].id, dev.sims[0].id)310 let nums = try await sms.numbers(); XCTAssertEqual(nums[0].simId, dev.sims[0].id)311 let usage = try await sms.usage(); XCTAssertGreaterThanOrEqual(usage.quota.usedToday, 3)312 let q = try await sms.queue(); XCTAssertGreaterThanOrEqual(q.pending, 0)313314 var mine: [WebhookEvent] = []315 for _ in 0..<80 {316 let (data, _) = try await URLSession.shared.data(from: URL(string: control + "/hits")!)317 mine = try JSONDecoder().decode([Hit].self, from: data).compactMap {318 // une livraison signée avec un autre secret appartient au webhook d'un autre SDK319 try? MacLustrSMS.verifyWebhook(secret: secret, timestamp: $0.headers["x-maclustr-timestamp"], body: Data($0.body.utf8), signature: $0.headers["x-maclustr-signature"])320 }321 if mine.contains(where: { $0.event == "sms.delivered" }) && mine.contains(where: { $0.event == "sms.received" && $0.data["text"]?.stringValue == text }) { break }322 try await Task.sleep(nanoseconds: 100_000_000)323 }324 XCTAssertTrue(mine.contains { $0.event == "sms.delivered" && $0.data["id"]?.stringValue == m.id })325 XCTAssertTrue(mine.contains { $0.event == "sms.received" && $0.data["text"]?.stringValue == text })326 let hooks = try await sms.listWebhooks()327 XCTAssertTrue(hooks.contains { $0.id == hook.id })328 } catch { _ = try? await sms.deleteWebhook(hook.id); throw error }329 let deleted = try await sms.deleteWebhook(hook.id)330 XCTAssertTrue(deleted)331 }332}333