Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: SPChat/Tests/CoreTests/NetworkingTests.swift3// Description: API client behaviour: cookies in the secret store, Origin header, error mapping, locked sessions, re-authentication retry, uploads.4import Foundation5import Testing6@testable import SPChatCore78@Suite struct CookieJarTests {9 @Test func splitsMergedSetCookieHeaders() {10 let h = "__Host-csa_ceremony=abc; Path=/; Expires=Wed, 18 Nov 2026 03:33:26 GMT; Max-Age=300; HttpOnly; SameSite=strict, __Host-csa_session=tok; Path=/; Expires=Fri, 18 Dec 2026 03:33:26 GMT; HttpOnly"11 #expect(CookieJar.split(h).count == 2)12 }1314 @Test func sessionCookieLivesInTheSecretStoreOnly() {15 let secrets = InMemorySecretStore()16 let jar = CookieJar(store: secrets, host: "chat.spboucher.ai")17 #expect(!jar.hasSession)18 jar.ingest(setCookie: "__Host-csa_ceremony=cer; Path=/; Max-Age=300, __Host-csa_session=tok123; Path=/; Max-Age=2592000; HttpOnly; Secure, other=1; Path=/")19 #expect(jar.hasSession); #expect(jar.header == "__Host-csa_ceremony=cer; __Host-csa_session=tok123") // foreign cookies are ignored20 #expect(secrets.read("session@chat.spboucher.ai") == "__Host-csa_session=tok123")21 // a new jar (next launch) restores the session, not the ceremony cookie22 let relaunched = CookieJar(store: secrets, host: "chat.spboucher.ai")23 #expect(relaunched.header == "__Host-csa_session=tok123")24 // rotation replaces the token; expiry removes it everywhere25 jar.ingest(setCookie: "__Host-csa_session=tok456; Path=/; Max-Age=2592000")26 #expect(secrets.read("session@chat.spboucher.ai") == "__Host-csa_session=tok456")27 jar.ingest(setCookie: "__Host-csa_session=; Path=/; Max-Age=0, __Host-csa_ceremony=; Path=/; Max-Age=0")28 #expect(!jar.hasSession); #expect(jar.header == nil); #expect(secrets.isEmpty)29 }30}3132@Suite struct ServerConfigurationTests {33 @Test func httpsOnlyExceptLoopback() {34 #expect(ServerConfiguration(url: URL(string: "https://chat.spboucher.ai")!)?.origin == "https://chat.spboucher.ai")35 #expect(ServerConfiguration(url: URL(string: "https://chat.spboucher.ai:443/x")!)?.origin == "https://chat.spboucher.ai")36 #expect(ServerConfiguration(url: URL(string: "http://localhost:8510")!)?.origin == "http://localhost:8510")37 #expect(ServerConfiguration(url: URL(string: "http://chat.spboucher.ai")!) == nil)38 #expect(ServerConfiguration(url: URL(string: "http://192.168.2.103:8500")!) == nil)39 #expect(ServerConfiguration(url: URL(string: "ftp://x")!) == nil)40 }41}4243@Suite struct APIClientTests {44 @Test func sendsCookieAndOriginOnlyOnMutations() async throws {45 let t = MockTransport(); let api = makeClient(t)46 t.on("GET", "/api/conversations", .json(200, #"{"conversations":[]}"#)); t.on("PATCH", "/api/conversations/c1", .json(200, #"{"conversation":{"id":"c1","title":"Nouveau"}}"#))47 _ = try await api.conversations(filter: .favorites, query: "été")48 let c = try await api.updateConversation("c1", ConversationPatch(title: "Nouveau", projectId: .some(nil), pinned: true))49 #expect(c.title == "Nouveau")50 let get = t.requests[0], patch = t.requests[1]51 #expect(get.headers["Origin"] == nil); #expect(get.headers["Cookie"]?.hasPrefix("__Host-csa_session=") == true)52 #expect(get.query?.contains("favorite=1") == true); #expect(get.query?.contains("q=%C3%A9t%C3%A9") == true)53 #expect(patch.headers["Origin"] == "https://chat.spboucher.ai"); #expect(patch.headers["Content-Type"] == "application/json")54 let body = JSONValue.parse(patch.body!)!55 #expect(body["title"]?.stringValue == "Nouveau"); #expect(body["projectId"]?.isNull == true); #expect(body["pinned"] == true); #expect(body["favorite"] == nil)56 }5758 @Test func lockedSessionClearsTheTokenAndNotifies() async {59 let t = MockTransport(); let secrets = InMemorySecretStore(); let api = makeClient(t, secrets: secrets)60 let ended = Flag(); api.onSessionEnded = { ended.set() }61 t.on("GET", "/api/models", .json(401, #"{"error":"Session requise","code":"locked"}"#, headers: ["x-csa-locked": "1"]))62 await #expect(throws: APIError.self) { _ = try await api.models() }63 #expect(ended.value); #expect(!api.hasSession); #expect(secrets.isEmpty)64 }6566 @Test func reauthIsRequestedOnceThenTheCallIsReplayed() async throws {67 let t = MockTransport(); let api = makeClient(t); let count = Counter()68 api.reauthenticator = { count.increment() }69 t.on("POST", "/api/auth/recovery-codes", .json(403, #"{"error":"Confirme","code":"reauth_required"}"#), .json(200, #"{"codes":["AAAA-BBBB-CCCC-DDDD-EEEE"]}"#))70 let j = try await api.json(.post, "/api/auth/recovery-codes")71 #expect(j["codes"]?[0]?.stringValue == "AAAA-BBBB-CCCC-DDDD-EEEE"); #expect(count.value == 1); #expect(t.requests.count == 2)72 }7374 @Test func reauthNeverLoops() async {75 let t = MockTransport(); let api = makeClient(t); let count = Counter()76 api.reauthenticator = { count.increment() }77 t.on("DELETE", "/api/owner", .json(403, #"{"error":"Confirme","code":"reauth_required"}"#))78 do { try await api.wipeAllData(includeUsage: false); Issue.record("must throw") } catch let e as APIError { #expect(e.kind == .reauthRequired) } catch { Issue.record("wrong error") }79 #expect(count.value == 1); #expect(t.requests.count == 2)80 }8182 @Test func errorMapping() async {83 let t = MockTransport(); let api = makeClient(t)84 t.on("GET", "/api/usage", .json(500, #"{"error":"Erreur interne (réf. ab12cd34)","code":"internal","rid":"ab12cd34"}"#, headers: ["x-request-id": "ab12cd34"]))85 t.on("GET", "/api/presets", .json(429, #"{"error":"Trop de tentatives. Réessaie plus tard.","code":"rate_limited"}"#, headers: ["Retry-After": "42"]))86 t.on("GET", "/api/projects", .fail(.notConnectedToInternet)); t.on("GET", "/api/prompts", .fail(.serverCertificateUntrusted)); t.on("GET", "/api/health", .json(200, "<html>"))87 do { _ = try await api.usage(); Issue.record("throw") } catch let e as APIError { #expect(e.kind == .server(status: 500)); #expect(e.requestId == "ab12cd34"); #expect(e.message.contains("ab12cd34")) } catch {}88 do { _ = try await api.presets(); Issue.record("throw") } catch let e as APIError { #expect(e.kind == .rateLimited(retryAfter: 42)) } catch {}89 do { _ = try await api.projects(); Issue.record("throw") } catch let e as APIError { #expect(e.kind == .network(offline: true)); #expect(e.message.hasPrefix("Hors ligne")) } catch {}90 do { _ = try await api.prompts(); Issue.record("throw") } catch let e as APIError { #expect(e.code == "tls") } catch {}91 do { _ = try await api.health(); Issue.record("throw") } catch let e as APIError { #expect(e.kind == .decoding) } catch {}92 }9394 @Test func uploadBuildsMultipartAndReportsProgress() async throws {95 let t = MockTransport(); let api = makeClient(t); let progress = Counter()96 t.on("POST", "/api/attachments", .json(201, #"{"attachments":[{"id":"att_1","filename":"note.txt","mime":"text/plain","size":5,"size_bytes":5,"pages":null,"index_status":"skipped"}]}"#))97 let atts = try await api.uploadAttachments([UploadFile(filename: "no\"te.txt", mime: "text/plain", data: Data("salut".utf8))], conversationId: "conv_1") { _ in progress.increment() }98 #expect(atts.first?.id == "att_1"); #expect(atts.first?.sizeBytes == 5); #expect(progress.value >= 2)99 let r = t.requests[0]; let body = String(decoding: r.body!, as: UTF8.self)100 #expect(r.headers["Content-Type"]?.hasPrefix("multipart/form-data; boundary=") == true); #expect(r.headers["Origin"] == "https://chat.spboucher.ai")101 #expect(body.contains(#"name="file"; filename="note.txt""#)); #expect(body.contains("salut")); #expect(body.contains(#"name="conversationId""#)); #expect(body.hasSuffix("--\r\n"))102 }103104 @Test func downloadReadsTheFileName() async throws {105 let t = MockTransport(); let api = makeClient(t)106 t.on("GET", "/api/conversations/c1/export", .data(200, Data("# T".utf8), headers: ["Content-Type": "text/markdown; charset=utf-8", "Content-Disposition": #"attachment; filename="Conversation - Ete.md"; filename*=UTF-8''Conversation%20-%20%C3%89t%C3%A9.md"#]))107 let f = try await api.exportConversation("c1", format: "md")108 #expect(f.filename == "Conversation - Été.md"); #expect(f.mime == "text/markdown"); #expect(String(decoding: f.data, as: UTF8.self) == "# T")109 }110}111112final class Flag: @unchecked Sendable { private let l = NSLock(); private var v = false; func set() { l.withLock { v = true } }; var value: Bool { l.withLock { v } } }113final class Counter: @unchecked Sendable { private let l = NSLock(); private var v = 0; func increment() { l.withLock { v += 1 } }; var value: Int { l.withLock { v } } }114