@testable import BaseKit import Foundation import Network import RastrilloApple import RastrilloTestSupport import XCTest enum Fixture { static func data(_ name: String) -> Data { let url = Bundle.module.url(forResource: "Fixtures/\(name)", withExtension: nil)! return try! Data(contentsOf: url) } static func snapshot(_ name: String) -> AskSnapshot { try! JSONDecoder().decode(AskSnapshot.self, from: data(name)) } } /// Counts the kit's `sessionRejected()` calls. final class Rejections: @unchecked Sendable { private let lock = NSLock() private var n = 0 var count: Int { lock.withLock { n } } func hit() { lock.withLock { n += 1 } } } func json(_ status: Int, _ body: String) -> ScriptedTransport.Step { .respond(status: status, body: Data(body.utf8)) } /// Form fields of a scripted call's body. func fields(_ call: ScriptedTransport.Call) -> [String: String] { guard let body = call.body, let text = String(data: body, encoding: .utf8) else { return [:] } var out: [String: String] = [:] for pair in text.split(separator: "&") { let parts = pair.split(separator: "=", maxSplits: 1).map(String.init) out[parts[0]] = (parts.count > 1 ? parts[1] : "").replacingOccurrences(of: "+", with: " ").removingPercentEncoding } return out } /// One HTTP/1.1 exchange on localhost: records the request NativeHTTP /// really sends, and answers it. final class LocalServer: @unchecked Sendable { let listener: NWListener private let lock = NSLock() private var requests: [String] = [] private let answer: @Sendable (String) -> (Int, String) var port: UInt16 { listener.port!.rawValue } var origin: URL { URL(string: "http://localhost:\(port)")! } var received: [String] { lock.withLock { requests } } init(answer: @escaping @Sendable (String) -> (Int, String)) throws { self.answer = answer listener = try NWListener(using: .tcp, on: .any) listener.newConnectionHandler = { [weak self] connection in self?.serve(connection) } let ready = DispatchSemaphore(value: 0) listener.stateUpdateHandler = { if case .ready = $0 { ready.signal() } } listener.start(queue: .global()) _ = ready.wait(timeout: .now() + 5) } private func serve(_ connection: NWConnection) { connection.start(queue: .global()) var buffer = Data() func read() { connection.receive(minimumIncompleteLength: 1, maximumLength: 65536) { [weak self] data, _, done, _ in guard let self else { return } if let data { buffer.append(data) } let text = String(decoding: buffer, as: UTF8.self) if let head = text.range(of: "\r\n\r\n") { let length = text[..= length { self.lock.withLock { self.requests.append(text) } let (status, body) = self.answer(text) let reply = "HTTP/1.1 \(status) X\r\nContent-Type: application/json\r\nContent-Length: \(body.utf8.count)\r\nConnection: close\r\n\r\n\(body)" connection.send(content: Data(reply.utf8), completion: .contentProcessed { _ in connection.cancel() }) return } } if done { connection.cancel() } else { read() } } } read() } deinit { listener.cancel() } } /// A transport whose answers wait until the test releases them, path by /// path: for races (an old account's answer landing after a new sign-in). final class GatedTransport: NativeTransport, @unchecked Sendable { let origin: URL private let lock = NSLock() private var answers: [String: (Int, Data)] = [:] private var headers: [String: [String: String]] = [:] private var waiting: [String: [CheckedContinuation]] = [:] private var released: Set = [] private var seen: [String] = [] private var sent: [(String, Data?)] = [] init(origin: URL = URL(string: "https://gated.invalid")!) { self.origin = origin } var calls: [String] { lock.withLock { seen } } /// The bodies posted to `path`, in order. func bodies(_ path: String) -> [Data?] { lock.withLock { sent.filter { $0.0 == path }.map(\.1) } } /// What `path` answers once released. func answer(_ path: String, status: Int = 200, headers: [String: String] = [:], _ body: String) { lock.withLock { answers[path] = (status, Data(body.utf8)); self.headers[path] = headers } } func release(_ path: String) { let ready = lock.withLock { () -> [CheckedContinuation] in released.insert(path) defer { waiting[path] = nil } return waiting[path] ?? [] } for c in ready { c.resume() } } func responseDetails(_ path: String, method: String, body: Data?, contentType: String, maxBytes: Int) async throws -> NativeResponse { await withCheckedContinuation { (c: CheckedContinuation) in let go = lock.withLock { () -> Bool in seen.append(path) sent.append((path, body)) if released.contains(path) { return true } waiting[path, default: []].append(c) return false } if go { c.resume() } } let (status, data, head) = lock.withLock { () -> (Int, Data, [String: String]) in let (s, d) = answers[path] ?? (404, Data()) return (s, d, headers[path] ?? [:]) } return NativeResponse(data: data, status: status, headers: head) } func stream(_ path: String, onOpen: @Sendable () async throws -> Void, onLine: @Sendable (String) async throws -> Void) async throws { lock.withLock { seen.append(path) } try await Task.sleep(for: .seconds(3600)) } func download(_ path: String, to destination: URL) async throws {} } /// A kit model that never touches the keychain, App Group or network. @MainActor func memoryOficina() -> OficinaIDModel { let suite = "BaseKitTests.\(UUID().uuidString)" let defaults = UserDefaults(suiteName: suite)! let store = OficinaIDStore(shared: OficinaMemoryStore(), appPrivate: OficinaMemoryStore(), group: defaults) return OficinaIDModel(configuration: BaseSession.configuration, store: store, service: FakeOficinaIDService(), passkeys: FakePasskeys(), appDefaults: defaults) } /// A kit model signed in for real through the kit's in-memory Oficina ID, /// to a person in two teams, each with a Base (`.invalid` origins: nothing /// leaves the machine). @MainActor func signedInOficina() async throws -> (OficinaIDModel, [OficinaTeam]) { let service = FakeOficinaIDService() service.addPerson(email: "paul@fennel.example", identityID: "id-paul") let teams = ["fennel", "rye"].map { label in OficinaTeam(sqid: "t-\(label)", label: label, name: label.capitalized, role: "member", apps: [OficinaTeamApp(app: "base", origin: "https://\(label).base.invalid", consumerID: "t-\(label)-base")]) } service.setTeams(teams, for: "id-paul") for team in teams { service.admit("id-paul", at: team.origin(for: "base")!, as: .linked) } let defaults = UserDefaults(suiteName: "BaseKitTests.\(UUID().uuidString)")! let store = OficinaIDStore(shared: OficinaMemoryStore(), appPrivate: OficinaMemoryStore(), group: defaults) let model = OficinaIDModel(configuration: BaseSession.configuration, store: store, service: service, passkeys: FakePasskeys(), makeKey: { OficinaSoftwareKey() }, appDefaults: defaults) await model.start() model.continueWithEmail() model.email = "paul@fennel.example" await model.submitEmail() model.code = FakeOficinaIDService.goodCode await model.submitCode() if case .teams(let list) = model.step, let first = list.first { await model.choose(first) } guard case .signedIn = model.step else { throw XCTSkip("the fake sign-in did not complete: \(model.step)") } return (model, teams) } /// Defaults of its own for each test: nothing a test keeps (a Disconnect) /// reaches another, or the next run. func freshDefaults() -> UserDefaults { UserDefaults(suiteName: "BaseKitTests.\(UUID().uuidString)")! }