Repository Public
1import Foundation2import Testing3@testable import MCCCore45/// Parent of every integration suite: they share one server, one owner account and rate-limited public endpoints,6/// so they run one after the other (the trait applies to the nested suites).7@Suite("Integration", .serialized, .enabled(if: IT.enabled))8struct Integration {}910/// Environment of the integration tests (set by Scripts/integration-test.sh). Without it they are skipped.11enum IT {12 static let env = ProcessInfo.processInfo.environment13 static let origin: URL? = env["MCC_IT_ORIGIN"].flatMap(URL.init(string:))14 static var enabled: Bool { origin != nil && env["MCC_IT_DATABASE"] != nil }15 static var database: String { env["MCC_IT_DATABASE"] ?? "" }1617 @discardableResult18 static func run(_ tool: String, _ args: [String]) throws -> String {19 let p = Process()20 p.executableURL = URL(fileURLWithPath: tool)21 p.arguments = args22 let out = Pipe(), err = Pipe()23 p.standardOutput = out24 p.standardError = err25 try p.run()26 let data = out.fileHandleForReading.readDataToEndOfFile()27 let errData = err.fileHandleForReading.readDataToEndOfFile()28 p.waitUntilExit()29 guard p.terminationStatus == 0 else {30 throw APIError(code: "test.process", message: "\(tool) failed: \(String(decoding: errData, as: UTF8.self))")31 }32 return String(decoding: data, as: UTF8.self).trimmingCharacters(in: .whitespacesAndNewlines)33 }3435 @discardableResult36 static func psql(_ sql: String) throws -> String {37 try run(env["MCC_IT_PSQL"] ?? "/opt/homebrew/bin/psql", ["-X", "-q", "-A", "-t", "-v", "ON_ERROR_STOP=1", "-d", database, "-c", sql])38 }3940 static func ownerSetupToken(handle: String, name: String) throws -> String {41 try run("/bin/bash", [env["MCC_IT_BACKEND_SCRIPT"] ?? "", "owner", database, handle, name])42 }4344 static func publish(topic: String, payload: String) throws {45 try psql("with e as (insert into events_outbox(topic, payload) values ('\(topic)', '\(payload)'::jsonb) returning seq) select seq from e, pg_notify('mcc_events', '')")46 }4748 /// The public endpoints are rate limited per IP; a test that hits the limit waits and retries.49 static func patiently<T: Sendable>(_ op: @Sendable () async throws -> T) async throws -> T {50 var last: any Error = APIError.cancelled51 for _ in 0..<15 {52 do { return try await op() } catch {53 let e = APIError.from(error)54 guard e.status == 429 else { throw e }55 last = e56 // A ceremony needs several tokens of the bucket (0.5/s): wait for a few, not just one.57 try await Task.sleep(for: .seconds(max(6, e.retryAfter ?? 0)))58 }59 }60 throw last61 }6263 struct Seat: Sendable {64 let api: APIClient65 let auth: AuthService66 let store: InMemorySecureStore67 let authenticator: SoftwareAuthenticator68 }6970 static func seat(authenticator: SoftwareAuthenticator? = nil, store: InMemorySecureStore = InMemorySecureStore(), label: String = "IT Mac") -> Seat {71 let a = authenticator ?? SoftwareAuthenticator(origin: origin!.absoluteString)72 let api = APIClient(origin: origin!, secureStore: store, userAgent: "MCCCoreTests/1.0")73 let auth = AuthService(api: api, passkeys: a) {74 DeviceInfo(kind: .macos, label: label, model: "Mac16,9", osVersion: "macOS 27.0.0", appVersion: "1.0.0 (test)")75 }76 return Seat(api: api, auth: auth, store: store, authenticator: a)77 }7879 static func signedIn(as authenticator: SoftwareAuthenticator, label: String = "IT Mac") async throws -> Seat {80 let s = seat(authenticator: authenticator, label: label)81 _ = try await patiently { try await s.auth.signIn() }82 return s83 }8485 static let owner = OwnerFixture()86 static let sharedOwner = SharedSeat()87}8889/// Creates the first owner once per test database through the real out-of-band path (`mccctl bootstrap-owner`)90/// and the real invitation flow, with the software authenticator.91actor OwnerFixture {92 private var task: Task<SoftwareAuthenticator, any Error>?93 private(set) var firstSeat: IT.Seat?94 private(set) var firstRegistration: API.RegistrationResult?95 private(set) var transaction: API.InvitationTransaction?9697 func authenticator() async throws -> SoftwareAuthenticator {98 if let task { return try await task.value }99 let t = Task { () throws -> SoftwareAuthenticator in100 let token = try IT.ownerSetupToken(handle: "owner-it", name: "Owner IT")101 let seat = IT.seat(label: "Owner Mac")102 let tx = try await IT.patiently { try await seat.auth.exchangeInvitation(token: token) }103 let reg = try await IT.patiently { try await seat.auth.completeInvitation(passkeyLabel: "Software key") }104 self.record(seat, reg, tx)105 return seat.authenticator106 }107 task = t108 return try await t.value109 }110111 private func record(_ seat: IT.Seat, _ reg: API.RegistrationResult, _ tx: API.InvitationTransaction) {112 firstSeat = seat; firstRegistration = reg; transaction = tx113 }114}115116/// One long-lived owner session shared by the tests that do not destroy it (the public endpoints are rate limited).117actor SharedSeat {118 private var task: Task<IT.Seat, any Error>?119 func seat() async throws -> IT.Seat {120 if let task { return try await task.value }121 let t = Task { try await IT.signedIn(as: try await IT.owner.authenticator(), label: "Second Mac") }122 task = t123 return try await t.value124 }125}126