| 1 | import Foundation |
| 2 | import Testing |
| 3 | @testable import EquipoKit |
| 4 | |
| 5 | private func err(_ status: Int, _ code: String) -> Result<APIResponse, EquipoAPIError> { |
| 6 | .success(APIResponse(status: status, data: Data(#"{"code":"\#(code)","copy_key":"api.\#(code)","request_id":"r"}"#.utf8))) |
| 7 | } |
| 8 | |
| 9 | /// Records each wait; never actually sleeps. |
| 10 | final class Sleeps: @unchecked Sendable { |
| 11 | private let lock = NSLock(); private(set) var waits: [Duration] = [] |
| 12 | var sleep: @Sendable (Duration) async throws -> Void { { d in self.lock.withLock { self.waits.append(d) } } } |
| 13 | } |
| 14 | |
| 15 | @MainActor @Suite struct PairingTests { |
| 16 | @Test func pairsAfterPendingAndSlowDown() async throws { |
| 17 | let t = ScriptedTransport() |
| 18 | t.on("POST /auth/devices", fixture: "device-challenge") |
| 19 | t.on("POST /auth/devices/exchange", err(409, "authorization_pending"), err(429, "slow_down"), .success(APIResponse(status: 200, data: Fixture.data("device-credential")))) |
| 20 | t.on("GET /me", fixture: "me") |
| 21 | let store = MemorySecretStore(); let sleeps = Sleeps() |
| 22 | let model = PairingModel(accounts: DeviceAccounts(store: store), makeTransport: { _ in t }, sleep: sleeps.sleep) |
| 23 | await model.run(origin: t.origin, label: "Test") |
| 24 | |
| 25 | #expect(model.step == .approved(teamName: "Oficina")) |
| 26 | // One proof, resent unchanged: same key, same body, same nonce. |
| 27 | let polls = t.sent("POST /auth/devices/exchange") |
| 28 | #expect(polls.count == 3) |
| 29 | #expect(Set(polls.map(\.idempotencyKey)).count == 1) |
| 30 | #expect(Set(polls.map(\.body)).count == 1) |
| 31 | #expect(polls.allSatisfy { $0.bearer == nil }) |
| 32 | // Never faster than five seconds; slower after slow_down. |
| 33 | #expect(sleeps.waits.allSatisfy { $0 >= .seconds(5) }) |
| 34 | #expect(sleeps.waits.last == .seconds(10)) |
| 35 | // The credential is kept, with the key that earned it. |
| 36 | let saved = try #require(DeviceAccounts(store: store).all().first) |
| 37 | #expect(saved.credential?.token == "equipo.person.v1.TOKENFIXTURE") |
| 38 | #expect(saved.teamName == "Oficina") |
| 39 | let begin = try JSONSerialization.jsonObject(with: t.sent("POST /auth/devices")[0].body!) as! [String: String] |
| 40 | #expect(begin["public_key"] == (try saved.publicKey())) |
| 41 | } |
| 42 | |
| 43 | @Test func aServerAskingForFasterPollsStillWaitsFiveSeconds() async throws { |
| 44 | let t = ScriptedTransport() |
| 45 | let fast = String(decoding: Fixture.data("device-challenge"), as: UTF8.self) |
| 46 | .replacingOccurrences(of: "\"poll_interval_seconds\": 5", with: "\"poll_interval_seconds\": 1") |
| 47 | #expect(fast.contains("\"poll_interval_seconds\": 1")) |
| 48 | t.on("POST /auth/devices", .success(APIResponse(status: 200, data: Data(fast.utf8)))) |
| 49 | t.on("POST /auth/devices/exchange", err(409, "authorization_pending"), .success(APIResponse(status: 200, data: Fixture.data("device-credential")))) |
| 50 | t.on("GET /me", fixture: "me") |
| 51 | let sleeps = Sleeps() |
| 52 | let model = PairingModel(accounts: DeviceAccounts(store: MemorySecretStore()), makeTransport: { _ in t }, sleep: sleeps.sleep) |
| 53 | await model.run(origin: t.origin, label: "Test") |
| 54 | #expect(!sleeps.waits.isEmpty) |
| 55 | #expect(sleeps.waits.allSatisfy { $0 == .seconds(5) }) |
| 56 | } |
| 57 | |
| 58 | @Test func aCredentialIsKeptEvenIfTheFirstReadFails() async throws { |
| 59 | let t = ScriptedTransport() |
| 60 | t.on("POST /auth/devices", fixture: "device-challenge") |
| 61 | t.on("POST /auth/devices/exchange", fixture: "device-credential") |
| 62 | t.on("GET /me", .success(APIResponse(status: 500, data: Data(#"{"code":"internal","copy_key":"api.internal","request_id":"r"}"#.utf8)))) |
| 63 | let store = MemorySecretStore() |
| 64 | let model = PairingModel(accounts: DeviceAccounts(store: store), makeTransport: { _ in t }, sleep: Sleeps().sleep) |
| 65 | await model.run(origin: t.origin, label: "Test") |
| 66 | let saved = try #require(DeviceAccounts(store: store).all().first, "the server holds a live device: so must we") |
| 67 | #expect(saved.credential?.token == "equipo.person.v1.TOKENFIXTURE") |
| 68 | guard case .approved = model.step else { Issue.record("paired, team name to follow: \(model.step)"); return } |
| 69 | } |
| 70 | |
| 71 | @Test func expiredChallengeStops() async throws { |
| 72 | let t = ScriptedTransport() |
| 73 | t.on("POST /auth/devices", fixture: "device-challenge") |
| 74 | t.on("POST /auth/devices/exchange", err(410, "device_expired")) |
| 75 | let model = PairingModel(accounts: DeviceAccounts(store: MemorySecretStore()), makeTransport: { _ in t }, sleep: Sleeps().sleep) |
| 76 | await model.run(origin: t.origin, label: "Test") |
| 77 | #expect(model.step == .expired) |
| 78 | } |
| 79 | |
| 80 | @Test func keyIsSavedBeforeTheServerHearsOfIt() async throws { |
| 81 | let t = ScriptedTransport() |
| 82 | t.on("POST /auth/devices", .failure(.offline)) |
| 83 | let store = MemorySecretStore() |
| 84 | let model = PairingModel(accounts: DeviceAccounts(store: store), makeTransport: { _ in t }, sleep: Sleeps().sleep) |
| 85 | await model.run(origin: t.origin, label: "Test") |
| 86 | #expect(DeviceAccounts(store: store).all().count == 1) |
| 87 | if case .failed = model.step {} else { Issue.record("expected failure, got \(model.step)") } |
| 88 | // Offline begins are retried as themselves. |
| 89 | #expect(Set(t.sent("POST /auth/devices").map(\.idempotencyKey)).count == 1) |
| 90 | } |
| 91 | |
| 92 | @Test func theBrowserPageMustBeTheTeams() async throws { |
| 93 | let t = ScriptedTransport() |
| 94 | var challenge = try JSONSerialization.jsonObject(with: Fixture.data("device-challenge")) as! [String: Any] |
| 95 | challenge["verification_uri"] = "https://elsewhere.example.test/approve" |
| 96 | t.on("POST /auth/devices", .success(APIResponse(status: 200, data: try JSONSerialization.data(withJSONObject: challenge)))) |
| 97 | let model = PairingModel(accounts: DeviceAccounts(store: MemorySecretStore()), makeTransport: { _ in t }, sleep: Sleeps().sleep) |
| 98 | await model.run(origin: t.origin, label: "Test") |
| 99 | if case .failed = model.step {} else { Issue.record("a foreign approval page was accepted: \(model.step)") } |
| 100 | #expect(t.sent("POST /auth/devices/exchange").isEmpty) |
| 101 | } |
| 102 | |
| 103 | @Test func originParsing() { |
| 104 | #expect(PairingModel.origin(from: "paulca.equipo.oficina.works")?.absoluteString == "https://paulca.equipo.oficina.works") |
| 105 | #expect(PairingModel.origin(from: " https://Team.Example.test/some/path?x ")?.absoluteString == "https://team.example.test") |
| 106 | #expect(PairingModel.origin(from: "http://team.example.test") == nil) |
| 107 | #expect(PairingModel.origin(from: "https://user@team.example.test") == nil) |
| 108 | #expect(PairingModel.origin(from: "") == nil) |
| 109 | // Plain http only to this machine. |
| 110 | #expect(PairingModel.origin(from: "http://127.0.0.1:8824")?.absoluteString == "http://127.0.0.1:8824") |
| 111 | #expect(PairingModel.origin(from: "http://localhost:8824/x")?.absoluteString == "http://localhost:8824") |
| 112 | #expect(PairingModel.origin(from: "http://127.0.0.1.example.test") == nil) |
| 113 | #expect(PairingModel.origin(from: "http://10.0.0.5:8824") == nil) |
| 114 | // The default port is the same place as no port. |
| 115 | #expect(PairingModel.origin(from: "team.example.test:443")?.absoluteString == "https://team.example.test") |
| 116 | #expect(PairingModel.origin(from: "https://team.example.test:8443")?.absoluteString == "https://team.example.test:8443") |
| 117 | } |
| 118 | } |
| 119 | |