Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : Immo-Ka Admin iOS9// File : ImmoKaAdminTests/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 : ImmoKaAdminTests15// Repository : https://git.spboucher.ai/immo-ka-admin-ios16// Project Website : https://www.immo-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 ImmoKaAdmin9596private 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@immo-ka.com","mailboxes":["contact@immo-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-ImmoKa-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.immo-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-ImmoKa-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@immo-ka.com","displayName":"Léa"}},"admin":{"name":"Léa","email":"lea@immo-ka.com"}}"#)121 : .json(#"{"admin":{"id":"a1","name":"Léa","email":"lea@immo-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.immo-ka.com")131 #expect(ch.challengeID == "c2" && ch.admin?.name == "Léa" && reg0.userID == Data("u1".utf8) && reg0.rpID == "www.immo-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("courtiers : filtre, décision avec motif, rattachement, annuaire public, fiche et masquage")141 func brokers() async throws {142 StubServer.install { r in143 if r.path.hasSuffix("/recherche") { return .json(#"{"items":[{"broker_id":"64215753413768","name":"Camille Tremblay","agency":"Agence Essai","banner":"ESSAI","listings":74}]}"#) }144 if r.path.hasSuffix("/decision") { return .json(#"{"status":"refuse","broker_id":null}"#) }145 if r.path.hasSuffix("/masquage") { return .noContent }146 if r.path.contains("/fiches/") { return .json(#"{"broker_id":"64215753413768","broker":{"broker_id":"64215753413768","name":"Camille Tremblay","listings":74},"draft":{},"published":null,"hidden":false,"media":[],"team":[]}"#) }147 return .json(#"{"items":[]}"#)148 }149 let a = api()150 _ = try await a.brokers(.pending)151 #expect(StubServer.seen.last?.url == "https://admin.test/api/v3/admin/courtiers?etat=en_attente")152 let d = try await a.decide(accountID: "acc/1", action: .refuse, reason: " Permis introuvable au registre ")153 var r = try #require(StubServer.seen.last)154 #expect(r.method == "POST" && r.url == "https://admin.test/api/v3/admin/courtiers/acc%2F1/decision" && d.status == "refuse")155 #expect(r.json["action"] as? String == "refuser" && r.json["reason"] as? String == "Permis introuvable au registre" && r.json["broker_id"] == nil)156 _ = try await a.decide(accountID: "acc1", action: .attach, brokerID: "64215753413768")157 r = try #require(StubServer.seen.last)158 #expect(r.json["action"] as? String == "rattacher" && r.json["broker_id"] as? String == "64215753413768" && r.json["reason"] == nil)159 let found = try await a.searchDirectory("trem blay")160 r = try #require(StubServer.seen.last)161 #expect(r.url == "https://admin.test/api/v3/courtiers/recherche?q=trem%20blay" && r.headers["Authorization"] == nil)162 #expect(found.first?.brokerID == "64215753413768" && found.first?.agency == "Agence Essai" && found.first?.banner == "ESSAI" && found.first?.listings == 74)163 let f = try await a.fiche(brokerID: "64215753413768")164 #expect(f.brokerName == "Camille Tremblay" && f.brokerListings == 74)165 try await a.hideFiche(brokerID: "64215753413768", hidden: true, reason: " Contenu trompeur ")166 r = try #require(StubServer.seen.last)167 #expect(r.path == "/api/v3/admin/fiches/64215753413768/masquage" && r.json["hidden"] as? Bool == true && r.json["reason"] as? String == "Contenu trompeur")168 }169170 @Test("masquer une fiche sans motif : le message du serveur (422) est montré tel quel")171 func hideWithoutReason() async throws {172 StubServer.install { _ in .json(#"{"error":{"code":"motif_requis","message":"Indiquez le motif du masquage.","param":"reason"}}"#, status: 422) }173 do { try await api().hideFiche(brokerID: "1", hidden: true, reason: ""); Issue.record("une erreur était attendue") }174 catch { #expect(AdminError.message(error) == "Indiquez le motif du masquage.") }175 }176177 @Test("signalements, clés, journal")178 func reportsAndKeys() async throws {179 StubServer.install { r in180 if r.method == "DELETE" || r.path.hasSuffix("/decision") { return .noContent }181 if r.path.hasSuffix("/invitation") { return .json(#"{"url":"https://www.immo-ka.com/admin/activation?jeton=abcdefghijklmnopqrstuvwx","expires_in_days":1}"#) }182 return .json(#"{"items":[]}"#)183 }184 let a = api()185 _ = try await a.reports(all: false)186 #expect(StubServer.seen.last?.url == "https://admin.test/api/v3/admin/signalements")187 _ = try await a.reports(all: true)188 #expect(StubServer.seen.last?.url == "https://admin.test/api/v3/admin/signalements?tous=1")189 try await a.decideReport(40, decision: "bloquer")190 #expect(StubServer.seen.last?.path == "/api/v3/admin/signalements/40/decision" && StubServer.seen.last?.json["decision"] as? String == "bloquer")191 let inv = try await a.keyInvitation()192 #expect(ActivationLink.token(from: inv.url) == "abcdefghijklmnopqrstuvwx" && inv.expiresInDays == 1)193 try await a.deleteKey("k 1")194 #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)195 _ = try await a.journal(); _ = try await a.admins()196 #expect(StubServer.seen.suffix(2).map(\.path) == ["/api/v3/admin/journal", "/api/v3/admin/administrateurs"])197 }198199 @Test("courrier : liste par curseur et recherche, lecture, lu / non lu, étoile, corbeille, envoi, pièce jointe")200 func mail() async throws {201 StubServer.install { r in202 if r.path.hasSuffix("/pieces/att_1") { return StubResponse(status: 200, headers: ["Content-Type": "application/pdf"], body: Data([0x25, 0x50, 0x44, 0x46])) }203 if r.method == "DELETE" { return .noContent }204 if r.method == "PATCH" { return .json(#"{"id":"msg_1","unread":true}"#) }205 if r.path.hasSuffix("/envoi") { return .json(#"{"status":"envoye","id":"msg_2"}"#) }206 if r.path.hasSuffix("/messages") { return .json(#"{"data":[],"next_cursor":"c2","has_more":true}"#) }207 return .json(#"{"id":"msg_1","mailbox":"contact@immo-ka.com","from":[],"to":[],"text":"x","attachments":[]}"#)208 }209 let a = api()210 let page = try await a.messages(address: "contact@immo-ka.com", folder: "inbox", text: "bail café", cursor: "c1")211 #expect(StubServer.seen.last?.url == "https://admin.test/api/v3/admin/courrier/messages?address=contact%40immo-ka.com&cursor=c1&folder=inbox&limit=30&text=bail%20caf%C3%A9")212 #expect(page.hasMore && page.nextCursor == "c2")213 _ = try await a.message("msg_1")214 try await a.patchMessage("msg_1", unread: true)215 var r = try #require(StubServer.seen.last)216 #expect(r.method == "PATCH" && r.path == "/api/v3/admin/courrier/messages/msg_1" && r.json["unread"] as? Bool == true && r.json["starred"] == nil)217 try await a.patchMessage("msg_1", starred: false)218 #expect(StubServer.seen.last?.json["starred"] as? Bool == false && StubServer.seen.last?.json["unread"] == nil)219 try await a.trashMessage("msg_1")220 #expect(StubServer.seen.last?.method == "DELETE")221 try await a.sendMail(MailDraft(from: "contact@immo-ka.com", to: ["support@immo-ka.com"], cc: nil, subject: "[essai] Bonjour", text: "Texte", replyToMessageID: "msg_1"))222 r = try #require(StubServer.seen.last)223 #expect(r.path == "/api/v3/admin/courrier/envoi" && r.json["from"] as? String == "contact@immo-ka.com" && r.json["to"] as? [String] == ["support@immo-ka.com"])224 #expect(r.json["subject"] as? String == "[essai] Bonjour" && r.json["reply_to_message_id"] as? String == "msg_1" && r.json["cc"] == nil)225 let att = try JSONDecoder().decode(MailAttachment.self, from: Data(#"{"id":"att_1","name":"Bail.pdf","type":"application/pdf","size":4}"#.utf8))226 let file = try await a.attachment(messageID: "msg_1", attachment: att)227 defer { try? FileManager.default.removeItem(at: file.url.deletingLastPathComponent()) }228 let written = try Data(contentsOf: file.url)229 #expect(file.bytes == 4 && file.url.lastPathComponent == "Bail.pdf" && written == Data([0x25, 0x50, 0x44, 0x46]))230 #expect(StubServer.seen.last?.headers["Authorization"] == "Bearer jeton-1" && file.url.path.hasPrefix(FileManager.default.temporaryDirectory.path))231 }232233 @Test("erreurs : message du serveur tel quel, phrases de repli, 401 non_authentifie distingué, hors ligne")234 func errors() async throws {235 func failure(_ r: StubResponse) async -> AdminError? {236 StubServer.install { _ in r }237 do { _ = try await api().me(); return nil } catch { return error as? AdminError }238 }239 let reason = await failure(.json(#"{"error":{"code":"motif_requis","message":"Un motif est obligatoire pour refuser.","param":"reason","request_id":"r"}}"#, status: 422))240 #expect(reason?.code == "motif_requis" && reason?.errorDescription == "Un motif est obligatoire pour refuser." && reason?.isUnauthenticated == false)241 let expired = await failure(.error(401, "non_authentifie", "Ouvrez une session d'administration."))242 #expect(expired?.isUnauthenticated == true)243 let other401 = await failure(.error(401, "cle_inconnue", "Cette clé d'accès n'est pas reconnue."))244 #expect(other401?.isUnauthenticated == false && other401?.errorDescription == "Cette clé d'accès n'est pas reconnue.")245 #expect(await failure(StubResponse(status: 502, body: Data("<html>".utf8)))?.errorDescription == "Le serveur a rencontré une erreur. Réessayez dans un instant.")246 #expect(await failure(StubResponse(status: 403))?.errorDescription == "Cette action vous est refusée.")247 #expect(await failure(StubResponse(status: 429))?.code == "http_429")248 let offline = await failure(.down), unreadable = await failure(.json("pas du json"))249 #expect(offline == .offline && unreadable == .decoding)250 }251}252253@Suite("Session d'administration")254@MainActor255struct AdminSessionTests {256 private func session(_ store: MemoryStore = MemoryStore()) -> AdminSession { AdminSession(store: store, session: StubServer.session(), base: { base }) }257258 @Test("sans session : rien au coffre, écran de connexion")259 func signedOut() {260 let s = session()261 #expect(!s.isSignedIn && !s.restoring && !s.hasStoredSession && !s.ended && !s.locked)262 }263264 @Test("session gardée : confirmée par le serveur au lancement ; 401 non_authentifie → écran de connexion, jeton effacé")265 func restoreAndExpire() async throws {266 let store = MemoryStore()267 store.set(AdminSession.tokenKey, "jeton-garde")268 let expired = Counter()269 StubServer.install { r in expired.next() > 2 ? .error(401, "non_authentifie", "Ouvrez une session d'administration.") : (r.path.hasSuffix("/journal") ? .json(#"{"items":[]}"#) : .json(meJSON)) }270 let s = session(store)271 #expect(s.restoring && s.hasStoredSession && !s.isSignedIn)272 await s.restore()273 #expect(s.isSignedIn && !s.restoring && s.me?.admin.name == "Léa" && StubServer.seen.first?.headers["Authorization"] == "Bearer jeton-garde")274 _ = try await s.call { try await $0.journal() }275 await #expect(throws: AdminError.self) { _ = try await s.call { try await $0.journal() } }276 #expect(!s.isSignedIn && s.ended && store.string(AdminSession.tokenKey) == nil && !s.hasStoredSession, "session refusée : retour à la connexion, rien ne reste au coffre")277 }278279 @Test("session trop vieille au coffre : écartée sans appel au serveur")280 func stale() throws {281 let store = MemoryStore()282 store.set(AdminSession.tokenKey, "vieux-jeton")283 let old = Date().addingTimeInterval(-13 * 3600)284 store.write(AdminSession.windowKey, try JSONEncoder().encode(SessionWindow(openedAt: old, lastActivity: old, idleHours: 12, maxHours: 168)))285 StubServer.install { _ in .json(meJSON) }286 let s = session(store)287 #expect(!s.restoring && !s.hasStoredSession && s.ended && store.string(AdminSession.tokenKey) == nil && StubServer.seen.isEmpty)288 }289290 @Test("hors ligne au lancement : la session gardée n'est pas effacée")291 func offlineRestore() async {292 let store = MemoryStore()293 store.set(AdminSession.tokenKey, "jeton-garde")294 StubServer.install { _ in .down }295 let s = session(store)296 await s.restore()297 #expect(!s.isSignedIn && !s.restoring && !s.ended && store.string(AdminSession.tokenKey) == "jeton-garde")298 }299300 @Test("activation : adresse refusée sans appel au serveur ; déconnexion : jeton effacé")301 func activationAndSignOut() async throws {302 StubServer.install { r in r.path.hasSuffix("/deconnexion") ? .noContent : .json(meJSON) }303 let store = MemoryStore()304 let s = session(store)305 do { try await s.activate(link: "https://www.immo-ka.com/admin/activation", keyName: ""); Issue.record("adresse sans jeton") } catch let e as AdminError {306 #expect(e.code == "adresse_invalide" && (e.errorDescription ?? "").contains("jeton"))307 }308 #expect(StubServer.seen.isEmpty)309 store.set(AdminSession.tokenKey, "jeton-garde")310 let t = session(store)311 await t.restore()312 #expect(t.isSignedIn)313 await t.signOut()314 #expect(!t.isSignedIn && !t.ended && store.string(AdminSession.tokenKey) == nil && StubServer.seen("POST", "/deconnexion").count == 1)315 }316317 @Test("verrouillage : arrière-plan de plus de quelques minutes, pas avant ; jamais sans session")318 func lock() async {319 let store = MemoryStore()320 store.set(AdminSession.tokenKey, "jeton-garde")321 StubServer.install { _ in .json(meJSON) }322 let s = session(store)323 await s.restore()324 let t0 = Date()325 s.didEnterBackground(now: t0)326 s.willEnterForeground(now: t0.addingTimeInterval(30))327 #expect(!s.locked, "un passage bref à l'arrière-plan ne verrouille pas")328 s.didEnterBackground(now: t0)329 s.didEnterBackground(now: t0.addingTimeInterval(100)) // l'heure retenue est celle de la sortie330 s.willEnterForeground(now: t0.addingTimeInterval(LockPolicy.delay + 1))331 #expect(s.locked && s.isSignedIn, "verrouillée, mais la session reste")332 let out = session()333 out.didEnterBackground(now: t0)334 out.willEnterForeground(now: t0.addingTimeInterval(3600))335 #expect(!out.locked)336 }337}338}339