| 1 | @testable import BaseKit |
| 2 | import Foundation |
| 3 | import Network |
| 4 | import RastrilloApple |
| 5 | import RastrilloTestSupport |
| 6 | import XCTest |
| 7 | |
| 8 | enum Fixture { |
| 9 | static func data(_ name: String) -> Data { |
| 10 | let url = Bundle.module.url(forResource: "Fixtures/\(name)", withExtension: nil)! |
| 11 | return try! Data(contentsOf: url) |
| 12 | } |
| 13 | static func snapshot(_ name: String) -> AskSnapshot { try! JSONDecoder().decode(AskSnapshot.self, from: data(name)) } |
| 14 | } |
| 15 | |
| 16 | /// Counts the kit's `sessionRejected()` calls. |
| 17 | final class Rejections: @unchecked Sendable { |
| 18 | private let lock = NSLock() |
| 19 | private var n = 0 |
| 20 | var count: Int { lock.withLock { n } } |
| 21 | func hit() { lock.withLock { n += 1 } } |
| 22 | } |
| 23 | |
| 24 | func json(_ status: Int, _ body: String) -> ScriptedTransport.Step { .respond(status: status, body: Data(body.utf8)) } |
| 25 | |
| 26 | /// Form fields of a scripted call's body. |
| 27 | func fields(_ call: ScriptedTransport.Call) -> [String: String] { |
| 28 | guard let body = call.body, let text = String(data: body, encoding: .utf8) else { return [:] } |
| 29 | var out: [String: String] = [:] |
| 30 | for pair in text.split(separator: "&") { |
| 31 | let parts = pair.split(separator: "=", maxSplits: 1).map(String.init) |
| 32 | out[parts[0]] = (parts.count > 1 ? parts[1] : "").replacingOccurrences(of: "+", with: " ").removingPercentEncoding |
| 33 | } |
| 34 | return out |
| 35 | } |
| 36 | |
| 37 | /// One HTTP/1.1 exchange on localhost: records the request NativeHTTP |
| 38 | /// really sends, and answers it. |
| 39 | final class LocalServer: @unchecked Sendable { |
| 40 | let listener: NWListener |
| 41 | private let lock = NSLock() |
| 42 | private var requests: [String] = [] |
| 43 | private let answer: @Sendable (String) -> (Int, String) |
| 44 | var port: UInt16 { listener.port!.rawValue } |
| 45 | var origin: URL { URL(string: "http://localhost:\(port)")! } |
| 46 | var received: [String] { lock.withLock { requests } } |
| 47 | |
| 48 | init(answer: @escaping @Sendable (String) -> (Int, String)) throws { |
| 49 | self.answer = answer |
| 50 | listener = try NWListener(using: .tcp, on: .any) |
| 51 | listener.newConnectionHandler = { [weak self] connection in self?.serve(connection) } |
| 52 | let ready = DispatchSemaphore(value: 0) |
| 53 | listener.stateUpdateHandler = { if case .ready = $0 { ready.signal() } } |
| 54 | listener.start(queue: .global()) |
| 55 | _ = ready.wait(timeout: .now() + 5) |
| 56 | } |
| 57 | |
| 58 | private func serve(_ connection: NWConnection) { |
| 59 | connection.start(queue: .global()) |
| 60 | var buffer = Data() |
| 61 | func read() { |
| 62 | connection.receive(minimumIncompleteLength: 1, maximumLength: 65536) { [weak self] data, _, done, _ in |
| 63 | guard let self else { return } |
| 64 | if let data { buffer.append(data) } |
| 65 | let text = String(decoding: buffer, as: UTF8.self) |
| 66 | if let head = text.range(of: "\r\n\r\n") { |
| 67 | let length = text[..<head.lowerBound].split(separator: "\r\n") |
| 68 | .first { $0.lowercased().hasPrefix("content-length:") } |
| 69 | .flatMap { Int($0.split(separator: ":")[1].trimmingCharacters(in: .whitespaces)) } ?? 0 |
| 70 | if buffer.count - text[..<head.upperBound].utf8.count >= length { |
| 71 | self.lock.withLock { self.requests.append(text) } |
| 72 | let (status, body) = self.answer(text) |
| 73 | 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)" |
| 74 | connection.send(content: Data(reply.utf8), completion: .contentProcessed { _ in connection.cancel() }) |
| 75 | return |
| 76 | } |
| 77 | } |
| 78 | if done { connection.cancel() } else { read() } |
| 79 | } |
| 80 | } |
| 81 | read() |
| 82 | } |
| 83 | |
| 84 | deinit { listener.cancel() } |
| 85 | } |
| 86 | |
| 87 | /// A transport whose answers wait until the test releases them, path by |
| 88 | /// path: for races (an old account's answer landing after a new sign-in). |
| 89 | final class GatedTransport: NativeTransport, @unchecked Sendable { |
| 90 | let origin: URL |
| 91 | private let lock = NSLock() |
| 92 | private var answers: [String: (Int, Data)] = [:] |
| 93 | private var headers: [String: [String: String]] = [:] |
| 94 | private var waiting: [String: [CheckedContinuation<Void, Never>]] = [:] |
| 95 | private var released: Set<String> = [] |
| 96 | private var seen: [String] = [] |
| 97 | private var sent: [(String, Data?)] = [] |
| 98 | init(origin: URL = URL(string: "https://gated.invalid")!) { self.origin = origin } |
| 99 | var calls: [String] { lock.withLock { seen } } |
| 100 | /// The bodies posted to `path`, in order. |
| 101 | func bodies(_ path: String) -> [Data?] { lock.withLock { sent.filter { $0.0 == path }.map(\.1) } } |
| 102 | |
| 103 | /// What `path` answers once released. |
| 104 | func answer(_ path: String, status: Int = 200, headers: [String: String] = [:], _ body: String) { |
| 105 | lock.withLock { answers[path] = (status, Data(body.utf8)); self.headers[path] = headers } |
| 106 | } |
| 107 | func release(_ path: String) { |
| 108 | let ready = lock.withLock { () -> [CheckedContinuation<Void, Never>] in |
| 109 | released.insert(path) |
| 110 | defer { waiting[path] = nil } |
| 111 | return waiting[path] ?? [] |
| 112 | } |
| 113 | for c in ready { c.resume() } |
| 114 | } |
| 115 | func responseDetails(_ path: String, method: String, body: Data?, contentType: String, maxBytes: Int) async throws -> NativeResponse { |
| 116 | await withCheckedContinuation { (c: CheckedContinuation<Void, Never>) in |
| 117 | let go = lock.withLock { () -> Bool in |
| 118 | seen.append(path) |
| 119 | sent.append((path, body)) |
| 120 | if released.contains(path) { return true } |
| 121 | waiting[path, default: []].append(c) |
| 122 | return false |
| 123 | } |
| 124 | if go { c.resume() } |
| 125 | } |
| 126 | let (status, data, head) = lock.withLock { () -> (Int, Data, [String: String]) in |
| 127 | let (s, d) = answers[path] ?? (404, Data()) |
| 128 | return (s, d, headers[path] ?? [:]) |
| 129 | } |
| 130 | return NativeResponse(data: data, status: status, headers: head) |
| 131 | } |
| 132 | func stream(_ path: String, onOpen: @Sendable () async throws -> Void, onLine: @Sendable (String) async throws -> Void) async throws { |
| 133 | lock.withLock { seen.append(path) } |
| 134 | try await Task.sleep(for: .seconds(3600)) |
| 135 | } |
| 136 | func download(_ path: String, to destination: URL) async throws {} |
| 137 | } |
| 138 | |
| 139 | /// A kit model that never touches the keychain, App Group or network. |
| 140 | @MainActor func memoryOficina() -> OficinaIDModel { |
| 141 | let suite = "BaseKitTests.\(UUID().uuidString)" |
| 142 | let defaults = UserDefaults(suiteName: suite)! |
| 143 | let store = OficinaIDStore(shared: OficinaMemoryStore(), appPrivate: OficinaMemoryStore(), group: defaults) |
| 144 | return OficinaIDModel(configuration: BaseSession.configuration, store: store, service: FakeOficinaIDService(), |
| 145 | passkeys: FakePasskeys(), appDefaults: defaults) |
| 146 | } |
| 147 | |
| 148 | /// A kit model signed in for real through the kit's in-memory Oficina ID, |
| 149 | /// to a person in two teams, each with a Base (`.invalid` origins: nothing |
| 150 | /// leaves the machine). |
| 151 | @MainActor func signedInOficina() async throws -> (OficinaIDModel, [OficinaTeam]) { |
| 152 | let service = FakeOficinaIDService() |
| 153 | service.addPerson(email: "paul@fennel.example", identityID: "id-paul") |
| 154 | let teams = ["fennel", "rye"].map { label in |
| 155 | OficinaTeam(sqid: "t-\(label)", label: label, name: label.capitalized, role: "member", |
| 156 | apps: [OficinaTeamApp(app: "base", origin: "https://\(label).base.invalid", consumerID: "t-\(label)-base")]) |
| 157 | } |
| 158 | service.setTeams(teams, for: "id-paul") |
| 159 | for team in teams { service.admit("id-paul", at: team.origin(for: "base")!, as: .linked) } |
| 160 | let defaults = UserDefaults(suiteName: "BaseKitTests.\(UUID().uuidString)")! |
| 161 | let store = OficinaIDStore(shared: OficinaMemoryStore(), appPrivate: OficinaMemoryStore(), group: defaults) |
| 162 | let model = OficinaIDModel(configuration: BaseSession.configuration, store: store, service: service, |
| 163 | passkeys: FakePasskeys(), makeKey: { OficinaSoftwareKey() }, appDefaults: defaults) |
| 164 | await model.start() |
| 165 | model.continueWithEmail() |
| 166 | model.email = "paul@fennel.example" |
| 167 | await model.submitEmail() |
| 168 | model.code = FakeOficinaIDService.goodCode |
| 169 | await model.submitCode() |
| 170 | if case .teams(let list) = model.step, let first = list.first { await model.choose(first) } |
| 171 | guard case .signedIn = model.step else { throw XCTSkip("the fake sign-in did not complete: \(model.step)") } |
| 172 | return (model, teams) |
| 173 | } |
| 174 | |
| 175 | /// Defaults of its own for each test: nothing a test keeps (a Disconnect) |
| 176 | /// reaches another, or the next run. |
| 177 | func freshDefaults() -> UserDefaults { UserDefaults(suiteName: "BaseKitTests.\(UUID().uuidString)")! } |
| 178 | |