SPB Git

Repository Public

APITests.swift 20.5 KB 330 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : Lou-Ka Admin iOS9// File             : LouKaAdminTests/APITests.swift10// Description      : client de l'API d'administration et session contre un11//                    serveur simulé (`URLProtocol`) — en-têtes, chemins, corps,12//                    erreurs, jeton au coffre, 401 `non_authentifie` → écran de13//                    connexion.14// Module           : LouKaAdminTests15// Repository       : https://git.spboucher.ai/lou-ka-admin-ios16// Project Website  : https://www.lou-ka.com17// Created          : 2026-11-3018// Last Modified    : 2026-11-3019//20// =============================================================================21// AUTHOR & PROFESSIONAL AFFILIATION22// =============================================================================23//24// Author           : Simon-Pierre Boucher25// Position         : Professor of Finance26// Institution      : Université du Québec en Outaouais (UQO)27// Department       : Département des sciences administratives28// Organization     : SP Boucher29//30// Website          : https://spboucher.ai31// Git              : https://git.spboucher.ai32//33// =============================================================================34// OFFICIAL CONTACT DIRECTORY35// =============================================================================36//37// General          : info@spboucher.ai38// Professional     : contact@spboucher.ai39// Direct           : simon@spboucher.ai40// Research         : research@spboucher.ai41// Development      : dev@spboucher.ai42// Support          : support@spboucher.ai43// Security/Admin   : admin@spboucher.ai44// Notifications    : notifications@spboucher.ai45//46// Preferred Contact: support@spboucher.ai47//48// =============================================================================49// COPYRIGHT & INTELLECTUAL PROPERTY50// =============================================================================51//52// Copyright (c) 202653// Simon-Pierre Boucher54//55// All rights reserved where applicable.56//57// This file is governed by the applicable project license,58// copyright notices, institutional agreements and relevant law.59//60// Unless expressly authorized by the applicable license or61// rights holder, copying, redistribution, sublicensing,62// publication and commercial exploitation are not permitted.63//64// Existing third-party rights and notices remain unaffected.65//66// =============================================================================67// CONFIDENTIALITY & SECURITY68// =============================================================================69//70// Classification   : Public71// Distribution     : Public repository; use is governed by the project license72// Security Contact : admin@spboucher.ai73//74// Access to this source does not independently grant permission75// to redistribute or disclose confidential materials.76//77// Do not embed credentials, private keys, access tokens,78// certificates or confidential personal information.79//80// =============================================================================81// LICENSE & MAINTENANCE82// =============================================================================83//84// License          : None specified (no license file in this repository)85// Maintainer       : Simon-Pierre Boucher86// Technical Contact: dev@spboucher.ai87//88// =============================================================================89// END OF SP BOUCHER SOURCE HEADER90// =============================================================================9192import Foundation93import Testing94@testable import LouKaAdmin9596private let base = URL(string: "https://admin.test")!97private func api(token: String? = "jeton-1") -> AdminAPI { AdminAPI(session: StubServer.session(), base: { base }, token: { token }) }98private let meJSON = #"{"admin":{"id":"a1","name":"Léa","email":"lea@lou-ka.com","mailboxes":["contact@lou-ka.com"]},"stats":{"comptes":3},"keys":[{"id":"k1","name":"iPhone"}],"mail":true}"#99100extension Stubbed {101@Suite("API d'administration : client")102struct AdminAPITests {103    @Test("en-têtes : X-LouKa-Client ios-admin, jeton Bearer, JSON ; aucun jeton sur les routes de connexion")104    func headers() async throws {105        StubServer.install { r in r.path.hasSuffix("/options") ? .json(#"{"challenge_id":"c1","options":{"challenge":"AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8","rpId":"www.lou-ka.com","userVerification":"required"}}"#) : .json(meJSON) }106        let me = try await api().me()107        #expect(me.admin.name == "Léa" && me.stats.comptes == 3)108        let r = try #require(StubServer.seen.first)109        #expect(r.method == "GET" && r.url == "https://admin.test/api/v3/admin" && r.headers["X-LouKa-Client"] == "ios-admin" && r.headers["Authorization"] == "Bearer jeton-1")110        let ch = try await api().loginOptions()111        let o = try #require(StubServer.seen.last)112        #expect(o.method == "POST" && o.path == "/api/v3/admin/connexion/options" && o.headers["Authorization"] == nil && o.headers["Content-Type"] == "application/json")113        #expect(String(data: o.body, encoding: .utf8) == "{}" && ch.challengeID == "c1")114        #expect(try PasskeyAssertionOptions(json: ch.options, defaultRPID: "x").challenge == Data(0..<32))115    }116117    @Test("connexion et activation : challenge_id, credential, key_name ; la réponse porte session.token")118    func ceremonies() async throws {119        StubServer.install { r in120            r.path.hasSuffix("/options") ? .json(#"{"challenge_id":"c2","options":{"challenge":"AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8","user":{"id":"dTE","name":"lea@lou-ka.com","displayName":"Léa"}},"admin":{"name":"Léa","email":"lea@lou-ka.com"}}"#)121                : .json(#"{"admin":{"id":"a1","name":"Léa","email":"lea@lou-ka.com","mailboxes":[]},"session":{"token":"jeton-neuf","idle_hours":12,"max_hours":168}}"#)122        }123        let cred = WebAuthnCredential.assertion(credentialID: Data([1]), clientDataJSON: Data("{}".utf8), authenticatorData: Data([2]), signature: Data([3]), userHandle: nil)124        let s = try await api(token: nil).loginVerify(challengeID: "c1", credential: cred)125        #expect(s.session?.token == "jeton-neuf" && s.session?.idleHours == 12 && s.session?.maxHours == 168 && s.admin.id == "a1")126        var r = try #require(StubServer.seen.last)127        #expect(r.path == "/api/v3/admin/connexion/verification" && r.json["challenge_id"] as? String == "c1")128        #expect(((r.json["credential"] as? [String: Any])?["response"] as? [String: Any])?["signature"] as? String == "Aw")129        let ch = try await api(token: nil).activationOptions(token: "jeton-activation-0123456789")130        let reg0 = try PasskeyRegistrationOptions(json: ch.options, defaultRPID: "www.lou-ka.com")131        #expect(ch.challengeID == "c2" && ch.admin?.name == "Léa" && reg0.userID == Data("u1".utf8) && reg0.rpID == "www.lou-ka.com")132        #expect(StubServer.seen.last?.json["token"] as? String == "jeton-activation-0123456789")133        let reg = WebAuthnCredential.registration(credentialID: Data([1]), clientDataJSON: Data("{}".utf8), attestationObject: Data([4]))134        _ = try await api(token: nil).activationVerify(token: "jeton-activation-0123456789", challengeID: "c2", credential: reg, keyName: "iPhone de Léa")135        r = try #require(StubServer.seen.last)136        #expect(r.path == "/api/v3/admin/activation/verification" && r.json["key_name"] as? String == "iPhone de Léa" && r.json["challenge_id"] as? String == "c2" && r.json["token"] as? String == "jeton-activation-0123456789")137        #expect(((r.json["credential"] as? [String: Any])?["response"] as? [String: Any])?["attestationObject"] as? String == "BA")138    }139140    @Test("gestionnaires : filtre, décision avec motif, rattachement, annuaire public, fiche et masquage")141    func managers() async throws {142        StubServer.install { r in143            if r.path.hasSuffix("/recherche") { return .json(#"{"items":[{"source_id":"cogir","name":"Cogir Immobilier","domain":"cogir.net","listings":269}]}"#) }144            if r.path.hasSuffix("/decision") { return .json(#"{"status":"refuse","source_id":null}"#) }145            if r.path.hasSuffix("/masquage") { return .noContent }146            if r.path.contains("/fiches/") { return .json(#"{"source_id":"cogir","draft":{},"published":null,"hidden":false,"media":[],"team":[]}"#) }147            return .json(#"{"items":[]}"#)148        }149        let a = api()150        _ = try await a.managers(.pending)151        #expect(StubServer.seen.last?.url == "https://admin.test/api/v3/admin/gestionnaires?etat=en_attente")152        let d = try await a.decide(accountID: "acc/1", action: .refuse, reason: "  Site sans lien avec l'entreprise  ")153        var r = try #require(StubServer.seen.last)154        #expect(r.method == "POST" && r.url == "https://admin.test/api/v3/admin/gestionnaires/acc%2F1/decision" && d.status == "refuse")155        #expect(r.json["action"] as? String == "refuser" && r.json["reason"] as? String == "Site sans lien avec l'entreprise" && r.json["source_id"] == nil)156        _ = try await a.decide(accountID: "acc1", action: .attach, sourceID: "cogir")157        r = try #require(StubServer.seen.last)158        #expect(r.json["action"] as? String == "rattacher" && r.json["source_id"] as? String == "cogir" && r.json["reason"] == nil)159        let found = try await a.searchDirectory("cog ir")160        r = try #require(StubServer.seen.last)161        #expect(r.url == "https://admin.test/api/v3/gestionnaires/recherche?q=cog%20ir" && r.headers["Authorization"] == nil && found.first?.sourceID == "cogir")162        _ = try await a.fiche(sourceID: "cogir")163        try await a.hideFiche(sourceID: "cogir", hidden: true, reason: " Contenu trompeur ")164        r = try #require(StubServer.seen.last)165        #expect(r.path == "/api/v3/admin/fiches/cogir/masquage" && r.json["hidden"] as? Bool == true && r.json["reason"] as? String == "Contenu trompeur")166    }167168    @Test("signalements, clés, journal")169    func reportsAndKeys() async throws {170        StubServer.install { r in171            if r.method == "DELETE" || r.path.hasSuffix("/decision") { return .noContent }172            if r.path.hasSuffix("/invitation") { return .json(#"{"url":"https://www.lou-ka.com/admin/activation?jeton=abcdefghijklmnopqrstuvwx","expires_in_days":1}"#) }173            return .json(#"{"items":[]}"#)174        }175        let a = api()176        _ = try await a.reports(all: false)177        #expect(StubServer.seen.last?.url == "https://admin.test/api/v3/admin/signalements")178        _ = try await a.reports(all: true)179        #expect(StubServer.seen.last?.url == "https://admin.test/api/v3/admin/signalements?tous=1")180        try await a.decideReport(40, decision: "bloquer")181        #expect(StubServer.seen.last?.path == "/api/v3/admin/signalements/40/decision" && StubServer.seen.last?.json["decision"] as? String == "bloquer")182        let inv = try await a.keyInvitation()183        #expect(ActivationLink.token(from: inv.url) == "abcdefghijklmnopqrstuvwx" && inv.expiresInDays == 1)184        try await a.deleteKey("k 1")185        #expect(StubServer.seen.last?.method == "DELETE" && StubServer.seen.last?.url == "https://admin.test/api/v3/admin/cles/k%201" && StubServer.seen.last?.body.isEmpty == true)186        _ = try await a.journal(); _ = try await a.admins()187        #expect(StubServer.seen.suffix(2).map(\.path) == ["/api/v3/admin/journal", "/api/v3/admin/administrateurs"])188    }189190    @Test("courrier : liste par curseur et recherche, lecture, lu / non lu, étoile, corbeille, envoi, pièce jointe")191    func mail() async throws {192        StubServer.install { r in193            if r.path.hasSuffix("/pieces/att_1") { return StubResponse(status: 200, headers: ["Content-Type": "application/pdf"], body: Data([0x25, 0x50, 0x44, 0x46])) }194            if r.method == "DELETE" { return .noContent }195            if r.method == "PATCH" { return .json(#"{"id":"msg_1","unread":true}"#) }196            if r.path.hasSuffix("/envoi") { return .json(#"{"status":"envoye","id":"msg_2"}"#) }197            if r.path.hasSuffix("/messages") { return .json(#"{"data":[],"next_cursor":"c2","has_more":true}"#) }198            return .json(#"{"id":"msg_1","mailbox":"contact@lou-ka.com","from":[],"to":[],"text":"x","attachments":[]}"#)199        }200        let a = api()201        let page = try await a.messages(address: "contact@lou-ka.com", folder: "inbox", text: "bail café", cursor: "c1")202        #expect(StubServer.seen.last?.url == "https://admin.test/api/v3/admin/courrier/messages?address=contact%40lou-ka.com&cursor=c1&folder=inbox&limit=30&text=bail%20caf%C3%A9")203        #expect(page.hasMore && page.nextCursor == "c2")204        _ = try await a.message("msg_1")205        try await a.patchMessage("msg_1", unread: true)206        var r = try #require(StubServer.seen.last)207        #expect(r.method == "PATCH" && r.path == "/api/v3/admin/courrier/messages/msg_1" && r.json["unread"] as? Bool == true && r.json["starred"] == nil)208        try await a.patchMessage("msg_1", starred: false)209        #expect(StubServer.seen.last?.json["starred"] as? Bool == false && StubServer.seen.last?.json["unread"] == nil)210        try await a.trashMessage("msg_1")211        #expect(StubServer.seen.last?.method == "DELETE")212        try await a.sendMail(MailDraft(from: "contact@lou-ka.com", to: ["support@lou-ka.com"], cc: nil, subject: "[essai] Bonjour", text: "Texte", replyToMessageID: "msg_1"))213        r = try #require(StubServer.seen.last)214        #expect(r.path == "/api/v3/admin/courrier/envoi" && r.json["from"] as? String == "contact@lou-ka.com" && r.json["to"] as? [String] == ["support@lou-ka.com"])215        #expect(r.json["subject"] as? String == "[essai] Bonjour" && r.json["reply_to_message_id"] as? String == "msg_1" && r.json["cc"] == nil)216        let att = try JSONDecoder().decode(MailAttachment.self, from: Data(#"{"id":"att_1","name":"Bail.pdf","type":"application/pdf","size":4}"#.utf8))217        let file = try await a.attachment(messageID: "msg_1", attachment: att)218        defer { try? FileManager.default.removeItem(at: file.url.deletingLastPathComponent()) }219        let written = try Data(contentsOf: file.url)220        #expect(file.bytes == 4 && file.url.lastPathComponent == "Bail.pdf" && written == Data([0x25, 0x50, 0x44, 0x46]))221        #expect(StubServer.seen.last?.headers["Authorization"] == "Bearer jeton-1" && file.url.path.hasPrefix(FileManager.default.temporaryDirectory.path))222    }223224    @Test("erreurs : message du serveur tel quel, phrases de repli, 401 non_authentifie distingué, hors ligne")225    func errors() async throws {226        func failure(_ r: StubResponse) async -> AdminError? {227            StubServer.install { _ in r }228            do { _ = try await api().me(); return nil } catch { return error as? AdminError }229        }230        let reason = await failure(.json(#"{"error":{"code":"motif_requis","message":"Un motif est obligatoire pour refuser.","param":"reason","request_id":"r"}}"#, status: 422))231        #expect(reason?.code == "motif_requis" && reason?.errorDescription == "Un motif est obligatoire pour refuser." && reason?.isUnauthenticated == false)232        let expired = await failure(.error(401, "non_authentifie", "Ouvrez une session d'administration."))233        #expect(expired?.isUnauthenticated == true)234        let other401 = await failure(.error(401, "cle_inconnue", "Cette clé d'accès n'est pas reconnue."))235        #expect(other401?.isUnauthenticated == false && other401?.errorDescription == "Cette clé d'accès n'est pas reconnue.")236        #expect(await failure(StubResponse(status: 502, body: Data("<html>".utf8)))?.errorDescription == "Le serveur a rencontré une erreur. Réessayez dans un instant.")237        #expect(await failure(StubResponse(status: 403))?.errorDescription == "Cette action vous est refusée.")238        #expect(await failure(StubResponse(status: 429))?.code == "http_429")239        let offline = await failure(.down), unreadable = await failure(.json("pas du json"))240        #expect(offline == .offline && unreadable == .decoding)241    }242}243244@Suite("Session d'administration")245@MainActor246struct AdminSessionTests {247    private func session(_ store: MemoryStore = MemoryStore()) -> AdminSession { AdminSession(store: store, session: StubServer.session(), base: { base }) }248249    @Test("sans session : rien au coffre, écran de connexion")250    func signedOut() {251        let s = session()252        #expect(!s.isSignedIn && !s.restoring && !s.hasStoredSession && !s.ended && !s.locked)253    }254255    @Test("session gardée : confirmée par le serveur au lancement ; 401 non_authentifie → écran de connexion, jeton effacé")256    func restoreAndExpire() async throws {257        let store = MemoryStore()258        store.set(AdminSession.tokenKey, "jeton-garde")259        let expired = Counter()260        StubServer.install { r in expired.next() > 2 ? .error(401, "non_authentifie", "Ouvrez une session d'administration.") : (r.path.hasSuffix("/journal") ? .json(#"{"items":[]}"#) : .json(meJSON)) }261        let s = session(store)262        #expect(s.restoring && s.hasStoredSession && !s.isSignedIn)263        await s.restore()264        #expect(s.isSignedIn && !s.restoring && s.me?.admin.name == "Léa" && StubServer.seen.first?.headers["Authorization"] == "Bearer jeton-garde")265        _ = try await s.call { try await $0.journal() }266        await #expect(throws: AdminError.self) { _ = try await s.call { try await $0.journal() } }267        #expect(!s.isSignedIn && s.ended && store.string(AdminSession.tokenKey) == nil && !s.hasStoredSession, "session refusée : retour à la connexion, rien ne reste au coffre")268    }269270    @Test("session trop vieille au coffre : écartée sans appel au serveur")271    func stale() throws {272        let store = MemoryStore()273        store.set(AdminSession.tokenKey, "vieux-jeton")274        let old = Date().addingTimeInterval(-13 * 3600)275        store.write(AdminSession.windowKey, try JSONEncoder().encode(SessionWindow(openedAt: old, lastActivity: old, idleHours: 12, maxHours: 168)))276        StubServer.install { _ in .json(meJSON) }277        let s = session(store)278        #expect(!s.restoring && !s.hasStoredSession && s.ended && store.string(AdminSession.tokenKey) == nil && StubServer.seen.isEmpty)279    }280281    @Test("hors ligne au lancement : la session gardée n'est pas effacée")282    func offlineRestore() async {283        let store = MemoryStore()284        store.set(AdminSession.tokenKey, "jeton-garde")285        StubServer.install { _ in .down }286        let s = session(store)287        await s.restore()288        #expect(!s.isSignedIn && !s.restoring && !s.ended && store.string(AdminSession.tokenKey) == "jeton-garde")289    }290291    @Test("activation : adresse refusée sans appel au serveur ; déconnexion : jeton effacé")292    func activationAndSignOut() async throws {293        StubServer.install { r in r.path.hasSuffix("/deconnexion") ? .noContent : .json(meJSON) }294        let store = MemoryStore()295        let s = session(store)296        do { try await s.activate(link: "https://www.lou-ka.com/admin/activation", keyName: ""); Issue.record("adresse sans jeton") } catch let e as AdminError {297            #expect(e.code == "adresse_invalide" && (e.errorDescription ?? "").contains("jeton"))298        }299        #expect(StubServer.seen.isEmpty)300        store.set(AdminSession.tokenKey, "jeton-garde")301        let t = session(store)302        await t.restore()303        #expect(t.isSignedIn)304        await t.signOut()305        #expect(!t.isSignedIn && !t.ended && store.string(AdminSession.tokenKey) == nil && StubServer.seen("POST", "/deconnexion").count == 1)306    }307308    @Test("verrouillage : arrière-plan de plus de quelques minutes, pas avant ; jamais sans session")309    func lock() async {310        let store = MemoryStore()311        store.set(AdminSession.tokenKey, "jeton-garde")312        StubServer.install { _ in .json(meJSON) }313        let s = session(store)314        await s.restore()315        let t0 = Date()316        s.didEnterBackground(now: t0)317        s.willEnterForeground(now: t0.addingTimeInterval(30))318        #expect(!s.locked, "un passage bref à l'arrière-plan ne verrouille pas")319        s.didEnterBackground(now: t0)320        s.didEnterBackground(now: t0.addingTimeInterval(100))   // l'heure retenue est celle de la sortie321        s.willEnterForeground(now: t0.addingTimeInterval(LockPolicy.delay + 1))322        #expect(s.locked && s.isSignedIn, "verrouillée, mais la session reste")323        let out = session()324        out.didEnterBackground(now: t0)325        out.willEnterForeground(now: t0.addingTimeInterval(3600))326        #expect(!out.locked)327    }328}329}330
Files main
Menu

Theme