SPB Git

Repository Public

ClientTests.swift 15.6 KB 239 lines swift

1import CryptoKit2import Foundation3import XCTest4@testable import SPMailClient56/// Scripted answers for URLSession: no network. Each test installs its own queue.7final class StubProtocol: URLProtocol, @unchecked Sendable {8    struct Seen: Sendable { let method: String; let url: URL; let headers: [String: String]; let body: Data }9    typealias Answer = @Sendable (Seen) -> (Int, [String: String], Data)1011    private static let lock = NSLock()12    nonisolated(unsafe) private static var queue: [Answer] = []13    nonisolated(unsafe) private static var log: [Seen] = []1415    static func script(_ answers: [Answer]) { lock.withLock { queue = answers; log = [] } }16    static var seen: [Seen] { lock.withLock { log } }1718    override class func canInit(with request: URLRequest) -> Bool { true }19    override class func canonicalRequest(for request: URLRequest) -> URLRequest { request }20    override func stopLoading() {}21    override func startLoading() {22        var body = request.httpBody ?? Data()23        if let stream = request.httpBodyStream {24            stream.open()25            var buf = [UInt8](repeating: 0, count: 65536)26            while stream.hasBytesAvailable {27                let n = stream.read(&buf, maxLength: buf.count)28                if n <= 0 { break }29                body.append(buf, count: n)30            }31            stream.close()32        }33        let seen = Seen(method: request.httpMethod ?? "GET", url: request.url!, headers: request.allHTTPHeaderFields ?? [:], body: body)34        let answer: Answer? = Self.lock.withLock {35            Self.log.append(seen)36            return Self.queue.isEmpty ? nil : Self.queue.removeFirst()37        }38        guard let answer else {39            client?.urlProtocol(self, didFailWithError: URLError(.cannotConnectToHost))40            return41        }42        let (status, headers, data) = answer(seen)43        let res = HTTPURLResponse(url: request.url!, statusCode: status, httpVersion: "HTTP/1.1", headerFields: headers)!44        client?.urlProtocol(self, didReceive: res, cacheStoragePolicy: .notAllowed)45        client?.urlProtocol(self, didLoad: data)46        client?.urlProtocolDidFinishLoading(self)47    }48}4950func json(_ status: Int, _ body: String, _ headers: [String: String] = [:]) -> StubProtocol.Answer {51    { _ in (status, ["Content-Type": "application/json", "X-Request-Id": "req_test"].merging(headers) { $1 }, Data(body.utf8)) }52}53func apiError(_ status: Int, _ code: String, _ headers: [String: String] = [:]) -> StubProtocol.Answer {54    json(status, #"{"error":{"code":"\#(code)","message":"msg \#(code)","details":{"required":["mail.send"]}}}"#, headers)55}56let outboundJSON = #"{"id":"msg_out_1","status":"sent","from":"a@x.test","message_id":"msg_1","thread_id":"thr_1","recipients":[{"address":"b@x.test","status":"sent","smtp_reply":null}],"external":false,"send_at":null,"attempts":1,"last_error":null,"submitted_at":null,"final_at":null,"created_at":"2026-11-19T06:04:18.001Z","updated_at":"2026-11-19T06:04:18.120Z"}"#57let summaryJSON = #"{"id":"msg_1","thread_id":"thr_1","mailbox":"b@x.test","delivered_to":["b@x.test"],"folders":[{"id":"fld_1","role":"inbox","name":"Inbox"}],"from":[{"email":"a@x.test","name":null}],"to":[{"email":"b@x.test","name":"B"}],"cc":[],"subject":"Hello","preview":"Hi","received_at":"2026-11-19T06:04:18Z","sent_at":null,"size":3412,"unread":true,"starred":false,"draft":false,"answered":false,"forwarded":false,"has_attachment":false,"labels":[]}"#5859final class ClientTests: XCTestCase {60    func makeClient(maxRetries: Int = 2, key: String = "spm_unit_test") throws -> SPMailClient {61        let cfg = URLSessionConfiguration.ephemeral62        cfg.protocolClasses = [StubProtocol.self]63        return try SPMailClient(apiKey: key, baseURL: URL(string: "http://localhost:1")!, session: URLSession(configuration: cfg), maxRetries: maxRetries)64    }65    func object(_ data: Data) throws -> [String: Any] { try XCTUnwrap(JSONSerialization.jsonObject(with: data) as? [String: Any]) }6667    func testConfiguration() throws {68        XCTAssertThrowsError(try SPMailClient(apiKey: " "))69        XCTAssertThrowsError(try SPMailClient(apiKey: "spm_x", baseURL: URL(string: "http://mail.example.org")!))70        XCTAssertEqual(try SPMailClient(apiKey: "spm_x").baseURL.absoluteString, "https://mail.spboucher.ai/api/v1")71        XCTAssertEqual(try SPMailClient(apiKey: "spm_x", baseURL: URL(string: "https://h.example/api/v1/")!).baseURL.absoluteString, "https://h.example/api/v1")72        let c = try SPMailClient(apiKey: "spm_secretsecret_value")73        XCTAssertFalse("\(c)".contains("secretsecret"))74        XCTAssertFalse(String(reflecting: c).contains("secretsecret"))75    }7677    func testSendEncodesWireFormatAndGeneratesIdempotencyKey() async throws {78        StubProtocol.script([json(200, outboundJSON), json(200, outboundJSON)])79        let client = try makeClient()80        let sent = try await client.send(SendRequest(from: "a@x.test", to: ["b@x.test", Recipient("c@x.test", name: "C")], subject: "Hi", text: "Body",81                                                     attachments: [AttachmentRef(fileID: "file_1")], headers: ["X-App": "t"], priority: .high))82        XCTAssertEqual(sent.id, "msg_out_1")83        XCTAssertEqual(sent.status, .sent)84        XCTAssertEqual(sent.recipients.first?.address, "b@x.test")85        let first = StubProtocol.seen[0]86        XCTAssertEqual(first.method, "POST")87        XCTAssertEqual(first.url.absoluteString, "http://localhost:1/api/v1/messages/send")88        XCTAssertEqual(first.headers["Authorization"], "Bearer spm_unit_test")89        let key = try XCTUnwrap(first.headers["Idempotency-Key"])90        XCTAssertTrue(key.hasPrefix("swift-") && key.count == 42)91        let body = try object(first.body)92        XCTAssertEqual(body["from"] as? String, "a@x.test")93        XCTAssertEqual((body["to"] as? [[String: String]])?.map { $0["email"] }, ["b@x.test", "c@x.test"])94        XCTAssertEqual((body["attachments"] as? [[String: Any]])?.first?["file_id"] as? String, "file_1")95        XCTAssertEqual(body["priority"] as? String, "high")96        XCTAssertNil(body["template_id"])9798        // template: variable names are sent untouched (no snake_case rewriting of dictionary keys)99        _ = try await client.sendTemplate("tpl-1", from: "a@x.test", to: ["b@x.test"], variables: ["firstName": "Zoé", "action_url": "https://example.org"], idempotencyKey: "order-42")100        let second = StubProtocol.seen[1]101        XCTAssertEqual(second.headers["Idempotency-Key"], "order-42")102        let tpl = try object(second.body)103        XCTAssertEqual(tpl["template_id"] as? String, "tpl-1")104        XCTAssertEqual(tpl["variables"] as? [String: String], ["firstName": "Zoé", "action_url": "https://example.org"])105        XCTAssertNil(tpl["text"])106    }107108    func testPendingApprovalIsDecodedAndNeverFinal() async throws {109        let pending = outboundJSON.replacingOccurrences(of: #""status":"sent""#, with: #""status":"pending_approval","approval_id":"ap-1""#)110        StubProtocol.script([json(202, pending), json(200, pending), json(200, pending), json(200, pending)])111        let client = try makeClient()112        let r = try await client.send(SendRequest(from: "a@x.test", to: ["ext@example.org"], text: "x"))113        XCTAssertEqual(r.status, .pendingApproval)114        XCTAssertEqual(r.approvalID, "ap-1")115        XCTAssertFalse(r.status.isFinal)116        do {117            _ = try await client.waitForDelivery(r.id, timeout: 0.3, interval: 0.1)118            XCTFail("must time out")119        } catch SPMailError.deliveryTimeout(let last) {120            XCTAssertEqual(last.status, .pendingApproval)121        }122        // an unknown future status does not break decoding123        StubProtocol.script([json(200, outboundJSON.replacingOccurrences(of: #""status":"sent""#, with: #""status":"teleported""#))])124        let odd = try await client.deliveryStatus("msg_out_1")125        XCTAssertEqual(odd.status, .unknown)126    }127128    func testListGetReplyMarkReadUpload() async throws {129        let full = String(summaryJSON.dropLast()) + #","bcc":[],"reply_to":[],"message_id":"<1@x>","in_reply_to":[],"references":[],"headers":[],"text":"Hi there","html":null,"truncated":false,"attachments":[{"id":"att_1","name":"a.pdf","type":"application/pdf","size":10,"cid":null,"disposition":"attachment","inline":false}],"auth":{"spf":"pass","dkim":"pass","dmarc":"pass","raw":null}}"#130        StubProtocol.script([131            json(200, #"{"data":[\#(summaryJSON)],"next_cursor":"c1","has_more":true}"#),132            json(200, full), json(200, outboundJSON), json(200, summaryJSON.replacingOccurrences(of: #""unread":true"#, with: #""unread":false"#)),133            json(201, #"{"id":"file_9","name":"r.pdf","type":"application/pdf","size":3,"mailbox":"a@x.test","expires_at":"2026-11-20T06:00:00Z"}"#),134        ])135        let client = try makeClient()136        let page = try await client.listMessages(MessageQuery(address: "b+tag@x.test", folder: "inbox", unread: true, subject: "héllo wörld", limit: 5))137        XCTAssertEqual(page.data.map(\.id), ["msg_1"])138        XCTAssertEqual(page.nextCursor, "c1")139        XCTAssertTrue(page.hasMore)140        XCTAssertEqual(page.data[0].from.first?.email, "a@x.test")141        XCTAssertEqual(StubProtocol.seen[0].url.absoluteString, "http://localhost:1/api/v1/messages?address=b%2Btag@x.test&folder=inbox&unread=true&subject=h%C3%A9llo%20w%C3%B6rld&limit=5")142143        let message = try await client.getMessage("msg_1")144        XCTAssertEqual(message.text, "Hi there")145        XCTAssertEqual(message.attachments.first?.name, "a.pdf")146147        _ = try await client.reply(to: "msg_1", ReplyRequest(text: "ok", replyAll: true))148        XCTAssertEqual(StubProtocol.seen[2].url.path, "/api/v1/messages/msg_1/reply")149        XCTAssertNotNil(StubProtocol.seen[2].headers["Idempotency-Key"])150        XCTAssertEqual(try object(StubProtocol.seen[2].body)["reply_all"] as? Bool, true)151152        let read = try await client.markRead("msg_1")153        XCTAssertFalse(read.unread)154        XCTAssertEqual(StubProtocol.seen[3].method, "PATCH")155        XCTAssertEqual(try object(StubProtocol.seen[3].body)["unread"] as? Bool, false)156157        let file = try await client.uploadFile(Data([1, 2, 3]), filename: "r é.pdf", contentType: "application/pdf")158        XCTAssertEqual(file.id, "file_9")159        XCTAssertEqual(StubProtocol.seen[4].headers["Content-Type"], "application/pdf")160        XCTAssertEqual(StubProtocol.seen[4].body, Data([1, 2, 3]))161        XCTAssertNil(StubProtocol.seen[4].headers["Idempotency-Key"])162        XCTAssertEqual(StubProtocol.seen[4].url.query(percentEncoded: true), "filename=r%20%C3%A9.pdf")163    }164165    func testTypedErrors() async throws {166        let cases: [(Int, String, APIError.Kind)] = [(400, "invalid_request", .badRequest), (401, "invalid_api_key", .unauthorized), (403, "insufficient_scope", .forbidden),167                                                     (404, "not_found", .notFound), (409, "idempotency_conflict", .conflict), (429, "daily_send_limit_exceeded", .rateLimited), (500, "internal", .server)]168        for (status, code, kind) in cases {169            StubProtocol.script([apiError(status, code)])170            do {171                _ = try await makeClient(maxRetries: 0, key: "spm_secretsecret_value").getMessage("msg_x")172                XCTFail("must throw")173            } catch let SPMailError.api(e) {174                XCTAssertEqual(e.status, status)175                XCTAssertEqual(e.code, code)176                XCTAssertEqual(e.kind, kind)177                XCTAssertEqual(e.message, "msg \(code)")178                XCTAssertEqual(e.requestID, "req_test")179                XCTAssertEqual(e.detailsJSON, #"{"required":["mail.send"]}"#)180                XCTAssertFalse("\(SPMailError.api(e))".contains("secretsecret"))181            }182        }183        StubProtocol.script([json(200, #"{"unexpected":true}"#)])184        do { _ = try await makeClient().me(); XCTFail("must throw") } catch SPMailError.decoding { }185    }186187    func testRetriesAreSafe() async throws {188        // GET: 503 then success189        StubProtocol.script([apiError(503, "mail_server_unavailable"), json(200, summaryJSON)])190        _ = try await makeClient().markRead("msg_1")  // PATCH flags is repeatable191        XCTAssertEqual(StubProtocol.seen.count, 2)192        // 429 honours Retry-After193        StubProtocol.script([apiError(429, "rate_limited", ["Retry-After": "1"]), json(200, outboundJSON)])194        let t0 = Date()195        _ = try await makeClient().deliveryStatus("msg_out_1")196        XCTAssertGreaterThanOrEqual(Date().timeIntervalSince(t0), 1.0)197        // send: every attempt carries the same Idempotency-Key198        StubProtocol.script([apiError(502, "mail_server_error"), apiError(504, "x"), json(200, outboundJSON)])199        _ = try await makeClient().send(SendRequest(from: "a@x.test", to: ["b@x.test"], text: "x"))200        let keys = StubProtocol.seen.compactMap { $0.headers["Idempotency-Key"] }201        XCTAssertEqual(keys.count, 3)202        XCTAssertEqual(Set(keys).count, 1)203        // upload is not idempotent: never retried204        StubProtocol.script([apiError(503, "mail_server_unavailable"), json(201, "{}")])205        do { _ = try await makeClient().uploadFile(Data([1]), filename: "a"); XCTFail("must throw") } catch let SPMailError.api(e) { XCTAssertEqual(e.status, 503) }206        XCTAssertEqual(StubProtocol.seen.count, 1)207        // the daily limit is never retried208        StubProtocol.script([apiError(429, "daily_send_limit_exceeded", ["Retry-After": "1"]), json(200, outboundJSON)])209        do { _ = try await makeClient().send(SendRequest(from: "a@x.test", to: ["b@x.test"], text: "x")); XCTFail("must throw") } catch let SPMailError.api(e) { XCTAssertEqual(e.kind, .rateLimited) }210        XCTAssertEqual(StubProtocol.seen.count, 1)211        // network failure on a GET with no retry budget212        StubProtocol.script([])213        do { _ = try await makeClient(maxRetries: 0).me(); XCTFail("must throw") } catch SPMailError.transport { }214    }215216    func testWebhookSignature() throws {217        let secret = "whsec_test_secret"218        let payload = Data(#"{"id":"evt_1","type":"message.received","occurred_at":"2026-11-19T06:04:19.412Z","address":"a@x.test","mailbox":"a@x.test","data":{"message_id":"msg_1"}}"#.utf8)219        let now = Date()220        let header = SPMailWebhook.sign(payload: payload, secret: secret, timestamp: now)221        // same value as the reference algorithm of docs/API.md §11.4222        let t = String(Int(now.timeIntervalSince1970))223        let reference = HMAC<SHA256>.authenticationCode(for: Data("\(t).".utf8) + payload, using: SymmetricKey(data: Data(secret.utf8))).map { String(format: "%02x", $0) }.joined()224        XCTAssertEqual(header, "t=\(t),v1=\(reference)")225        XCTAssertTrue(SPMailWebhook.verify(payload: payload, header: header, secret: secret))226        XCTAssertFalse(SPMailWebhook.verify(payload: payload + Data(" ".utf8), header: header, secret: secret))227        XCTAssertFalse(SPMailWebhook.verify(payload: payload, header: header, secret: "whsec_other"))228        XCTAssertFalse(SPMailWebhook.verify(payload: payload, header: nil, secret: secret))229        XCTAssertFalse(SPMailWebhook.verify(payload: payload, header: "v1=abc", secret: secret))230        let old = SPMailWebhook.sign(payload: payload, secret: secret, timestamp: now.addingTimeInterval(-301))231        XCTAssertFalse(SPMailWebhook.verify(payload: payload, header: old, secret: secret))232        XCTAssertTrue(SPMailWebhook.verify(payload: payload, header: old, secret: secret, tolerance: 600))233        let event = try SPMailWebhook.constructEvent(payload: payload, header: header, secret: secret)234        XCTAssertEqual(event.type, "message.received")235        XCTAssertEqual(event.id, "evt_1")236        XCTAssertThrowsError(try SPMailWebhook.constructEvent(payload: payload, header: old, secret: secret))237    }238}239
Files main
Menu

Theme