oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1import Foundation
2import RastrilloApple
3import RastrilloTestSupport
4import Testing
5@testable import EquipoKit
6
7private final class IDClock: @unchecked Sendable {
8 private let lock = NSLock()
9 private var date = Date()
10 var now: Date { lock.withLock { date } }
11 func advance(_ seconds: TimeInterval) { lock.withLock { date += seconds } }
12}
13
14@MainActor private final class IDFixture {
15 let service = FakeOficinaIDService()
16 let shared = OficinaMemoryStore()
17 let privateStore = OficinaMemoryStore()
18 let secrets = MemorySecretStore()
19 let transport = ScriptedTransport()
20 let clock = IDClock()
21 let notifications = FakeNotifications()
22 let suite = "EquipoIDTests.\(UUID().uuidString)"
23 let defaults: UserDefaults
24 let model: OficinaIDModel
25 let app: EquipoAppModel
26
27 init(held: (any EquipoTransport)? = nil) {
28 defaults = UserDefaults(suiteName: suite)!
29 let store = OficinaIDStore(shared: shared, appPrivate: privateStore, group: defaults)
30 let clock = clock
31 model = OficinaIDModel(configuration: EquipoOficinaID.configuration, store: store, service: service,
32 passkeys: FakePasskeys(), makeKey: { OficinaSoftwareKey() }, now: { clock.now }, appDefaults: defaults)
33 let transport = transport
34 app = EquipoAppModel(store: secrets, notifications: notifications, push: PushRegistrar(environment: nil), oficinaModel: model,
35 makeTransport: { _ in if let held { held } else { transport } }, now: { clock.now }, deviceLabel: { "Test phone" })
36 service.addPerson(email: "person@example.test", identityID: "id-1")
37 service.setTeams([team()], for: "id-1")
38 service.admit("id-1", at: transport.origin, as: .linked)
39 transport.on("POST /auth/devices/native", fixture: "device-credential")
40 transport.on("GET /auth/devices", fixture: "devices")
41 transport.on("DELETE /auth/devices/dev_01JD5Z4Q2X", fixture: "ack")
42 }
43 deinit { UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) }
44 func team(_ id: String = "t1", app: String = "equipo") -> OficinaTeam {
45 OficinaTeam(sqid: id, label: id, name: "Team \(id)", role: "member", apps: [
46 OficinaTeamApp(app: app, origin: transport.origin.absoluteString, consumerID: id)
47 ])
48 }
49 func signIn() async {
50 await app.start()
51 model.continueWithEmail(); model.email = "person@example.test"
52 await model.submitEmail(); model.code = FakeOficinaIDService.goodCode
53 await model.submitCode()
54 await app.oficina.synchronize()
55 }
56 func seedIdentity() async throws {
57 let key = OficinaSoftwareKey()
58 let start = try await service.startCode(email: "person@example.test", key: key, platform: "macos")
59 guard case .granted(let grant) = try await service.verifyCode(start: start.start, code: FakeOficinaIDService.goodCode, key: key) else { throw EquipoAPIError.signedOut }
60 _ = try model.store.add(grant: grant, key: key, label: "Person", labelSource: .email, method: "code", now: clock.now)
61 }
62}
63
64@MainActor @Suite struct OficinaIDTests {
65 @Test func firstAppShowsWelcomeThenKeepsDeviceAndFreshKey() async throws {
66 let f = IDFixture()
67 await f.app.start()
68 #expect(f.model.step == .welcome)
69 #expect(f.app.session == nil)
70 #expect(!f.app.showingPairing)
71 await f.signIn()
72 let account = try #require(f.app.session?.account)
73 #expect(account.oficinaIdentity == "id-1")
74 #expect(account.oficinaTeam == "t1")
75 #expect(f.app.accounts.all() == [account])
76 let request = try #require(f.transport.sent("POST /auth/devices/native").first)
77 let body = try JSONDecoder().decode([String: String].self, from: #require(request.body))
78 #expect(body == ["public_key": try account.publicKey(), "label": "Test phone"])
79 let wire = try request.urlRequest(origin: f.transport.origin)
80 #expect(wire.url?.path == "/api/v1/auth/devices/native")
81 #expect(wire.value(forHTTPHeaderField: "Origin") == f.transport.origin.absoluteString)
82 #expect(wire.value(forHTTPHeaderField: "Cookie")?.hasPrefix("__Host-rastrillo_session=") == true)
83 #expect(wire.value(forHTTPHeaderField: "Authorization") == nil)
84 #expect(wire.value(forHTTPHeaderField: "Content-Type") == "application/json")
85 #expect(!wire.httpShouldHandleCookies)
86 await f.app.oficina.synchronize()
87 #expect(f.transport.sent("POST /auth/devices/native").count == 1)
88 let bearer = try APIRequest("GET", "/snapshot", bearer: account.credential?.token).urlRequest(origin: account.origin)
89 #expect(bearer.value(forHTTPHeaderField: "Cookie") == nil)
90 }
91
92 @Test func oneIdentityGoesStraightInAndSeveralTeamsOrNoneUseKit() async throws {
93 for count in [0, 1, 2] {
94 let f = IDFixture()
95 f.service.setTeams((0..<count).map { f.team("t\($0)") } + [f.team("docs", app: "docs")], for: "id-1")
96 try await f.seedIdentity()
97 await f.app.start()
98 if count == 1 {
99 #expect(f.app.session?.account.oficinaTeam == "t0")
100 } else if count == 0 {
101 #expect(f.model.step == .noTeams)
102 #expect(f.app.session == nil)
103 } else {
104 guard case .teams(let teams) = f.model.step else { Issue.record("expected kit's team step"); return }
105 #expect(teams.count == 2)
106 #expect(f.app.session == nil)
107 await f.model.choose(teams[1]); await f.app.oficina.synchronize()
108 #expect(f.app.session?.account.oficinaTeam == "t1")
109 }
110 }
111 }
112
113 @Test func renewsAfter24HoursWithoutReplacingConversationSession() async throws {
114 let f = IDFixture(); await f.signIn()
115 let original = try #require(f.app.session)
116 let key = original.account.keySeed
117 await f.app.oficina.renewIfNeeded()
118 #expect(f.transport.sent("POST /auth/devices/native").count == 1)
119 f.clock.advance(24 * 60 * 60 + 1)
120 await f.app.oficina.renewIfNeeded()
121 #expect(f.transport.sent("POST /auth/devices/native").count == 2)
122 #expect(f.app.session === original)
123 #expect(f.app.session?.account.keySeed != key)
124 }
125
126 @Test func rejectionsRemintOnceAndRetryWithTheNewBearer() async throws {
127 for status in [401, 403] {
128 let f = IDFixture(); await f.signIn()
129 let original = try #require(f.app.session)
130 let next = String(decoding: Fixture.data("device-credential"), as: UTF8.self).replacingOccurrences(of: "TOKENFIXTURE", with: "RENEWED")
131 f.transport.replace("POST /auth/devices/native", with: .success(APIResponse(status: 200, data: Data(next.utf8))))
132 f.transport.on("GET /me", .success(APIResponse(status: status, data: Data())), .success(APIResponse(status: 200, data: Fixture.data("me"))))
133 _ = try await original.client.me()
134 #expect(f.transport.sent("POST /auth/devices/native").count == 2)
135 #expect(f.transport.sent("GET /me").count == 2)
136 #expect(f.transport.sent("GET /me").last?.bearer == "equipo.person.v1.RENEWED")
137 // Both ordinary requests remain device bearers, never cookies.
138 #expect(f.transport.sent("GET /me").allSatisfy { $0.bearer != nil && $0.nativeSession == nil })
139 }
140 }
141
142 @Test func offlineRenewalKeepsAccountAndSignOutForgetsItImmediately() async throws {
143 let f = IDFixture(); await f.signIn()
144 let original = try #require(f.app.session)
145 f.clock.advance(24 * 60 * 60 + 1)
146 f.service.failNext("assert", with: .offline)
147 await f.app.oficina.renewIfNeeded()
148 #expect(f.app.session === original)
149 await f.app.signOut()
150 #expect(f.app.session == nil)
151 #expect(f.app.accounts.all().isEmpty)
152 #expect(f.model.identity == nil)
153 await f.app.oficina.cleanup?.value
154 await f.model.cleanup?.value
155 #expect(f.service.liveGrants == 0)
156 #expect(!f.transport.sent("GET /auth/devices").isEmpty)
157 }
158
159 @Test func pairingFallbackSuspendsStraightInAndReturnResumesIt() async throws {
160 let f = IDFixture(); try await f.seedIdentity()
161 f.app.otherWays()
162 await f.app.start()
163 #expect(f.app.showingPairing)
164 #expect(f.model.step == .welcome)
165 #expect(!f.service.calls.contains { $0.hasPrefix("assert ") })
166 #expect(f.app.session == nil)
167 #expect(f.transport.sent("POST /auth/devices/native").isEmpty)
168 await f.app.useOficinaID()
169 #expect(!f.app.showingPairing)
170 #expect(f.app.session != nil)
171 }
172
173 @Test func foregroundRecoversAfterARejectedSessionMetAnOutage() async throws {
174 let f = IDFixture(); await f.signIn()
175 let original = try #require(f.app.session)
176 f.service.failNext("assert", at: f.transport.origin.absoluteString, with: .offline)
177 f.transport.on("GET /me", .success(APIResponse(status: 401, data: Data())))
178 _ = try? await original.client.me()
179 #expect(f.app.session === original)
180 guard case .unavailable = f.model.step else { Issue.record("expected an unavailable team"); return }
181 f.clock.advance(61)
182 await f.app.oficina.renewIfNeeded()
183 guard case .signedIn = f.model.step else { Issue.record("foreground did not recover"); return }
184 #expect(f.app.session === original)
185 #expect(f.transport.sent("POST /auth/devices/native").count == 2)
186 }
187
188 @Test func signingInWhileAlreadyForegroundStartsTheConversation() async throws {
189 let f = IDFixture()
190 await f.app.start()
191 f.app.foreground()
192 await f.signIn()
193 for _ in 0..<100 {
194 if !f.transport.sent("GET /snapshot").isEmpty { break }
195 try await Task.sleep(for: .milliseconds(10))
196 }
197 f.app.background()
198 #expect(!f.transport.sent("GET /snapshot").isEmpty)
199 }
200
201 @Test func dailyTimerRenewsWhileAppStaysOpen() async throws {
202 let f = IDFixture(); await f.signIn()
203 let sleep = IDDailySleep(clock: f.clock)
204 await f.app.runRenewals(sleep: { try await sleep.wait($0) })
205 #expect(f.transport.sent("POST /auth/devices/native").count == 2)
206 #expect(await sleep.waits == [.seconds(86400), .seconds(86400)])
207 }
208
209 @Test func aDefinite403StaysARefusalAfterRemint() async throws {
210 let f = IDFixture(); await f.signIn()
211 let next = String(decoding: Fixture.data("device-credential"), as: UTF8.self).replacingOccurrences(of: "TOKENFIXTURE", with: "RENEWED")
212 f.transport.replace("POST /auth/devices/native", with: .success(APIResponse(status: 200, data: Data(next.utf8))))
213 f.transport.on("GET /me", .success(APIResponse(status: 403, data: Data())))
214 do {
215 _ = try await f.app.session?.client.me()
216 Issue.record("the permission refusal disappeared")
217 } catch let error as EquipoAPIError {
218 #expect(error.status == 403)
219 }
220 #expect(f.transport.sent("GET /me").count == 2)
221 #expect(f.transport.sent("POST /auth/devices/native").count == 2)
222 }
223
224 @Test func rejectedEventStreamRemintsAndPreservesCursor() async throws {
225 for status in [401, 403] {
226 let f = IDFixture(); await f.signIn()
227 let next = String(decoding: Fixture.data("device-credential"), as: UTF8.self).replacingOccurrences(of: "TOKENFIXTURE", with: "RENEWED")
228 f.transport.replace("POST /auth/devices/native", with: .success(APIResponse(status: 200, data: Data(next.utf8))))
229 f.transport.onStream(.failure(.status(status)), .success([]))
230 let session = try #require(f.app.session)
231 let stream = try await session.client.events(after: 42)
232 for try await _ in stream {}
233 let requests = f.transport.sent("GET /events")
234 #expect(requests.count == 2)
235 #expect(requests.allSatisfy { $0.query == [URLQueryItem(name: "after", value: "42")] })
236 #expect(requests.last?.bearer == "equipo.person.v1.RENEWED")
237 #expect(f.transport.sent("POST /auth/devices/native").count == 2)
238 }
239 }
240
241 @Test func repeatedRejectionsAreRateLimitedAndKeepConversation() async throws {
242 let f = IDFixture(); await f.signIn()
243 let original = try #require(f.app.session)
244 f.transport.on("GET /me", .success(APIResponse(status: 401, data: Data())))
245 for _ in 0..<3 { _ = try? await original.client.me() }
246 #expect(f.transport.sent("POST /auth/devices/native").count == 2)
247 #expect(f.app.session === original)
248 }
249
250 @Test func signOutStopsPushesAndRevokesThisDevice() async throws {
251 let f = IDFixture(); await f.signIn()
252 #expect(f.notifications.asked > 0)
253 await f.app.push.attach(f.app.session?.client)
254 let generation = f.app.push.generation
255 f.app.needsYouChanged(3)
256 await f.app.signOut()
257 #expect(f.notifications.unregistered == 1)
258 #expect(f.app.accounts.all().isEmpty)
259 #expect(f.notifications.badges.last == 0)
260 #expect(f.app.session == nil)
261 await f.app.oficina.cleanup?.value
262 #expect(f.app.push.generation == generation + 1)
263 #expect(f.transport.sent("DELETE /auth/devices/dev_01JD5Z4Q2X").count == 1)
264 let count = f.transport.sent("POST /auth/devices/native").count
265 await f.app.oficina.renewIfNeeded()
266 #expect(f.transport.sent("POST /auth/devices/native").count == count)
267 #expect(f.model.step == .welcome)
268 }
269
270 @Test func replacementThroughKitAlsoForgetsDeviceAndPushes() async throws {
271 let f = IDFixture(); await f.signIn()
272 f.model.useAnother()
273 #expect(f.app.session != nil)
274 f.model.cancelReplace()
275 #expect(f.app.session != nil)
276 f.model.useAnother(); f.model.confirmReplace()
277 #expect(f.app.session == nil)
278 #expect(f.app.accounts.all().isEmpty)
279 #expect(f.notifications.unregistered == 1)
280 #expect(f.model.step == .email)
281 }
282
283 @Test func sharedIdentityRemovalLeavesAnActiveFallbackPairingAlone() async throws {
284 let f = IDFixture(); await f.signIn()
285 f.app.otherWays()
286 var paired = DeviceAccount.new(origin: f.transport.origin, label: "Paired")
287 paired.credential = try Fixture.decode("device-credential")
288 try f.app.accounts.commit(.save(paired), lifetime: f.app.accounts.lifetimes.current)
289 f.app.adopt(paired, transport: f.transport)
290 f.model.signOut()
291 #expect(f.app.session?.account == paired)
292 #expect(f.app.accounts.all() == [paired])
293 }
294
295 @Test func onlyDeviceRegistrationMaySendTheSessionCookie() throws {
296 for path in ["/snapshot", "/auth/devices", "/auth/devices/exchange"] {
297 #expect(throws: EquipoAPIError.badOrigin) {
298 try APIRequest("POST", path, nativeSession: NativeSession(name: "session", value: "fixture"))
299 .urlRequest(origin: URL(string: "https://example.test")!)
300 }
301 }
302 }
303
304 @Test func deviceEndpointRejectionRemintsTheKitSession() async throws {
305 let f = IDFixture()
306 f.transport.replace("POST /auth/devices/native", with: .success(APIResponse(status: 403, data: Data())))
307 f.transport.on("POST /auth/devices/native", fixture: "device-credential")
308 await f.signIn()
309 #expect(f.app.session != nil)
310 #expect(f.transport.sent("POST /auth/devices/native").count == 2)
311 let cookies = f.transport.sent("POST /auth/devices/native").compactMap { $0.nativeSession?.value }
312 #expect(Set(cookies).count == 2)
313 }
314
315 @Test func nativeCredentialWhoseIdentityWasRemovedCannotSurviveRelaunch() async throws {
316 let f = IDFixture(); await f.signIn()
317 try f.model.store.remove("id-1")
318 let transport = f.transport
319 let freshModel = OficinaIDModel(configuration: EquipoOficinaID.configuration,
320 store: OficinaIDStore(shared: f.shared, appPrivate: f.privateStore, group: f.defaults),
321 service: f.service, passkeys: FakePasskeys(), makeKey: { OficinaSoftwareKey() }, appDefaults: f.defaults)
322 let relaunched = EquipoAppModel(store: f.secrets, push: PushRegistrar(environment: nil), oficinaModel: freshModel,
323 makeTransport: { _ in transport })
324 await relaunched.start()
325 #expect(relaunched.session == nil)
326 #expect(relaunched.accounts.all().isEmpty)
327 }
328
329 @Test func lateRegistrationCannotRestoreSignedOutDevice() async throws {
330 let held = HeldIDTransport()
331 let f = IDFixture(held: held)
332 try await f.seedIdentity()
333 let start = Task { await f.app.start() }
334 await held.waitUntilEntered()
335 await f.app.signOut()
336 await held.release()
337 await start.value
338 #expect(f.app.session == nil)
339 #expect(f.app.accounts.all().isEmpty)
340 #expect(f.model.identity == nil)
341 }
342
343 @Test func lateSnapshotCannotRestoreSignedOutDevice() async throws {
344 let held = HeldEquipoRead()
345 let f = IDFixture(held: held)
346 await f.signIn()
347 let departed = try #require(f.app.session)
348 await held.hold("/snapshot")
349 let refresh = Task { await departed.refresh() }
350 await held.waitUntilEntered()
351 await f.app.signOut()
352 #expect(f.app.accounts.all().isEmpty)
353 await held.release()
354 await refresh.value
355 #expect(departed.status == .signedOut)
356 #expect(departed.me == nil)
357 #expect(f.app.session == nil)
358 #expect(f.app.accounts.all().isEmpty)
359 }
360
361 @Test func lateRenewalCannotRestoreSignedOutDevice() async throws {
362 let held = HeldEquipoRead()
363 let f = IDFixture(held: held)
364 await f.signIn()
365 let departed = try #require(f.app.session)
366 let oldAccount = departed.account
367 f.clock.advance(86401)
368 await held.nativeToken("ABANDONED")
369 await held.hold("/auth/devices/native")
370 let renewal = Task { await f.app.oficina.renewIfNeeded() }
371 await held.waitUntilEntered()
372 await f.app.signOut()
373 await held.release()
374 await renewal.value
375 #expect(f.app.session == nil)
376 #expect(f.app.accounts.all().isEmpty)
377 #expect(f.app.oficina.account == nil)
378 #expect(f.model.identity == nil)
379 #expect(await held.sent("DELETE /auth/devices/dev_01JD5Z4Q2X").contains { $0.bearer == "equipo.person.v1.ABANDONED" })
380 // Even a queued adoption and direct metadata update cannot reopen
381 // the departed session or save its private key again.
382 departed.renew(oldAccount, transport: held)
383 departed.apply(try Fixture.decode("thin/snapshot"))
384 #expect(departed.status == .signedOut)
385 #expect(f.app.accounts.all().isEmpty)
386 }
387
388 @Test(arguments: ["pairing", "replacement", "ended"])
389 func departingSessionCannotPersistAfterItsReplacement(_ route: String) async throws {
390 let held = HeldEquipoRead()
391 let f = IDFixture(held: held); await f.signIn()
392 let departed = try #require(f.app.session)
393 await held.hold("/snapshot")
394 let refresh = Task { await departed.refresh() }
395 await held.waitUntilEntered()
396 switch route {
397 case "pairing": f.app.otherWays()
398 case "replacement":
399 var next = departed.account
400 next.oficinaTeam = "replacement"
401 try f.app.accounts.commit(.save(next), lifetime: f.app.accounts.lifetimes.current)
402 f.app.adopt(next, transport: held)
403 default: f.app.sessionEnded()
404 }
405 let saved = f.app.accounts.all()
406 await held.release()
407 await refresh.value
408 #expect(departed.status == .signedOut)
409 #expect(departed.me == nil)
410 #expect(f.app.accounts.all() == saved)
411 }
412
413 @Test func latePairingRevocationCannotRemoveANewCredential() async throws {
414 let held = HeldEquipoRead()
415 let accounts = DeviceAccounts(store: MemorySecretStore())
416 var old = DeviceAccount.new(origin: held.origin, label: "Old phone")
417 old.credential = try Fixture.decode("device-credential")
418 try accounts.commit(.save(old), lifetime: accounts.lifetimes.current)
419 let departed = EquipoSession(account: old, accounts: accounts, transport: held)
420 await held.hold("/auth/devices")
421 let signOut = Task { await departed.signOut() }
422 await held.waitUntilEntered()
423 #expect(departed.status == .signedOut)
424 #expect(accounts.all().isEmpty)
425 var replacement = old
426 replacement.keySeed = DeviceAccount.new(origin: held.origin, label: "New phone").keySeed
427 accounts.lifetimes.begin()
428 try accounts.commit(.save(replacement), lifetime: accounts.lifetimes.current)
429 await held.release()
430 await signOut.value
431 #expect(accounts.all() == [replacement])
432 }
433
434 @Test func unavailableRenewalShowsRecoveryWithoutAnErrorString() async throws {
435 let f = IDFixture(); await f.signIn()
436 let original = try #require(f.app.session)
437 #expect(EquipoOficinaNotice(model: f.app).message == nil)
438 f.service.failNext("assert", at: f.transport.origin.absoluteString, with: .offline)
439 f.transport.on("GET /me", .success(APIResponse(status: 401, data: Data())))
440 _ = try? await original.client.me()
441 guard case .unavailable = f.model.step else { Issue.record("expected an unavailable team"); return }
442 #expect(f.app.oficina.error == nil)
443 #expect(f.model.error == nil)
444 #expect(EquipoOficinaNotice(model: f.app).message == OficinaIDText.text("unavailable.title"))
445 #expect(f.app.session === original)
446 await f.app.oficina.renewIfNeeded()
447 #expect(EquipoOficinaNotice(model: f.app).message == nil)
448 #expect(f.app.session === original)
449 }
450
451 @Test(arguments: ["/auth/devices/exchange", "/me"], [false, true])
452 func cancelledPairingCannotOverwriteNativeSignIn(_ boundary: String, _ signOut: Bool) async throws {
453 let held = HeldEquipoRead()
454 let f = IDFixture(held: held)
455 try await f.seedIdentity()
456 f.app.otherWays(); await f.app.start()
457 await held.hold(boundary)
458 f.app.pairing.start(origin: held.origin, label: "Abandoned pairing")
459 await held.waitUntilEntered()
460 await held.nativeToken("NEW_SIGN_IN")
461 await f.app.useOficinaID()
462 let native = try #require(f.app.session?.account)
463 if signOut { await f.app.signOut(); await f.app.oficina.cleanup?.value }
464 await held.release()
465 // Wait for the abandoned pairing's network cleanup as well as /me.
466 for _ in 0..<200 {
467 if await held.sent("DELETE /auth/devices/dev_01JD5Z4Q2X").contains(where: { $0.bearer == "equipo.person.v1.TOKENFIXTURE" }) { break }
468 try await Task.sleep(for: .milliseconds(5))
469 }
470 #expect(f.app.accounts.all() == (signOut ? [] : [native]))
471 #expect(f.app.pairing.account == nil)
472 #expect(f.app.pairing.step == .enterTeam)
473 #expect(await held.sent("DELETE /auth/devices/dev_01JD5Z4Q2X").contains { $0.bearer == "equipo.person.v1.TOKENFIXTURE" })
474 }
475
476 @Test func departedWriteCannotRetryWithALaterSignInsBearer() async throws {
477 let held = HeldEquipoRead()
478 let f = IDFixture(held: held); await f.signIn()
479 let departed = try #require(f.app.session)
480 let outer = try #require(departed.client.transport as? LifetimeTransport)
481 let renewing = try #require(outer.inner as? EquipoRenewingTransport)
482 let snapshot: Snapshot = try Fixture.decode("thin/snapshot")
483 let card = try #require(snapshot.cards?.first { $0.isOpen })
484 let route = "POST /cards/\(card.id)/answer"
485 await held.answerFailure(route)
486 await held.hold("/cards/\(card.id)/answer")
487 let answer = Task { await departed.answer(card, choice: "wait_mac") }
488 await held.waitUntilEntered()
489 await f.app.signOut()
490 await f.app.oficina.cleanup?.value
491 await f.model.cleanup?.value
492 await held.nativeToken("NEW_SIGN_IN")
493 await f.signIn()
494 #expect(f.app.session?.account.credential?.token == "equipo.person.v1.NEW_SIGN_IN")
495 #expect(renewing.credential() == nil)
496 await held.release()
497 #expect(await answer.value == .failed)
498 #expect(await held.sent(route).count == 1)
499 // A retained client is also bound, independently of the write loop.
500 _ = try? await departed.client.me()
501 #expect(await held.sent("GET /me").isEmpty)
502 }
503
504 @Test(arguments: [false, true])
505 func endedWriteLoopsDoNotWaitOrRetry(_ aside: Bool) async throws {
506 let held = HeldEquipoRead()
507 let f = IDFixture(held: held); await f.signIn()
508 let current = try #require(f.app.session)
509 let sleeps = Sleeps()
510 let worker = EquipoSession(account: current.account, accounts: f.app.accounts,
511 transport: current.client.transport, lifetime: current.lifetime, sleep: sleeps.sleep)
512 let snapshot: Snapshot = try Fixture.decode("thin/snapshot")
513 let card = try #require(snapshot.cards?.first { $0.kind == "merge" && $0.isOpen })
514 let path = "/cards/\(card.id)/" + (aside ? "visibility" : "answer")
515 await held.answerFailure("POST " + path)
516 await held.hold(path)
517 let write = Task { aside ? await worker.setAside(card, true) : await worker.answer(card, choice: "wait_mac") }
518 await held.waitUntilEntered()
519 await f.app.signOut()
520 await held.release()
521 #expect(await write.value == .failed)
522 #expect(sleeps.waits.isEmpty)
523 #expect(await held.sent("POST " + path).count == 1)
524 }
525
526 @Test func endedTransportRefusesLateResponsesAndNewRequests() async throws {
527 let held = HeldEquipoRead()
528 let lifetimes = SignInLifetimes()
529 let lifetime = lifetimes.current
530 let transport = LifetimeTransport(inner: held, lifetime: lifetime)
531 await held.hold("/me")
532 let read = Task { try await transport.send(APIRequest("GET", "/me", bearer: "old")) }
533 await held.waitUntilEntered()
534 lifetimes.begin()
535 await held.release()
536 var rejected = false
537 do { _ = try await read.value } catch is CancellationError { rejected = true }
538 #expect(rejected)
539 _ = try? await transport.send(APIRequest("GET", "/snapshot", bearer: "old"))
540 #expect(await held.sent("GET /snapshot").isEmpty)
541 }
542
543 @Test(arguments: [false, true])
544 func cancellingPairingAloneEndsItsLifetime(_ signOut: Bool) async throws {
545 let held = HeldEquipoRead()
546 let f = IDFixture(held: held)
547 f.app.otherWays(); await f.app.start()
548 await held.hold("/auth/devices/exchange")
549 f.app.pairing.start(origin: held.origin, label: "Cancelled")
550 await held.waitUntilEntered()
551 let lifetime = try #require(f.app.pairing.lifetime)
552 if signOut { await f.app.signOut() } else { f.app.pairing.cancel() }
553 #expect(!lifetime.isActive)
554 await held.release()
555 for _ in 0..<200 {
556 if !(await held.sent("DELETE /auth/devices/dev_01JD5Z4Q2X")).isEmpty { break }
557 try await Task.sleep(for: .milliseconds(5))
558 }
559 #expect(f.app.accounts.all().isEmpty)
560 #expect(f.app.pairing.step == .enterTeam)
561 #expect(await held.sent("DELETE /auth/devices/dev_01JD5Z4Q2X").count == 1)
562 }
563
564 @Test(arguments: [false, true])
565 func signOutBeforeRegistrationEndsThePendingLifetime(_ throughKit: Bool) async {
566 let f = IDFixture()
567 let lifetime = f.app.accounts.lifetimes.current
568 if throughKit { f.app.oficina.signOut() } else { await f.app.signOut() }
569 #expect(!lifetime.isActive)
570 #expect(f.app.accounts.all().isEmpty)
571 }
572
573 @Test func signingOutAfterTheSessionEndsStillForgetsItsCredential() async throws {
574 let f = IDFixture(); await f.signIn()
575 f.app.sessionEnded()
576 await f.app.signOut()
577 #expect(f.app.accounts.all().isEmpty)
578 await f.app.oficina.cleanup?.value
579 #expect(f.transport.sent("DELETE /auth/devices/dev_01JD5Z4Q2X").count == 1)
580 }
581
582 @Test(arguments: ["continueAs", "unavailable"], ["appSignOut", "bridgeSignOut", "replacement", "pairing"])
583 func leavingBeforeBridgeSynchronizesForgetsEveryNativeAccount(_ landing: String, _ route: String) async throws {
584 let f = IDFixture()
585 try await f.seedIdentity()
586 var native = DeviceAccount.new(origin: f.transport.origin, label: "Saved native")
587 native.credential = try Fixture.decode("device-credential")
588 native.oficinaIdentity = "id-1"
589 var another = native
590 another.origin = URL(string: "https://another.example.test")!
591 another.oficinaIdentity = "another-identity"
592 var paired = native
593 paired.origin = URL(string: "https://paired.example.test")!
594 paired.oficinaIdentity = nil
595 for account in [native, another, paired] {
596 try f.app.accounts.commit(.save(account), lifetime: f.app.accounts.lifetimes.current)
597 }
598 f.service.failNext("assert", with: .offline)
599 await f.app.start()
600 if landing == "unavailable" {
601 f.service.failNext("assert", at: f.transport.origin.absoluteString, with: .offline)
602 await f.model.choose(f.team())
603 }
604 if landing == "continueAs" {
605 guard case .continueAs = f.model.step else { Issue.record("expected Continue as"); return }
606 } else {
607 guard case .unavailable = f.model.step else { Issue.record("expected unavailable"); return }
608 }
609 #expect(f.app.oficina.account == nil)
610 #expect(f.app.session == nil)
611 switch route {
612 case "appSignOut": await f.app.signOut()
613 case "bridgeSignOut": f.app.oficina.signOut()
614 case "replacement": f.model.useAnother(); f.model.confirmReplace()
615 default: f.app.otherWays()
616 }
617 #expect(f.app.accounts.all() == [paired])
618 await f.app.oficina.cleanup?.value
619 #expect(f.transport.sent("DELETE /auth/devices/dev_01JD5Z4Q2X").count == 2)
620 #expect(f.app.accounts.all() == [paired])
621 }
622
623 @Test(arguments: ["appSignOut", "bridgeSignOut", "pairing"])
624 func leavingBeforeIdentityLoadsForgetsTheSavedBearer(_ route: String) async throws {
625 let f = IDFixture()
626 var native = DeviceAccount.new(origin: f.transport.origin, label: "Saved native")
627 native.credential = try Fixture.decode("device-credential")
628 native.oficinaIdentity = "id-1"
629 try f.app.accounts.commit(.save(native), lifetime: f.app.accounts.lifetimes.current)
630 #expect(f.model.identity == nil)
631 switch route {
632 case "appSignOut": await f.app.signOut()
633 case "bridgeSignOut": f.app.oficina.signOut()
634 default: f.app.otherWays()
635 }
636 #expect(f.app.accounts.all().isEmpty)
637 await f.app.oficina.cleanup?.value
638 #expect(f.transport.sent("DELETE /auth/devices/dev_01JD5Z4Q2X").count == 1)
639 }
640
641 @Test(arguments: ["appSignOut", "bridgeSignOut", "replacement", "server"])
642 func onlyServerSessionEndShowsTheEndedTeamNotice(_ route: String) async throws {
643 let f = IDFixture(); await f.signIn()
644 let team = try #require(f.app.session?.teamName)
645 switch route {
646 case "appSignOut": await f.app.signOut()
647 case "bridgeSignOut": f.app.oficina.signOut()
648 case "replacement": f.model.useAnother(); f.model.confirmReplace()
649 default: f.app.sessionEnded()
650 }
651 f.app.otherWays()
652 #expect(f.app.endedTeam == (route == "server" ? team : nil))
653 }
654
655 @Test func permissionRefusalDuringHomeOutageKeepsTheKitSession() async throws {
656 let f = IDFixture(); await f.signIn()
657 let original = try #require(f.app.session)
658 let credential = try #require(try f.model.store.credential("id-1"))
659 let stored = try #require(f.model.store.session(grantID: credential.grantID, origin: f.transport.origin))
660 f.service.failNext("assert", at: f.transport.origin.absoluteString, with: .offline)
661 f.transport.on("GET /me", .success(APIResponse(status: 403, data: Data())))
662 do {
663 _ = try await original.client.me()
664 Issue.record("expected the permission refusal")
665 } catch let error as EquipoAPIError { #expect(error.status == 403) }
666 // The kit's only forced re-mint API deletes before contacting Home.
667 // Keep this executable reproduction until the kit can preserve a usable
668 // session during forced renewal. Unexpected success fails this test.
669 withKnownIssue("Kit sessionRejected deletes the usable session before an offline re-mint") {
670 #expect(f.model.store.session(grantID: credential.grantID, origin: f.transport.origin)?.session == stored.session)
671 }
672 #expect(f.app.session === original)
673 }
674
675 @Test func oldSavedPairingStillLoadsWithoutOficinaID() throws {
676 let f = IDFixture()
677 var account = DeviceAccount.new(origin: f.transport.origin, label: "Old phone")
678 account.credential = try Fixture.decode("device-credential")
679 try f.app.accounts.commit(.save(account), lifetime: f.app.accounts.lifetimes.current)
680 let relaunched = EquipoAppModel(store: f.secrets, push: PushRegistrar(environment: nil), oficinaModel: f.model)
681 #expect(relaunched.session?.account == account)
682 #expect(relaunched.showingPairing)
683 }
684}
685
686/// Holds the first device answer until sign-out has invalidated its request.
687private actor HeldIDTransport: EquipoTransport {
688 nonisolated let origin = URL(string: "https://oficina.example.test")!
689 private var entered = false
690 private var continuation: CheckedContinuation<Void, Never>?
691 func send(_ request: APIRequest) async throws -> APIResponse {
692 if request.path == "/auth/devices/native" {
693 entered = true
694 await withCheckedContinuation { continuation = $0 }
695 return APIResponse(status: 200, data: Fixture.data("device-credential"))
696 }
697 return APIResponse(status: 404, data: Data())
698 }
699 func lines(_ request: APIRequest) async throws -> AsyncThrowingStream<String, Error> { throw EquipoAPIError.offline }
700 func waitUntilEntered() async {
701 while !entered { await Task.yield() }
702 }
703 func release() { continuation?.resume(); continuation = nil }
704}
705
706private actor IDDailySleep {
707 let clock: IDClock
708 var waits: [Duration] = []
709 init(clock: IDClock) { self.clock = clock }
710 func wait(_ duration: Duration) throws {
711 waits.append(duration)
712 if waits.count > 1 { throw CancellationError() }
713 clock.advance(86401)
714 }
715}
716
717/// Lets an actual scripted response arrive after its caller has signed out.
718/// Cancellation deliberately does not release it: a network reply can be late.
719private actor HeldEquipoRead: EquipoTransport {
720 nonisolated let origin = URL(string: "https://oficina.example.test")!
721 private let script = ScriptedTransport()
722 private var path: String?
723 private var entered = false
724 private var continuation: CheckedContinuation<Void, Never>?
725 init() {
726 script.on("POST /auth/devices/native", fixture: "device-credential")
727 script.on("POST /auth/devices", fixture: "device-challenge")
728 script.on("POST /auth/devices/exchange", fixture: "device-credential")
729 script.on("GET /me", fixture: "me")
730 script.on("GET /auth/devices", fixture: "devices")
731 script.on("DELETE /auth/devices/dev_01JD5Z4Q2X", fixture: "ack")
732 script.on("GET /snapshot", fixture: "thin/snapshot")
733 script.on("GET /tasks", fixture: "thin/tasks")
734 script.on("GET /needs-you", fixture: "thin/needs-you")
735 }
736 func hold(_ path: String) { self.path = path; entered = false }
737 func send(_ request: APIRequest) async throws -> APIResponse {
738 let response: Result<APIResponse, Error>
739 do { response = .success(try await script.send(request)) }
740 catch { response = .failure(error) }
741 if request.path == path {
742 path = nil
743 entered = true
744 await withCheckedContinuation { continuation = $0 }
745 }
746 return try response.get()
747 }
748 func nativeToken(_ value: String) {
749 let data = String(decoding: Fixture.data("device-credential"), as: UTF8.self).replacingOccurrences(of: "TOKENFIXTURE", with: value)
750 script.replace("POST /auth/devices/native", with: .success(APIResponse(status: 200, data: Data(data.utf8))))
751 }
752 func answerFailure(_ route: String) {
753 script.on(route, .failure(.offline), .success(APIResponse(status: 200, data: Fixture.data("thin/answered"))))
754 }
755 func sent(_ route: String) -> [APIRequest] { script.sent(route) }
756 func lines(_ request: APIRequest) async throws -> AsyncThrowingStream<String, Error> { throw EquipoAPIError.offline }
757 func waitUntilEntered() async { while !entered { await Task.yield() } }
758 func release() { continuation?.resume(); continuation = nil }
759}
760