oficina / docs Public

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

Plain git — no account needed to clone.

Download

Download this file

1import Combine
2import CryptoKit
3import Foundation
4import Observation
5import Synchronization
6import RastrilloApple
7import RastrilloNative
8import RastrilloTestSupport
9import XCTest
10@testable import DocsKit
11
12/// Docs on Oficina ID (spec 2026-11-14-oficina-id-native, slice A), against
13/// the kit's in-memory Home, directory and instances: no keychain, App Group
14/// or network.
15@MainActor final class OficinaIDAdoptionTests: XCTestCase {
16 final class Clock: @unchecked Sendable { var date = Date(timeIntervalSince1970: 1_800_000_000) }
17
18 let paulca = URL(string: "https://paulca.docs.oficina.works")!
19 let tito = URL(string: "https://tito.docs.oficina.works")!
20 var service: FakeOficinaIDService!
21 var clock: Clock!
22 var suites: [String] = []
23
24 override func setUp() async throws {
25 service = FakeOficinaIDService()
26 clock = Clock()
27 }
28
29 override func tearDown() async throws {
30 for suite in suites { UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) }
31 }
32
33 private func defaults() -> UserDefaults {
34 let suite = "OficinaIDAdoptionTests.\(UUID().uuidString)"
35 suites.append(suite)
36 return UserDefaults(suiteName: suite)!
37 }
38
39 private func team(_ sqid: String, _ name: String, _ label: String, apps: [String] = ["docs"]) -> OficinaTeam {
40 OficinaTeam(sqid: sqid, label: label, name: name, role: "member",
41 apps: apps.map { OficinaTeamApp(app: $0, origin: "https://\(label).\($0).oficina.works", consumerID: "\(sqid)-\($0)") })
42 }
43
44 /// One device: the shared and private stores, the App Group and Docs'
45 /// own defaults outlive an app run, so a second session on the same
46 /// device is Docs launched again.
47 final class Device {
48 let shared = OficinaMemoryStore(), own = OficinaMemoryStore()
49 let group: UserDefaults, defaults: UserDefaults
50 init(group: UserDefaults, defaults: UserDefaults) { self.group = group; self.defaults = defaults }
51 }
52
53 private func device() -> Device { Device(group: defaults(), defaults: defaults()) }
54
55 private func session(on device: Device? = nil) -> DocsOficinaSession {
56 let clock = self.clock!
57 let device = device ?? self.device()
58 let store = OficinaIDStore(shared: device.shared, appPrivate: device.own, group: device.group)
59 let model = OficinaIDModel(configuration: DocsOficinaSession.configuration, store: store, service: service,
60 passkeys: FakePasskeys(), makeKey: { OficinaSoftwareKey() }, now: { clock.date },
61 appDefaults: device.defaults)
62 return DocsOficinaSession(model: model, now: { clock.date })
63 }
64
65 private func onePaulTeam(_ identity: String = "id-paul", email: String = "paul@tito.io") {
66 service.addPerson(email: email, identityID: identity)
67 service.setTeams([team("t1", "Paul", "paulca")], for: identity)
68 service.admit(identity, at: paulca, as: .linked)
69 }
70
71 /// Welcome → Email → Code, as a person would.
72 private func signIn(_ session: DocsOficinaSession, email: String = "paul@tito.io") async {
73 await session.start()
74 if session.model.step != .email { XCTAssertEqual(session.model.step, .welcome) }
75 session.model.continueWithEmail()
76 session.model.email = email
77 await session.model.submitEmail()
78 session.model.code = FakeOficinaIDService.goodCode
79 await session.model.submitCode()
80 }
81
82 private func exchanges(at origin: URL) -> Int { service.calls.filter { $0 == "exchange \(origin.absoluteString)" }.count }
83
84 func testRouteIsOficinaIDUnlessSomeoneSignedInTheOldWay() {
85 XCTAssertEqual(DocsSignInRoute.resolve(stored: "", hasServerAccounts: false), .oficinaID)
86 // Appendix C: old per-app sessions keep working until replaced.
87 XCTAssertEqual(DocsSignInRoute.resolve(stored: "", hasServerAccounts: true), .server)
88 XCTAssertEqual(DocsSignInRoute.resolve(stored: "oficina-id", hasServerAccounts: true), .oficinaID)
89 XCTAssertEqual(DocsSignInRoute.resolve(stored: "server", hasServerAccounts: false), .server)
90 XCTAssertEqual(DocsSignInRoute.resolve(stored: "something else", hasServerAccounts: false), .oficinaID)
91 }
92
93 func testAccountsBelongToTheirIdentityOnly() {
94 let account = DocsOficinaSession.accountID(identity: "id-1", team: "t1")
95 XCTAssertTrue(DocsOficinaSession.account(account, belongsTo: "id-1"))
96 XCTAssertFalse(DocsOficinaSession.account(account, belongsTo: "id"))
97 XCTAssertFalse(DocsOficinaSession.account(DocsOficinaSession.accountID(identity: "id-10", team: "t1"), belongsTo: "id-1"))
98 XCTAssertFalse(DocsOficinaSession.account(UUID().uuidString, belongsTo: "id-1"))
99 }
100
101 func testOneDocsTeamSignsStraightInAndTheWorkspaceGetsItsSession() async throws {
102 service.addPerson(email: "paul@tito.io", identityID: "id-paul")
103 // A team without Docs is no team for Docs.
104 service.setTeams([team("t1", "Paul", "paulca"), team("t3", "Sums", "sums", apps: ["sheets"])], for: "id-paul")
105 service.admit("id-paul", at: paulca, as: .linked)
106 let docs = session()
107 await signIn(docs)
108 let state = try XCTUnwrap(docs.signedIn)
109 XCTAssertEqual(state.origin, paulca)
110 let account = DocsOficinaSession.accountID(state)
111 XCTAssertEqual(account, "oficina-id.id-paul.t1")
112 let transport = try XCTUnwrap(docs.transport(for: account)())
113 XCTAssertEqual(transport.origin, paulca)
114 XCTAssertEqual(docs.client(for: account)?.credential?.value, state.session.value)
115 XCTAssertTrue(service.isLive(session: state.session))
116 // Another identity's account gets nothing.
117 XCTAssertNil(docs.transport(for: DocsOficinaSession.accountID(identity: "id-other", team: "t1"))())
118 }
119
120 func testARefusedSessionIsReMintedOnceAMinute() async throws {
121 service.addPerson(email: "paul@tito.io", identityID: "id-paul")
122 service.setTeams([team("t1", "Paul", "paulca")], for: "id-paul")
123 service.admit("id-paul", at: paulca, as: .linked)
124 let docs = session()
125 await signIn(docs)
126 let first = try XCTUnwrap(docs.signedIn)
127 let account = DocsOficinaSession.accountID(first)
128 XCTAssertEqual(exchanges(at: paulca), 1)
129
130 service.expire(session: first.session)
131 await docs.rejected(account)
132 let second = try XCTUnwrap(docs.signedIn)
133 XCTAssertNotEqual(second.session.value, first.session.value)
134 XCTAssertEqual(docs.client(for: account)?.credential?.value, second.session.value, "the supplier follows the new session")
135 XCTAssertEqual(exchanges(at: paulca), 2)
136
137 // An instance that keeps refusing cannot set off a loop.
138 await docs.rejected(account)
139 XCTAssertEqual(exchanges(at: paulca), 2)
140 clock.date.addTimeInterval(61)
141 await docs.rejected(account)
142 XCTAssertEqual(exchanges(at: paulca), 3)
143
144 // Only the team in use is re-minted.
145 await docs.rejected(DocsOficinaSession.accountID(identity: "id-paul", team: "t2"))
146 XCTAssertEqual(exchanges(at: paulca), 3)
147 }
148
149 func testSigningOutLeavesNoTransport() async throws {
150 service.addPerson(email: "paul@tito.io", identityID: "id-paul")
151 service.setTeams([team("t1", "Paul", "paulca")], for: "id-paul")
152 service.admit("id-paul", at: paulca, as: .linked)
153 let docs = session()
154 await signIn(docs)
155 let state = try XCTUnwrap(docs.signedIn)
156 let supplier = docs.transport(for: DocsOficinaSession.accountID(state))
157 XCTAssertNotNil(supplier())
158 docs.model.signOut()
159 await docs.model.cleanup?.value
160 XCTAssertEqual(docs.model.step, .welcome)
161 XCTAssertNil(supplier(), "a workspace still open after sign-out must fail as unauthorized, not send")
162 XCTAssertFalse(service.isLive(session: state.session), "the instance session is signed out too (§10)")
163 }
164
165 func testSwitchingTeamKeepsTheOtherTeamsSession() async throws {
166 service.addPerson(email: "paul@tito.io", identityID: "id-paul")
167 let paul = team("t1", "Paul", "paulca"), titoTeam = team("t2", "Tito", "tito")
168 service.setTeams([paul, titoTeam], for: "id-paul")
169 service.admit("id-paul", at: paulca, as: .linked)
170 service.admit("id-paul", at: tito, as: .linked)
171 let docs = session()
172 await signIn(docs)
173 guard case .teams(let teams) = docs.model.step else { return XCTFail("two Docs teams ask which: \(docs.model.step)") }
174 XCTAssertEqual(DocsTeamPicker.teams(teams, current: paul).map(\.sqid), ["t1", "t2"])
175 await docs.model.choose(paul)
176 let first = try XCTUnwrap(docs.signedIn)
177 await docs.model.choose(titoTeam)
178 let second = try XCTUnwrap(docs.signedIn)
179 XCTAssertEqual(second.origin, tito)
180 // A document window of the first team keeps its session.
181 XCTAssertEqual(docs.client(for: DocsOficinaSession.accountID(first))?.credential?.value, first.session.value)
182 XCTAssertNotNil(docs.client(for: DocsOficinaSession.accountID(second)))
183 }
184
185 func testTeamPickerListsDocsTeamsAndAlwaysTheCurrentOne() {
186 let paul = team("t1", "Paul", "paulca"), sums = team("t3", "Sums", "sums", apps: ["sheets"])
187 let campbells = team("t2", "campbells", "campbells")
188 XCTAssertEqual(DocsTeamPicker.teams([sums, paul, campbells], current: paul).map(\.sqid), ["t2", "t1"])
189 // An empty or missing cache still shows the team in use.
190 XCTAssertEqual(DocsTeamPicker.teams(nil, current: paul).map(\.sqid), ["t1"])
191 }
192
193 func testTheWatchReportsRefusedSessionsOnly() async throws {
194 final class Count: @unchecked Sendable { var value = 0 }
195 let count = Count()
196 let scripted = ScriptedTransport([.respond(status: 200), .respond(status: 401), .respond(status: 303),
197 .respond(status: 403), .respond(status: 401)])
198 let watch = DocsSessionWatch(inner: scripted) { count.value += 1 }
199 _ = try await watch.responseDetails("/", method: "GET", body: nil, contentType: "application/json", maxBytes: 1024)
200 XCTAssertEqual(count.value, 0)
201 _ = try await watch.responseDetails("/", method: "GET", body: nil, contentType: "application/json", maxBytes: 1024)
202 _ = try await watch.responseDetails("/", method: "GET", body: nil, contentType: "application/json", maxBytes: 1024)
203 XCTAssertEqual(count.value, 2, "401 and the 303 to sign-in are an ended session")
204 _ = try await watch.responseDetails("/", method: "GET", body: nil, contentType: "application/json", maxBytes: 1024)
205 XCTAssertEqual(count.value, 2, "403 is a refusal of the request, not of the session")
206 do {
207 try await watch.stream("/d/x/stream", onOpen: {}, onLine: { _ in })
208 XCTFail("a refused stream throws")
209 } catch NativeClientError.unauthorized {}
210 XCTAssertEqual(count.value, 3)
211 }
212
213 // MARK: Review round (Fable, d143194)
214
215 func testIdentityAndTeamThatAreNotPathSafeAreEncoded() {
216 let odd = DocsOficinaSession.accountID(identity: "a/b", team: "c.d")
217 XCTAssertFalse(odd.contains("/"))
218 XCTAssertEqual(odd.split(separator: ".").count, 3, "prefix, identity, team: no stray dots")
219 XCTAssertTrue(DocsOficinaSession.account(odd, belongsTo: "a/b"))
220 XCTAssertFalse(DocsOficinaSession.account(odd, belongsTo: "a"))
221 XCTAssertNotEqual(DocsOficinaSession.accountID(identity: "a", team: "b"), DocsOficinaSession.accountID(identity: "~a", team: "b"))
222 XCTAssertEqual(DocsOficinaSession.accountID(identity: "Ab_9-z", team: "t1"), "oficina-id.Ab_9-z.t1", "safe parts stay readable")
223 XCTAssertTrue(DocsOficinaSession.isOficinaAccount(odd))
224 XCTAssertFalse(DocsOficinaSession.isOficinaAccount(UUID().uuidString))
225 }
226
227 func testReplacingTheIdentityPurgesItsSessions() async throws {
228 onePaulTeam()
229 onePaulTeam("id-till", email: "till@lagged.io")
230 let docs = session()
231 await signIn(docs)
232 let paul = DocsOficinaSession.accountID(try XCTUnwrap(docs.signedIn))
233 docs.model.useAnother()
234 XCTAssertTrue(docs.model.confirmingReplace)
235 docs.model.confirmReplace()
236 XCTAssertNil(docs.transport(for: paul)(), "the replaced identity's workspaces get no session")
237 XCTAssertNil(docs.mounted)
238 await signIn(docs, email: "till@lagged.io")
239 let till = DocsOficinaSession.accountID(try XCTUnwrap(docs.signedIn))
240 XCTAssertNotEqual(till, paul)
241 XCTAssertNotNil(docs.transport(for: till)())
242 XCTAssertNil(docs.transport(for: paul)(), "and never comes back")
243 }
244
245 func testAReMintRestartsAnOutboxStoppedByTheEndedSession() async throws {
246 onePaulTeam()
247 let docs = session()
248 await signIn(docs)
249 let account = DocsOficinaSession.accountID(try XCTUnwrap(docs.signedIn))
250 var supplied: NativeTransport? = nil
251 let offline = DocsOfflineAccount(store: EphemeralDocsStore(), accountID: account,
252 connectivity: NativeConnectivity(source: ScriptedPathSource(.satisfied)),
253 transport: { supplied })
254 DocsOfflineAccount.accounts[account] = offline
255 defer { DocsOfflineAccount.accounts[account] = nil }
256 try await offline.outbox.enqueue(lane: "doc:k", kind: "update", payload: Data([1]))
257 let stopped = await offline.drainer.drain()
258 XCTAssertEqual(stopped, .sessionEnded)
259 XCTAssertTrue(offline.drainer.sessionEnded)
260 supplied = docs.transport(for: account)()
261 await docs.rejected(account)
262 XCTAssertFalse(offline.drainer.sessionEnded, "the new session restarts the stopped outbox")
263 }
264
265 func testA401WithHomeDownKeepsTheWorkspaceMounted() async throws {
266 onePaulTeam()
267 let docs = session()
268 await signIn(docs)
269 let first = try XCTUnwrap(docs.signedIn)
270 let account = DocsOficinaSession.accountID(first)
271 service.expire(session: first.session)
272 service.failNext("assert", with: .offline)
273 await docs.rejected(account)
274 guard case .unavailable = docs.model.step else { return XCTFail("Home down: \(docs.model.step)") }
275 XCTAssertEqual(docs.mounted, first, "the open workspace stays, under the Can't reach line")
276 XCTAssertNotNil(docs.transport(for: account)())
277 await docs.model.retry()
278 let second = try XCTUnwrap(docs.signedIn)
279 XCTAssertEqual(docs.mounted, second)
280 XCTAssertNotEqual(second.session.value, first.session.value)
281 XCTAssertEqual(docs.client(for: account)?.credential?.value, second.session.value)
282 }
283
284 func testOnlyASignInMadeHereCountsNotARestore() async throws {
285 onePaulTeam()
286 let device = device()
287 let first = session(on: device)
288 await signIn(first)
289 XCTAssertNotNil(first.signedIn)
290 XCTAssertEqual(first.signIns, 1)
291 // Docs launched again: the team comes back with no sign-in.
292 let again = session(on: device)
293 await again.start()
294 XCTAssertNotNil(again.signedIn)
295 XCTAssertEqual(again.signIns, 0, "a restored identity must not change the route someone chose")
296 }
297
298 func testRenewAfterADayGoesThroughTheSession() async throws {
299 onePaulTeam()
300 let docs = session()
301 await signIn(docs)
302 let first = try XCTUnwrap(docs.signedIn)
303 let account = DocsOficinaSession.accountID(first)
304 await docs.renewIfNeeded()
305 XCTAssertEqual(exchanges(at: paulca), 1, "a fresh session is kept")
306 clock.date.addTimeInterval(25 * 3600)
307 await docs.renewIfNeeded()
308 XCTAssertEqual(exchanges(at: paulca), 2)
309 let renewed = try XCTUnwrap(docs.signedIn)
310 XCTAssertNotEqual(renewed.session.value, first.session.value)
311 XCTAssertEqual(docs.client(for: account)?.credential?.value, renewed.session.value)
312 }
313
314 func testTeamsRefreshAtLaunchOnTheMenuAndOnA403() async throws {
315 onePaulTeam()
316 let device = device()
317 await signIn(session(on: device))
318 let titoTeam = team("t2", "Tito", "tito")
319 service.setTeams([team("t1", "Paul", "paulca"), titoTeam], for: "id-paul")
320 let teamsCalls = { self.service.calls.filter { $0 == "teams" }.count }
321 clock.date.addTimeInterval(301)
322 let docs = session(on: device)
323 await docs.start()
324 XCTAssertEqual(docs.model.store.teams("id-paul")?.teams.map(\.sqid), ["t1", "t2"], "launch refreshes")
325 let afterLaunch = teamsCalls()
326 await docs.pickerOpened()
327 XCTAssertEqual(teamsCalls(), afterLaunch, "the menu waits five minutes")
328 service.setTeams([team("t1", "Paul", "paulca")], for: "id-paul")
329 await docs.refused()
330 XCTAssertEqual(docs.model.store.teams("id-paul")?.teams.map(\.sqid), ["t1"], "a 403 refreshes at once")
331 await docs.refused()
332 XCTAssertEqual(teamsCalls(), afterLaunch + 1, "at most once a minute")
333 clock.date.addTimeInterval(301)
334 await docs.pickerOpened()
335 XCTAssertEqual(teamsCalls(), afterLaunch + 2)
336 }
337
338 func testTheWatchReports403sAsRefusals() async throws {
339 final class Count: @unchecked Sendable { var rejected = 0, refused = 0 }
340 let count = Count()
341 let watch = DocsSessionWatch(inner: ScriptedTransport([.respond(status: 403), .respond(status: 200)]),
342 rejected: { count.rejected += 1 }, refused: { count.refused += 1 })
343 _ = try await watch.responseDetails("/", method: "GET", body: nil, contentType: "application/json", maxBytes: 1024)
344 _ = try await watch.responseDetails("/", method: "GET", body: nil, contentType: "application/json", maxBytes: 1024)
345 XCTAssertEqual(count.refused, 1)
346 XCTAssertEqual(count.rejected, 0)
347 }
348
349 func testSharingExportImagesAndJumpUseTheCurrentSession() async throws {
350 onePaulTeam()
351 let docs = session()
352 await signIn(docs)
353 let first = try XCTUnwrap(docs.signedIn)
354 let account = DocsOficinaSession.accountID(first)
355 let opened = first.client()
356 service.expire(session: first.session)
357 await docs.rejected(account)
358 let renewed = try XCTUnwrap(docs.signedIn)
359 let live = DocsWorkspace.liveClient(docs.transport(for: account), fallback: opened)
360 let watched = try XCTUnwrap(live as? DocsSessionWatch, "watched for 401s")
361 XCTAssertEqual((watched.inner as? NativeHTTP)?.credential?.value, renewed.session.value)
362 // A window without a supplier (a server account's) keeps its client.
363 XCTAssertTrue(DocsWorkspace.liveClient(nil, fallback: opened) as AnyObject === opened)
364 }
365
366 // MARK: The store key outlives an origin change
367
368 /// A keychain in memory, one item per KeychainKeyProvider account.
369 final class MemoryKeychain: @unchecked Sendable {
370 let lock = NSLock()
371 var items: [String: StoreKeyState] = [:]
372 struct Keys: KeyProvider {
373 let chain: MemoryKeychain, account: String
374 func copyKey() -> (OSStatus, SymmetricKey?) {
375 chain.lock.withLock { chain.items[account].map { (errSecSuccess, SymmetricKey(data: $0.current)) } ?? (errSecItemNotFound, nil) }
376 }
377 func addKey(_ key: SymmetricKey) -> OSStatus {
378 chain.lock.withLock {
379 guard chain.items[account] == nil else { return errSecDuplicateItem }
380 chain.items[account] = StoreKeyState(current: key.withUnsafeBytes { Data($0) }); return errSecSuccess
381 }
382 }
383 func deleteKey() -> OSStatus { chain.lock.withLock { chain.items[account] = nil }; return errSecSuccess }
384 func sealState() -> (OSStatus, StoreKeyState?) {
385 chain.lock.withLock { chain.items[account].map { (errSecSuccess, $0) } ?? (errSecItemNotFound, nil) }
386 }
387 func saveSealState(_ state: StoreKeyState) -> OSStatus { chain.lock.withLock { chain.items[account] = state }; return errSecSuccess }
388 }
389 func keys(_ account: String, origin: URL) -> Keys { Keys(chain: self, account: DocsOfflineAccount.keys(accountID: account, origin: origin).account) }
390 }
391
392 func testAnOficinaTeamsStoreAndOutboxSurviveAnOriginChange() async throws {
393 let root = FileManager.default.temporaryDirectory.appendingPathComponent("docs-origin-\(UUID().uuidString)")
394 defer { try? FileManager.default.removeItem(at: root) }
395 let chain = MemoryKeychain()
396 let account = DocsOficinaSession.accountID(identity: "id-paul", team: "t1")
397 let old = URL(string: "https://paul.docs.oficina.works")!, moved = URL(string: "https://paulca.docs.oficina.works")!
398 let before = Outbox(store: NativeSealedStore(root: root, accountID: account, keys: chain.keys(account, origin: old)), account: account)
399 try await before.enqueue(lane: "doc:k", kind: "update", payload: Data([7]))
400 let after = Outbox(store: NativeSealedStore(root: root, accountID: account, keys: chain.keys(account, origin: moved)), account: account)
401 try await after.load()
402 let kept = await after.entries(lane: "doc:k", excludingInFlight: false)
403 XCTAssertEqual(kept.map(\.payload), [Data([7])], "the label moved; the unsent change did not go with it")
404 // A server account is its host: a new origin is a new account.
405 let server = UUID().uuidString
406 XCTAssertNotEqual(DocsOfflineAccount.keys(accountID: server, origin: old).account,
407 DocsOfflineAccount.keys(accountID: server, origin: moved).account)
408 }
409
410 func testUnsentChangesLeftOnDiskBlockSigningOutOfThatIdentity() async throws {
411 let root = FileManager.default.temporaryDirectory.appendingPathComponent("docs-unsent-\(UUID().uuidString)")
412 defer { try? FileManager.default.removeItem(at: root) }
413 let chain = MemoryKeychain()
414 let account = DocsOficinaSession.accountID(identity: "id-paul", team: "t2")
415 let keys: (String) -> KeyProvider = { chain.keys($0, origin: DocsOfflineAccount.oficinaKeyOrigin) }
416 // An outbox a crash left behind, for a team not opened this run.
417 let left = Outbox(store: NativeSealedStore(root: root.appendingPathComponent(account), accountID: account, keys: keys(account)), account: account)
418 try await left.enqueue(lane: "doc:k", kind: "update", payload: Data([1]))
419 let paul = await DocsOfflineAccount.hasUnsent(identity: "id-paul", root: root, keys: keys)
420 let till = await DocsOfflineAccount.hasUnsent(identity: "id-till", root: root, keys: keys)
421 XCTAssertTrue(paul)
422 XCTAssertFalse(till)
423 // Once sent, nothing blocks.
424 let entries = await left.entries(lane: "doc:k", excludingInFlight: false)
425 try await left.ack(entries.map(\.id))
426 let sent = await DocsOfflineAccount.hasUnsent(identity: "id-paul", root: root, keys: keys)
427 XCTAssertFalse(sent)
428 }
429
430 func testTheLeaveGuardOrdersOpenDocumentsFirst() async {
431 let open = await DocsLeaveBlock.check(identity: "id-nobody", openDocuments: true, unsentHere: true)
432 XCTAssertEqual(open, .openDocuments)
433 let unsent = await DocsLeaveBlock.check(identity: "id-nobody", openDocuments: false, unsentHere: true)
434 XCTAssertEqual(unsent, .sending)
435 XCTAssertFalse(DocsLeaveBlock.sending.message.isEmpty)
436 XCTAssertNotEqual(DocsLeaveBlock.sending.message, "native.leave.sending", "the line is translated, not a key")
437 }
438
439 // MARK: Straight in (Paul, 2026-11-19; spec §9, rule 0)
440
441 /// Paul on one team with Docs and Sheets, signed in on `device` by
442 /// Sheets: the saved identity Docs finds at launch. A fixture that
443 /// cannot sign in fails the test (never a skip, which would hide what
444 /// depends on it).
445 @discardableResult
446 private func savedIdentity(on device: Device) async throws -> OficinaTeam {
447 let paul = team("t1", "Paul", "paulca", apps: ["docs", "sheets"])
448 service.addPerson(email: "paul@tito.io", identityID: "id-paul")
449 service.setTeams([paul], for: "id-paul")
450 service.admit("id-paul", at: paulca, as: .linked)
451 service.admit("id-paul", at: URL(string: "https://paulca.sheets.oficina.works")!, as: .linked)
452 let clock = self.clock!
453 let sheets = OficinaIDModel(configuration: OficinaIDConfiguration(app: "sheets", appName: "Sheets"),
454 store: OficinaIDStore(shared: device.shared, appPrivate: OficinaMemoryStore(), group: device.group),
455 service: service, passkeys: FakePasskeys(), makeKey: { OficinaSoftwareKey() }, now: { clock.date },
456 appDefaults: defaults())
457 await sheets.start()
458 sheets.continueWithEmail()
459 sheets.email = "paul@tito.io"
460 await sheets.submitEmail()
461 sheets.code = FakeOficinaIDService.goodCode
462 await sheets.submitCode()
463 guard case .signedIn = sheets.step else {
464 XCTFail("Sheets did not sign in: \(sheets.step)")
465 throw CancellationError()
466 }
467 return paul
468 }
469
470 /// One Oficina ID on the device: Docs opens its team with no screen, and
471 /// the launch is not a sign-in made here (the route stays as chosen).
472 func testASavedIdentitySignsDocsStraightIn() async throws {
473 let device = device()
474 let paul = try await savedIdentity(on: device)
475 let docs = session(on: device)
476 var steps: [String] = []
477 let watching = docs.model.$step.sink { steps.append("\($0)".components(separatedBy: "(").first ?? "") }
478 await docs.start()
479 watching.cancel()
480 let mounted = try XCTUnwrap(docs.mounted, "straight in: \(docs.model.step)")
481 XCTAssertEqual(mounted.team, paul)
482 XCTAssertEqual(mounted.origin, paulca)
483 XCTAssertEqual(Set(steps), ["loading", "signedIn"], "no screen on the way in")
484 XCTAssertEqual(docs.signIns, 0, "going straight in does not choose the route")
485 XCTAssertEqual(service.calls.filter { $0.hasPrefix("startCode") }.count, 1, "one sign-in for both apps")
486 XCTAssertNotNil(docs.transport(for: DocsOficinaSession.accountID(mounted))())
487 }
488
489 /// Docs' last route was its own sign-in: nothing goes straight in, and
490 /// nothing touches the network, until the route is Oficina ID again.
491 func testTheServerRouteSuspendsStraightIn() async throws {
492 let device = device()
493 try await savedIdentity(on: device)
494 let docs = session(on: device)
495 let calls = service.calls.count
496 await docs.start(serverRoute: true)
497 XCTAssertTrue(docs.model.straightInSuspended)
498 XCTAssertNil(docs.mounted)
499 XCTAssertEqual(docs.model.step, .welcome)
500 XCTAssertEqual(service.calls.count, calls, "no network while Docs' own sign-in is the route")
501 await docs.routeChanged(to: .oficinaID)
502 XCTAssertFalse(docs.model.straightInSuspended)
503 XCTAssertEqual(docs.mounted?.origin, paulca, "straight in once the route is Oficina ID")
504 XCTAssertEqual(docs.signIns, 0)
505 }
506
507 /// The route alone decides: flipping to the server route while signed
508 /// in suspends straight in and disturbs nothing; flipping back resumes
509 /// without a second sign-in.
510 func testTheRouteAloneDecidesTheSuspension() async throws {
511 let device = device()
512 try await savedIdentity(on: device)
513 let docs = session(on: device)
514 await docs.start()
515 let mounted = try XCTUnwrap(docs.mounted)
516 let exchangesBefore = exchanges(at: paulca)
517 await docs.routeChanged(to: .server)
518 XCTAssertTrue(docs.model.straightInSuspended)
519 XCTAssertEqual(docs.mounted, mounted, "signed in, suspending changes nothing")
520 XCTAssertNotNil(docs.transport(for: DocsOficinaSession.accountID(mounted))(), "the session stays usable")
521 await docs.routeChanged(to: .oficinaID)
522 XCTAssertFalse(docs.model.straightInSuspended)
523 XCTAssertEqual(docs.mounted, mounted)
524 XCTAssertEqual(exchanges(at: paulca), exchangesBefore, "resuming a signed-in model mints nothing")
525 }
526
527 /// "Use another Oficina ID" is asked only while signed in to the
528 /// identity, never with one of its document windows open, never over an
529 /// outage (the team stays mounted, but there is no dialog to ask with).
530 func testUseAnotherIsRefusedWithAnOpenDocumentOrOverAnOutage() async throws {
531 let device = device()
532 let paul = try await savedIdentity(on: device)
533 let docs = session(on: device)
534 await docs.start()
535 let state = try XCTUnwrap(docs.mounted)
536 XCTAssertFalse(docs.useAnother(identity: state.identity.id, canLeave: false), "a document window is open")
537 XCTAssertFalse(docs.model.confirmingReplace)
538 XCTAssertFalse(docs.useAnother(identity: "id-someone-else", canLeave: true), "another identity's menu")
539 XCTAssertFalse(docs.model.confirmingReplace)
540
541 service.expire(session: state.session)
542 service.failNext("exchange", at: paulca.absoluteString, with: .offline)
543 await docs.rejected(DocsOficinaSession.accountID(state))
544 XCTAssertEqual(docs.model.step, .unavailable(paul))
545 XCTAssertNotNil(docs.mounted, "the workspace stays over the outage")
546 XCTAssertFalse(docs.useAnother(identity: state.identity.id, canLeave: true), "over an outage")
547 XCTAssertFalse(docs.model.confirmingReplace)
548
549 await docs.model.retry()
550 XCTAssertTrue(docs.useAnother(identity: state.identity.id, canLeave: true))
551 XCTAssertTrue(docs.model.confirmingReplace)
552 }
553
554 /// From the menu it only asks: cancelling changes nothing; confirming
555 /// signs the identity out on every app and goes to Email, and its
556 /// workspaces get no session.
557 func testUseAnotherFromTheMenuAsksThenReplaces() async throws {
558 let device = device()
559 try await savedIdentity(on: device)
560 let docs = session(on: device)
561 await docs.start()
562 let state = try XCTUnwrap(docs.mounted)
563 let account = DocsOficinaSession.accountID(state)
564 XCTAssertTrue(docs.useAnother(identity: state.identity.id, canLeave: true))
565 docs.model.cancelReplace()
566 XCTAssertEqual(docs.mounted, state, "cancelling changes nothing")
567 XCTAssertEqual(docs.client(for: account)?.credential?.value, state.session.value)
568 XCTAssertTrue(service.isLive(session: state.session))
569 XCTAssertTrue(docs.useAnother(identity: state.identity.id, canLeave: true))
570 docs.model.confirmReplace()
571 await docs.model.cleanup?.value
572 XCTAssertNil(docs.mounted)
573 XCTAssertEqual(docs.model.step, .email)
574 XCTAssertEqual(try docs.model.store.identities(), [], "signed out on every app")
575 XCTAssertNil(docs.transport(for: account)())
576 }
577
578 /// #130, finding 1: with changes unsent, "Use another" is refused before
579 /// the kit asks. The confirmation used to go up, and be confirmable,
580 /// while the outbox was being checked, then be withdrawn.
581 func testUseAnotherWithUnsentChangesIsRefusedBeforeItAsks() async throws {
582 let device = device()
583 try await savedIdentity(on: device)
584 let docs = session(on: device)
585 await docs.start()
586 let state = try XCTUnwrap(docs.mounted)
587 let account = DocsOficinaSession.accountID(state)
588 let offline = DocsOfflineAccount(store: EphemeralDocsStore(), accountID: account,
589 connectivity: NativeConnectivity(source: ScriptedPathSource(.satisfied)), transport: { nil })
590 DocsOfflineAccount.accounts[account] = offline
591 defer { DocsOfflineAccount.accounts[account] = nil }
592 try await offline.outbox.enqueue(lane: "doc:k", kind: "update", payload: Data([1]))
593 var asked = 0
594 let watch = docs.model.$confirmingReplace.sink { if $0 { asked += 1 } }
595 defer { watch.cancel() }
596
597 let refused = await docs.requestUseAnother(identity: state.identity.id, openDocuments: { false })
598 XCTAssertEqual(refused, .sending)
599 XCTAssertEqual(asked, 0, "the confirmation never went up")
600 XCTAssertEqual(docs.mounted, state)
601
602 // A document window opened while the outbox was checked refuses too.
603 DocsOfflineAccount.accounts[account] = nil
604 var windowOpen = false
605 let opened = await docs.requestUseAnother(identity: state.identity.id, openDocuments: {
606 defer { windowOpen = true }
607 return windowOpen
608 })
609 XCTAssertEqual(opened, .openDocuments)
610 XCTAssertEqual(asked, 0)
611
612 // Nothing unsent, no window: the kit asks.
613 let clear = await docs.requestUseAnother(identity: state.identity.id, openDocuments: { false })
614 XCTAssertNil(clear)
615 XCTAssertEqual(asked, 1)
616 XCTAssertTrue(docs.model.confirmingReplace)
617 }
618
619 /// #130, finding 4: a write sent on the old cookie comes back "signed
620 /// out" after another request's re-mint has already replaced the
621 /// session. It must not leave the outbox stopped ("needs sign-in") with
622 /// a good session, nor mint again.
623 func testARefusalOfAnAlreadyReplacedSessionRestartsTheOutbox() async throws {
624 onePaulTeam()
625 let docs = session()
626 await signIn(docs)
627 let first = try XCTUnwrap(docs.signedIn)
628 let account = DocsOficinaSession.accountID(first)
629 // The outbox's write goes out on the first session...
630 let server = ScriptedTransport([.respond(status: 403, body: Data("signed out\n".utf8))])
631 let stale = docs.watch(server, account: account, session: first.session.value)
632 let offline = DocsOfflineAccount(store: EphemeralDocsStore(), accountID: account,
633 connectivity: NativeConnectivity(source: ScriptedPathSource(.satisfied)), transport: { stale })
634 DocsOfflineAccount.accounts[account] = offline
635 defer { DocsOfflineAccount.accounts[account] = nil }
636 try offline.saveMetadata(DocsOfflineMetadata(detail: DocumentDetail(sqid: "k", title: "Notes", guid: "g", can_write: true, can_share: true),
637 pendingTitle: "Plans"), key: "k")
638 try await offline.outbox.enqueue(lane: "doc:k", kind: "metadata", payload: Data())
639 // ...and another request's re-mint completes first.
640 service.expire(session: first.session)
641 await docs.rejected(account)
642 XCTAssertNotEqual(try XCTUnwrap(docs.signedIn).session.value, first.session.value)
643 let exchanged = exchanges(at: paulca)
644
645 // Then the write's "signed out" lands and stops the outbox.
646 let stopped = await offline.drainer.drain()
647 XCTAssertEqual(stopped, .sessionEnded)
648 XCTAssertEqual(server.calls.map(\.path), ["/d/k/title"])
649 let deadline = Date().addingTimeInterval(2)
650 while offline.drainer.sessionEnded, Date() < deadline { try await Task.sleep(for: .milliseconds(10)) }
651 XCTAssertFalse(offline.drainer.sessionEnded, "the outbox sends again on the session it now has")
652 XCTAssertEqual(exchanges(at: paulca), exchanged, "a refusal of a replaced session mints nothing")
653 }
654
655 /// Docs' guards answer a write with an ended session 403 "signed out"
656 /// (internal/docs/native_contract_test.go): that is the session, not
657 /// the request, so it re-mints and reads as unauthorized. Any other 403
658 /// stays a refusal of the request.
659 func testASignedOut403IsAnEndedSession() async throws {
660 final class Counts: @unchecked Sendable { var rejected = 0, refused = 0 }
661 let counts = Counts()
662 let server = ScriptedTransport([
663 .respond(status: 403, body: Data("signed out\n".utf8)),
664 .respond(status: 403, body: Data("Something went wrong.\n".utf8)),
665 .respond(status: 403, body: Data("signed out".utf8)),
666 ])
667 let watch = DocsSessionWatch(inner: server, rejected: { counts.rejected += 1 }, refused: { counts.refused += 1 })
668 let ended = try await watch.responseDetails("/documents", method: "POST", body: Data("{}".utf8),
669 contentType: "application/json", maxBytes: 1024)
670 XCTAssertEqual(ended.status, 401)
671 XCTAssertEqual(counts.rejected, 1)
672 XCTAssertEqual(counts.refused, 0)
673 for _ in 0..<2 {
674 let refusal = try await watch.responseDetails("/documents", method: "POST", body: Data("{}".utf8),
675 contentType: "application/json", maxBytes: 1024)
676 XCTAssertEqual(refusal.status, 403)
677 }
678 XCTAssertEqual(counts.rejected, 1, "only the exact bytes are an ended session")
679 XCTAssertEqual(counts.refused, 2)
680 }
681
682 /// What the signed-in window's body builds, built under observation as
683 /// a body is: the transport and the workspace, with "Use another". None
684 /// of it may change anything a view watches, or each body pass would
685 /// invalidate the next (84d1008).
686 func testBuildingTheSignedInWorkspaceChangesNothingAViewWatches() async throws {
687 let device = device()
688 try await savedIdentity(on: device)
689 let docs = session(on: device)
690 await docs.start()
691 let state = try XCTUnwrap(docs.mounted)
692 let account = DocsOficinaSession.accountID(state)
693 let offline = DocsOfflineAccount(store: EphemeralDocsStore(), accountID: account,
694 connectivity: NativeConnectivity(source: ScriptedPathSource(.satisfied)),
695 transport: docs.transport(for: account))
696 DocsOfflineAccount.accounts[account] = offline
697 defer { DocsOfflineAccount.accounts[account] = nil }
698 let client = try XCTUnwrap(docs.client(for: account))
699 var published = 0
700 let watches = [docs.objectWillChange.sink { _ in published += 1 }, docs.model.objectWillChange.sink { _ in published += 1 }]
701 let changed = Mutex(false)
702 withObservationTracking {
703 _ = offline.drainer.status()
704 _ = offline.drainer.sessionEnded
705 _ = DocsWorkspace(client: client, accountID: account, transport: docs.transport(for: account), accounts: {}, signOut: {},
706 accountsLabel: DocsOficinaSession.teamsTitle, signOutLabel: "Sign out", useAnother: {})
707 _ = docs.mounted
708 _ = docs.model.step
709 } onChange: { changed.withLock { $0 = true } }
710 for _ in 0..<3 {
711 _ = DocsWorkspace(client: client, accountID: account, transport: docs.transport(for: account), signOut: {}, useAnother: {})
712 }
713 watches.forEach { $0.cancel() }
714 XCTAssertFalse(changed.withLock { $0 }, "building the signed-in workspace must not invalidate its window")
715 XCTAssertEqual(published, 0, "nor publish from the session or the model")
716 }
717
718 #if os(macOS)
719 func testTheLaunchCheckFailsWithoutTheEntitlements() {
720 // The test runner is not signed with Docs' entitlements: every check
721 // that needs them must say FAIL, or the gate could not catch a build
722 // that lost them.
723 let result = DocsOficinaLaunchCheck.run()
724 XCTAssertFalse(result.passed)
725 for name in ["keychain-access-groups", "shared group", "Docs' group", "App Group", "associated domains"] {
726 XCTAssertTrue(result.lines.contains { $0.hasPrefix("FAIL \(name)") }, "\(name): \(result.lines)")
727 }
728 }
729 #endif
730}
731