import Foundation import Testing @testable import EquipoKit private func err(_ status: Int, _ code: String) -> Result { .success(APIResponse(status: status, data: Data(#"{"code":"\#(code)","copy_key":"api.\#(code)","request_id":"r"}"#.utf8))) } /// Records each wait; never actually sleeps. final class Sleeps: @unchecked Sendable { private let lock = NSLock(); private(set) var waits: [Duration] = [] var sleep: @Sendable (Duration) async throws -> Void { { d in self.lock.withLock { self.waits.append(d) } } } } @MainActor @Suite struct PairingTests { @Test func pairsAfterPendingAndSlowDown() async throws { let t = ScriptedTransport() t.on("POST /auth/devices", fixture: "device-challenge") t.on("POST /auth/devices/exchange", err(409, "authorization_pending"), err(429, "slow_down"), .success(APIResponse(status: 200, data: Fixture.data("device-credential")))) t.on("GET /me", fixture: "me") let store = MemorySecretStore(); let sleeps = Sleeps() let model = PairingModel(accounts: DeviceAccounts(store: store), makeTransport: { _ in t }, sleep: sleeps.sleep) await model.run(origin: t.origin, label: "Test") #expect(model.step == .approved(teamName: "Oficina")) // One proof, resent unchanged: same key, same body, same nonce. let polls = t.sent("POST /auth/devices/exchange") #expect(polls.count == 3) #expect(Set(polls.map(\.idempotencyKey)).count == 1) #expect(Set(polls.map(\.body)).count == 1) #expect(polls.allSatisfy { $0.bearer == nil }) // Never faster than five seconds; slower after slow_down. #expect(sleeps.waits.allSatisfy { $0 >= .seconds(5) }) #expect(sleeps.waits.last == .seconds(10)) // The credential is kept, with the key that earned it. let saved = try #require(DeviceAccounts(store: store).all().first) #expect(saved.credential?.token == "equipo.person.v1.TOKENFIXTURE") #expect(saved.teamName == "Oficina") let begin = try JSONSerialization.jsonObject(with: t.sent("POST /auth/devices")[0].body!) as! [String: String] #expect(begin["public_key"] == (try saved.publicKey())) } @Test func aServerAskingForFasterPollsStillWaitsFiveSeconds() async throws { let t = ScriptedTransport() let fast = String(decoding: Fixture.data("device-challenge"), as: UTF8.self) .replacingOccurrences(of: "\"poll_interval_seconds\": 5", with: "\"poll_interval_seconds\": 1") #expect(fast.contains("\"poll_interval_seconds\": 1")) t.on("POST /auth/devices", .success(APIResponse(status: 200, data: Data(fast.utf8)))) t.on("POST /auth/devices/exchange", err(409, "authorization_pending"), .success(APIResponse(status: 200, data: Fixture.data("device-credential")))) t.on("GET /me", fixture: "me") let sleeps = Sleeps() let model = PairingModel(accounts: DeviceAccounts(store: MemorySecretStore()), makeTransport: { _ in t }, sleep: sleeps.sleep) await model.run(origin: t.origin, label: "Test") #expect(!sleeps.waits.isEmpty) #expect(sleeps.waits.allSatisfy { $0 == .seconds(5) }) } @Test func aCredentialIsKeptEvenIfTheFirstReadFails() async throws { let t = ScriptedTransport() t.on("POST /auth/devices", fixture: "device-challenge") t.on("POST /auth/devices/exchange", fixture: "device-credential") t.on("GET /me", .success(APIResponse(status: 500, data: Data(#"{"code":"internal","copy_key":"api.internal","request_id":"r"}"#.utf8)))) let store = MemorySecretStore() let model = PairingModel(accounts: DeviceAccounts(store: store), makeTransport: { _ in t }, sleep: Sleeps().sleep) await model.run(origin: t.origin, label: "Test") let saved = try #require(DeviceAccounts(store: store).all().first, "the server holds a live device: so must we") #expect(saved.credential?.token == "equipo.person.v1.TOKENFIXTURE") guard case .approved = model.step else { Issue.record("paired, team name to follow: \(model.step)"); return } } @Test func expiredChallengeStops() async throws { let t = ScriptedTransport() t.on("POST /auth/devices", fixture: "device-challenge") t.on("POST /auth/devices/exchange", err(410, "device_expired")) let model = PairingModel(accounts: DeviceAccounts(store: MemorySecretStore()), makeTransport: { _ in t }, sleep: Sleeps().sleep) await model.run(origin: t.origin, label: "Test") #expect(model.step == .expired) } @Test func keyIsSavedBeforeTheServerHearsOfIt() async throws { let t = ScriptedTransport() t.on("POST /auth/devices", .failure(.offline)) let store = MemorySecretStore() let model = PairingModel(accounts: DeviceAccounts(store: store), makeTransport: { _ in t }, sleep: Sleeps().sleep) await model.run(origin: t.origin, label: "Test") #expect(DeviceAccounts(store: store).all().count == 1) if case .failed = model.step {} else { Issue.record("expected failure, got \(model.step)") } // Offline begins are retried as themselves. #expect(Set(t.sent("POST /auth/devices").map(\.idempotencyKey)).count == 1) } @Test func theBrowserPageMustBeTheTeams() async throws { let t = ScriptedTransport() var challenge = try JSONSerialization.jsonObject(with: Fixture.data("device-challenge")) as! [String: Any] challenge["verification_uri"] = "https://elsewhere.example.test/approve" t.on("POST /auth/devices", .success(APIResponse(status: 200, data: try JSONSerialization.data(withJSONObject: challenge)))) let model = PairingModel(accounts: DeviceAccounts(store: MemorySecretStore()), makeTransport: { _ in t }, sleep: Sleeps().sleep) await model.run(origin: t.origin, label: "Test") if case .failed = model.step {} else { Issue.record("a foreign approval page was accepted: \(model.step)") } #expect(t.sent("POST /auth/devices/exchange").isEmpty) } @Test func originParsing() { #expect(PairingModel.origin(from: "paulca.equipo.oficina.works")?.absoluteString == "https://paulca.equipo.oficina.works") #expect(PairingModel.origin(from: " https://Team.Example.test/some/path?x ")?.absoluteString == "https://team.example.test") #expect(PairingModel.origin(from: "http://team.example.test") == nil) #expect(PairingModel.origin(from: "https://user@team.example.test") == nil) #expect(PairingModel.origin(from: "") == nil) // Plain http only to this machine. #expect(PairingModel.origin(from: "http://127.0.0.1:8824")?.absoluteString == "http://127.0.0.1:8824") #expect(PairingModel.origin(from: "http://localhost:8824/x")?.absoluteString == "http://localhost:8824") #expect(PairingModel.origin(from: "http://127.0.0.1.example.test") == nil) #expect(PairingModel.origin(from: "http://10.0.0.5:8824") == nil) // The default port is the same place as no port. #expect(PairingModel.origin(from: "team.example.test:443")?.absoluteString == "https://team.example.test") #expect(PairingModel.origin(from: "https://team.example.test:8443")?.absoluteString == "https://team.example.test:8443") } }