SPB Git

Repository Public

AuthAndCacheTests.swift 13.0 KB 148 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: SPChat/Tests/CoreTests/AuthAndCacheTests.swift3// Description: Passkey ceremonies against a scripted server, session lifecycle, and the offline SQLite cache.4import Foundation5import Testing6@testable import SPChatCore78@Suite struct AuthServiceTests {9    private let loginOptions = #"{"options":{"rpId":"chat.spboucher.ai","challenge":"T26MIJAOQALIrkLCsrX25SYynMrsarLEwucK3SaCD3s","allowCredentials":[],"timeout":300000,"userVerification":"required"}}"#10    private let registerOptions = #"{"options":{"challenge":"AAECAwQFBgcICQoLDA0ODw","rp":{"name":"Chat SPBoucher AI","id":"chat.spboucher.ai"},"user":{"id":"q83vEjRWeJA","name":"proprietaire","displayName":"Propriétaire"},"pubKeyCredParams":[{"alg":-7,"type":"public-key"}],"excludeCredentials":[{"id":"AQID","type":"public-key"}],"authenticatorSelection":{"residentKey":"required","userVerification":"required"}}}"#11    private let sessionCookie = ["Set-Cookie": "__Host-csa_session=\(String(repeating: "s", count: 43)); Path=/; Max-Age=2592000; HttpOnly; Secure; SameSite=lax"]1213    @Test func enrolThenSignInCarriesTheCeremonyCookieAndStoresTheSession() async throws {14        let t = MockTransport(); let secrets = InMemorySecretStore(); let api = makeClient(t, secrets: secrets, session: false)15        let device = SoftwareAuthenticator(origin: "https://chat.spboucher.ai"); let auth = AuthService(api: api, authenticator: device)16        t.on("POST", "/api/auth/setup", .json(200, #"{"ok":true,"kind":"bootstrap"}"#, headers: ["Set-Cookie": "__Host-csa_setup=setuptok; Path=/; Max-Age=600; HttpOnly; SameSite=strict"]))17        t.on("POST", "/api/auth/register/options", .json(200, registerOptions, headers: ["Set-Cookie": "__Host-csa_ceremony=cer1; Path=/; Max-Age=300"]))18        t.on("POST", "/api/auth/register/verify", .json(200, #"{"ok":true,"signedIn":true}"#, headers: sessionCookie))19        try await auth.redeemSetupCode("ABCD-EFGH-JKMN-PQRS-TVWX")20        try await auth.registerPasskey(label: "Mac de test")21        #expect(api.hasSession); #expect(device.credentialCount == 1)22        let verify = t.requests[2]; let body = JSONValue.parse(verify.body!)!23        #expect(verify.headers["Cookie"]?.contains("__Host-csa_ceremony=cer1") == true); #expect(verify.headers["Cookie"]?.contains("__Host-csa_setup=setuptok") == true)24        #expect(verify.headers["Origin"] == "https://chat.spboucher.ai")25        #expect(body["label"]?.stringValue == "Mac de test"); #expect(body["response"]?["type"]?.stringValue == "public-key")26        #expect(body["response"]?["id"] == body["response"]?["rawId"])27        let cdj = JSONValue.parse(Data(base64URLEncoded: body["response"]!["response"]!["clientDataJSON"]!.stringValue!)!)!28        #expect(cdj["type"]?.stringValue == "webauthn.create"); #expect(cdj["challenge"]?.stringValue == "AAECAwQFBgcICQoLDA0ODw"); #expect(cdj["origin"]?.stringValue == "https://chat.spboucher.ai")2930        // sign out: the server is told, the token is forgotten31        t.on("POST", "/api/auth/logout", .json(200, #"{"ok":true}"#))32        await auth.signOut()33        #expect(!api.hasSession); #expect(secrets.isEmpty)3435        // sign in with the registered passkey36        t.on("POST", "/api/auth/login/options", .json(200, loginOptions, headers: ["Set-Cookie": "__Host-csa_ceremony=cer2; Path=/; Max-Age=300"]))37        t.on("POST", "/api/auth/login/verify", .json(200, #"{"ok":true}"#, headers: ["Set-Cookie": sessionCookie["Set-Cookie"]! + ", __Host-csa_ceremony=; Path=/; Max-Age=0"]))38        try await auth.signIn()39        #expect(api.hasSession); #expect(secrets.read("session@chat.spboucher.ai")?.hasPrefix("__Host-csa_session=") == true)40        let login = t.requests.last!; let lb = JSONValue.parse(login.body!)!41        #expect(login.headers["Cookie"]?.contains("cer2") == true)42        #expect(lb["response"]?["response"]?["userHandle"]?.stringValue == "q83vEjRWeJA"); #expect(lb["response"]?["response"]?["signature"]?.stringValue?.isEmpty == false)43        #expect(api.cookies.header?.contains("ceremony") == false) // single-use cookie dropped after verification44    }4546    @Test func failuresAreExplainedAndNeverOpenASession() async {47        let t = MockTransport(); let api = makeClient(t, session: false)48        let device = SoftwareAuthenticator(origin: "https://chat.spboucher.ai"); let auth = AuthService(api: api, authenticator: device)49        t.on("POST", "/api/auth/login/options", .json(200, loginOptions), .json(200, loginOptions), .json(429, #"{"error":"Trop de tentatives.","code":"rate_limited"}"#), .fail(.notConnectedToInternet))50        t.on("POST", "/api/auth/login/verify", .json(401, #"{"error":"Vérification refusée.","code":"auth_failed"}"#))51        // 1. no passkey on this device → cancelled by the system sheet52        do { try await auth.signIn(); Issue.record("throw") } catch let e as PasskeyError { #expect(e.code == .cancelled) } catch { Issue.record("wrong") }53        // 2. server refuses the assertion54        _ = try? await device.register(RegistrationRequest(rpId: "chat.spboucher.ai", rpName: "x", challenge: Data([1]), userId: Data([2]), userName: "u", excludeCredentials: []))55        do { try await auth.signIn(); Issue.record("throw") } catch let e as PasskeyError { #expect(e.code == .refused); #expect(e.message == "Vérification refusée.") } catch { Issue.record("wrong") }56        do { try await auth.signIn(); Issue.record("throw") } catch let e as PasskeyError { #expect(e.code == .rateLimited) } catch { Issue.record("wrong") }57        do { try await auth.signIn(); Issue.record("throw") } catch let e as PasskeyError { #expect(e.code == .network) } catch { Issue.record("wrong") }58        #expect(!api.hasSession)59    }6061    @Test func sensitiveCallTriggersReauthenticationThroughTheService() async throws {62        let t = MockTransport(); let api = makeClient(t)63        let device = SoftwareAuthenticator(origin: "https://chat.spboucher.ai"); let auth = AuthService(api: api, authenticator: device)64        _ = try await device.register(RegistrationRequest(rpId: "chat.spboucher.ai", rpName: "x", challenge: Data([1]), userId: Data([2]), userName: "u", excludeCredentials: []))65        t.on("POST", "/api/auth/recovery-codes", .json(403, #"{"error":"Confirme avec ta clé d'accès pour continuer","code":"reauth_required"}"#), .json(200, #"{"codes":["A","B"]}"#))66        t.on("POST", "/api/auth/reauth/options", .json(200, loginOptions))67        t.on("POST", "/api/auth/reauth/verify", .json(200, #"{"ok":true}"#, headers: ["Set-Cookie": "__Host-csa_session=\(String(repeating: "r", count: 43)); Path=/; Max-Age=2592000"]))68        let codes = try await auth.generateRecoveryCodes()69        #expect(codes == ["A", "B"]); #expect(device.assertions == 1)70        #expect(t.requests.last?.headers["Cookie"]?.contains(String(repeating: "r", count: 43)) == true) // rotated token used for the replay71    }7273    @Test func optionParsing() {74        let a = AuthService.assertionRequest(JSONValue.parse(Data(loginOptions.utf8))!["options"]!)75        #expect(a?.rpId == "chat.spboucher.ai"); #expect(a?.challenge.count == 32); #expect(a?.allowCredentials.isEmpty == true)76        let r = AuthService.registrationRequest(JSONValue.parse(Data(registerOptions.utf8))!["options"]!)77        #expect(r?.userName == "proprietaire"); #expect(r?.excludeCredentials == [Data([1, 2, 3])]); #expect(r?.rpName == "Chat SPBoucher AI")78        #expect(AuthService.assertionRequest(["rpId": "x"]) == nil)79    }80}8182@Suite struct CacheStoreTests {83    private func conv(_ id: String, _ title: String, pinned: Bool = false, favorite: Bool = false, archived: Bool = false, at: TimeInterval) -> Conversation {84        Conversation(id: id, title: title, pinned: pinned, favorite: favorite, archivedAt: archived ? Date(timeIntervalSince1970: at) : nil, lastMessageAt: Date(timeIntervalSince1970: at), createdAt: Date(timeIntervalSince1970: at))85    }86    private func detail(_ c: Conversation, _ texts: [(MessageRole, String, Bool)]) -> ConversationDetail {87        var parent: String?; var msgs: [Message] = []88        for (i, t) in texts.enumerated() { let m = Message(id: "\(c.id)_m\(i)", conversationId: c.id, parentId: parent, role: t.0, parts: [.text(t.1)], active: t.2, createdAt: Date(timeIntervalSince1970: 1000 + Double(i))); msgs.append(m); parent = m.id }89        return ConversationDetail(conversation: c, messages: msgs, draft: "brouillon", liveRun: "run_live")90    }9192    @Test func listOrderFiltersAndReplacement() async throws {93        let store = try CacheStore(url: nil)94        try await store.replaceConversations([conv("a", "Alpha", at: 100), conv("b", "Bêta épinglée", pinned: true, at: 50), conv("c", "Gamma 100%", favorite: true, at: 200)], archived: false)95        try await store.replaceConversations([conv("z", "Vieille", archived: true, at: 10)], archived: true)96        #expect(try await store.conversations().map(\.id) == ["b", "c", "a"]) // pinned first, then most recent97        #expect(try await store.conversations(filter: .favorites).map(\.id) == ["c"]); #expect(try await store.conversations(filter: .archived).map(\.id) == ["z"])98        #expect(try await store.conversations(query: "100%").map(\.id) == ["c"]); #expect(try await store.conversations(query: "%").map(\.id) == ["c"]) // LIKE wildcards are escaped99        // the server no longer lists "a": it disappears with its messages100        try await store.saveDetail(detail(conv("a", "Alpha", at: 100), [(.user, "question", true)]))101        try await store.replaceConversations([conv("b", "Bêta épinglée", pinned: true, at: 50), conv("c", "Gamma 100%", favorite: true, at: 200)], archived: false)102        #expect(try await store.conversations().map(\.id) == ["b", "c"]); #expect(try await store.detail("a") == nil)103        #expect(try await store.conversations(filter: .archived).count == 1) // the archived list is untouched104    }105106    @Test func detailRoundTripAndOfflineSearch() async throws {107        let store = try CacheStore(url: nil)108        let c = conv("c1", "Recette de crêpes", at: 100)109        try await store.saveDetail(detail(c, [(.user, "Comment réussir une pâte à crêpes légère ?", true), (.assistant, "Ancienne version abandonnée avec sarrasin", false), (.assistant, "Laisse reposer la pâte une heure au frais.", true)]))110        let cached = try #require(try await store.detail("c1"))111        #expect(cached.detail.messages.count == 3); #expect(cached.detail.draft == "brouillon"); #expect(cached.detail.liveRun == nil) // a live run id is never cached112        #expect(abs(cached.fetchedAt.timeIntervalSinceNow) < 5)113        let hits = try await store.search("pate reposer") // diacritics-insensitive, all terms114        #expect(hits.first?.conversationId == "c1"); #expect(hits.first?.snippet.contains("<b>") == true)115        #expect(try await store.search("sarrasin").isEmpty) // inactive branches are not indexed116        #expect(try await store.search("recette").first?.role == "title") // titles are searched too117        #expect(try await store.search("\" OR 1=1 --").isEmpty) // hostile input is tokenised, never interpreted as FTS syntax118        try await store.deleteConversation("c1")119        #expect(try await store.search("pate").isEmpty); #expect(try await store.stats().messages == 0)120    }121122    @Test func catalogueValuesAndWipe() async throws {123        let dir = FileManager.default.temporaryDirectory.appendingPathComponent("spchat-test-\(UUID().uuidString)"); defer { try? FileManager.default.removeItem(at: dir) }124        let url = dir.appendingPathComponent("cache.sqlite")125        do {126            let store = try CacheStore(url: url)127            try await store.set(ModelCatalog(models: [AIModel(id: "m1", provider: "openai", displayName: "M1")], defaultModel: "m1"), for: "models")128            try await store.upsertConversation(conv("a", "Persistante", at: 1))129        }130        let reopened = try CacheStore(url: url) // survives a relaunch131        #expect(try await reopened.get(ModelCatalog.self, for: "models")?.defaultModel == "m1"); #expect(try await reopened.conversations().count == 1)132        try await reopened.wipe()133        #expect(try await reopened.get(ModelCatalog.self, for: "models") == nil); #expect(try await reopened.conversations().isEmpty)134        let raw = try Data(contentsOf: url); #expect(raw.range(of: Data("Persistante".utf8)) == nil) // nothing readable left in the file after a wipe135    }136137    @Test func veryLongConversation() async throws {138        let store = try CacheStore(url: nil); let c = conv("big", "Longue", at: 1)139        let texts = (0..<4000).map { i -> (MessageRole, String, Bool) in (i % 2 == 0 ? .user : .assistant, "Message numéro \(i) " + String(repeating: "lorem ipsum dolor sit amet ", count: 20), true) }140        let clock = ContinuousClock()141        let write = try await clock.measure { try await store.saveDetail(detail(c, texts)) }142        var loaded: ConversationDetail?143        let read = try await clock.measure { loaded = try await store.detail("big")?.detail }144        #expect(loaded?.messages.count == 4000); #expect(write < .seconds(5)); #expect(read < .seconds(2))145        #expect(try await store.search("numéro 3999").first?.id == "big_m3999")146    }147}148
Files main
Menu

Theme