import Combine import CryptoKit import Foundation import Observation import Synchronization import RastrilloApple import RastrilloNative import RastrilloTestSupport import XCTest @testable import DocsKit /// Docs on Oficina ID (spec 2026-11-14-oficina-id-native, slice A), against /// the kit's in-memory Home, directory and instances: no keychain, App Group /// or network. @MainActor final class OficinaIDAdoptionTests: XCTestCase { final class Clock: @unchecked Sendable { var date = Date(timeIntervalSince1970: 1_800_000_000) } let paulca = URL(string: "https://paulca.docs.oficina.works")! let tito = URL(string: "https://tito.docs.oficina.works")! var service: FakeOficinaIDService! var clock: Clock! var suites: [String] = [] override func setUp() async throws { service = FakeOficinaIDService() clock = Clock() } override func tearDown() async throws { for suite in suites { UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) } } private func defaults() -> UserDefaults { let suite = "OficinaIDAdoptionTests.\(UUID().uuidString)" suites.append(suite) return UserDefaults(suiteName: suite)! } private func team(_ sqid: String, _ name: String, _ label: String, apps: [String] = ["docs"]) -> OficinaTeam { OficinaTeam(sqid: sqid, label: label, name: name, role: "member", apps: apps.map { OficinaTeamApp(app: $0, origin: "https://\(label).\($0).oficina.works", consumerID: "\(sqid)-\($0)") }) } /// One device: the shared and private stores, the App Group and Docs' /// own defaults outlive an app run, so a second session on the same /// device is Docs launched again. final class Device { let shared = OficinaMemoryStore(), own = OficinaMemoryStore() let group: UserDefaults, defaults: UserDefaults init(group: UserDefaults, defaults: UserDefaults) { self.group = group; self.defaults = defaults } } private func device() -> Device { Device(group: defaults(), defaults: defaults()) } private func session(on device: Device? = nil) -> DocsOficinaSession { let clock = self.clock! let device = device ?? self.device() let store = OficinaIDStore(shared: device.shared, appPrivate: device.own, group: device.group) let model = OficinaIDModel(configuration: DocsOficinaSession.configuration, store: store, service: service, passkeys: FakePasskeys(), makeKey: { OficinaSoftwareKey() }, now: { clock.date }, appDefaults: device.defaults) return DocsOficinaSession(model: model, now: { clock.date }) } private func onePaulTeam(_ identity: String = "id-paul", email: String = "paul@tito.io") { service.addPerson(email: email, identityID: identity) service.setTeams([team("t1", "Paul", "paulca")], for: identity) service.admit(identity, at: paulca, as: .linked) } /// Welcome → Email → Code, as a person would. private func signIn(_ session: DocsOficinaSession, email: String = "paul@tito.io") async { await session.start() if session.model.step != .email { XCTAssertEqual(session.model.step, .welcome) } session.model.continueWithEmail() session.model.email = email await session.model.submitEmail() session.model.code = FakeOficinaIDService.goodCode await session.model.submitCode() } private func exchanges(at origin: URL) -> Int { service.calls.filter { $0 == "exchange \(origin.absoluteString)" }.count } func testRouteIsOficinaIDUnlessSomeoneSignedInTheOldWay() { XCTAssertEqual(DocsSignInRoute.resolve(stored: "", hasServerAccounts: false), .oficinaID) // Appendix C: old per-app sessions keep working until replaced. XCTAssertEqual(DocsSignInRoute.resolve(stored: "", hasServerAccounts: true), .server) XCTAssertEqual(DocsSignInRoute.resolve(stored: "oficina-id", hasServerAccounts: true), .oficinaID) XCTAssertEqual(DocsSignInRoute.resolve(stored: "server", hasServerAccounts: false), .server) XCTAssertEqual(DocsSignInRoute.resolve(stored: "something else", hasServerAccounts: false), .oficinaID) } func testAccountsBelongToTheirIdentityOnly() { let account = DocsOficinaSession.accountID(identity: "id-1", team: "t1") XCTAssertTrue(DocsOficinaSession.account(account, belongsTo: "id-1")) XCTAssertFalse(DocsOficinaSession.account(account, belongsTo: "id")) XCTAssertFalse(DocsOficinaSession.account(DocsOficinaSession.accountID(identity: "id-10", team: "t1"), belongsTo: "id-1")) XCTAssertFalse(DocsOficinaSession.account(UUID().uuidString, belongsTo: "id-1")) } func testOneDocsTeamSignsStraightInAndTheWorkspaceGetsItsSession() async throws { service.addPerson(email: "paul@tito.io", identityID: "id-paul") // A team without Docs is no team for Docs. service.setTeams([team("t1", "Paul", "paulca"), team("t3", "Sums", "sums", apps: ["sheets"])], for: "id-paul") service.admit("id-paul", at: paulca, as: .linked) let docs = session() await signIn(docs) let state = try XCTUnwrap(docs.signedIn) XCTAssertEqual(state.origin, paulca) let account = DocsOficinaSession.accountID(state) XCTAssertEqual(account, "oficina-id.id-paul.t1") let transport = try XCTUnwrap(docs.transport(for: account)()) XCTAssertEqual(transport.origin, paulca) XCTAssertEqual(docs.client(for: account)?.credential?.value, state.session.value) XCTAssertTrue(service.isLive(session: state.session)) // Another identity's account gets nothing. XCTAssertNil(docs.transport(for: DocsOficinaSession.accountID(identity: "id-other", team: "t1"))()) } func testARefusedSessionIsReMintedOnceAMinute() async throws { service.addPerson(email: "paul@tito.io", identityID: "id-paul") service.setTeams([team("t1", "Paul", "paulca")], for: "id-paul") service.admit("id-paul", at: paulca, as: .linked) let docs = session() await signIn(docs) let first = try XCTUnwrap(docs.signedIn) let account = DocsOficinaSession.accountID(first) XCTAssertEqual(exchanges(at: paulca), 1) service.expire(session: first.session) await docs.rejected(account) let second = try XCTUnwrap(docs.signedIn) XCTAssertNotEqual(second.session.value, first.session.value) XCTAssertEqual(docs.client(for: account)?.credential?.value, second.session.value, "the supplier follows the new session") XCTAssertEqual(exchanges(at: paulca), 2) // An instance that keeps refusing cannot set off a loop. await docs.rejected(account) XCTAssertEqual(exchanges(at: paulca), 2) clock.date.addTimeInterval(61) await docs.rejected(account) XCTAssertEqual(exchanges(at: paulca), 3) // Only the team in use is re-minted. await docs.rejected(DocsOficinaSession.accountID(identity: "id-paul", team: "t2")) XCTAssertEqual(exchanges(at: paulca), 3) } func testSigningOutLeavesNoTransport() async throws { service.addPerson(email: "paul@tito.io", identityID: "id-paul") service.setTeams([team("t1", "Paul", "paulca")], for: "id-paul") service.admit("id-paul", at: paulca, as: .linked) let docs = session() await signIn(docs) let state = try XCTUnwrap(docs.signedIn) let supplier = docs.transport(for: DocsOficinaSession.accountID(state)) XCTAssertNotNil(supplier()) docs.model.signOut() await docs.model.cleanup?.value XCTAssertEqual(docs.model.step, .welcome) XCTAssertNil(supplier(), "a workspace still open after sign-out must fail as unauthorized, not send") XCTAssertFalse(service.isLive(session: state.session), "the instance session is signed out too (§10)") } func testSwitchingTeamKeepsTheOtherTeamsSession() async throws { service.addPerson(email: "paul@tito.io", identityID: "id-paul") let paul = team("t1", "Paul", "paulca"), titoTeam = team("t2", "Tito", "tito") service.setTeams([paul, titoTeam], for: "id-paul") service.admit("id-paul", at: paulca, as: .linked) service.admit("id-paul", at: tito, as: .linked) let docs = session() await signIn(docs) guard case .teams(let teams) = docs.model.step else { return XCTFail("two Docs teams ask which: \(docs.model.step)") } XCTAssertEqual(DocsTeamPicker.teams(teams, current: paul).map(\.sqid), ["t1", "t2"]) await docs.model.choose(paul) let first = try XCTUnwrap(docs.signedIn) await docs.model.choose(titoTeam) let second = try XCTUnwrap(docs.signedIn) XCTAssertEqual(second.origin, tito) // A document window of the first team keeps its session. XCTAssertEqual(docs.client(for: DocsOficinaSession.accountID(first))?.credential?.value, first.session.value) XCTAssertNotNil(docs.client(for: DocsOficinaSession.accountID(second))) } func testTeamPickerListsDocsTeamsAndAlwaysTheCurrentOne() { let paul = team("t1", "Paul", "paulca"), sums = team("t3", "Sums", "sums", apps: ["sheets"]) let campbells = team("t2", "campbells", "campbells") XCTAssertEqual(DocsTeamPicker.teams([sums, paul, campbells], current: paul).map(\.sqid), ["t2", "t1"]) // An empty or missing cache still shows the team in use. XCTAssertEqual(DocsTeamPicker.teams(nil, current: paul).map(\.sqid), ["t1"]) } func testTheWatchReportsRefusedSessionsOnly() async throws { final class Count: @unchecked Sendable { var value = 0 } let count = Count() let scripted = ScriptedTransport([.respond(status: 200), .respond(status: 401), .respond(status: 303), .respond(status: 403), .respond(status: 401)]) let watch = DocsSessionWatch(inner: scripted) { count.value += 1 } _ = try await watch.responseDetails("/", method: "GET", body: nil, contentType: "application/json", maxBytes: 1024) XCTAssertEqual(count.value, 0) _ = try await watch.responseDetails("/", method: "GET", body: nil, contentType: "application/json", maxBytes: 1024) _ = try await watch.responseDetails("/", method: "GET", body: nil, contentType: "application/json", maxBytes: 1024) XCTAssertEqual(count.value, 2, "401 and the 303 to sign-in are an ended session") _ = try await watch.responseDetails("/", method: "GET", body: nil, contentType: "application/json", maxBytes: 1024) XCTAssertEqual(count.value, 2, "403 is a refusal of the request, not of the session") do { try await watch.stream("/d/x/stream", onOpen: {}, onLine: { _ in }) XCTFail("a refused stream throws") } catch NativeClientError.unauthorized {} XCTAssertEqual(count.value, 3) } // MARK: Review round (Fable, d143194) func testIdentityAndTeamThatAreNotPathSafeAreEncoded() { let odd = DocsOficinaSession.accountID(identity: "a/b", team: "c.d") XCTAssertFalse(odd.contains("/")) XCTAssertEqual(odd.split(separator: ".").count, 3, "prefix, identity, team: no stray dots") XCTAssertTrue(DocsOficinaSession.account(odd, belongsTo: "a/b")) XCTAssertFalse(DocsOficinaSession.account(odd, belongsTo: "a")) XCTAssertNotEqual(DocsOficinaSession.accountID(identity: "a", team: "b"), DocsOficinaSession.accountID(identity: "~a", team: "b")) XCTAssertEqual(DocsOficinaSession.accountID(identity: "Ab_9-z", team: "t1"), "oficina-id.Ab_9-z.t1", "safe parts stay readable") XCTAssertTrue(DocsOficinaSession.isOficinaAccount(odd)) XCTAssertFalse(DocsOficinaSession.isOficinaAccount(UUID().uuidString)) } func testReplacingTheIdentityPurgesItsSessions() async throws { onePaulTeam() onePaulTeam("id-till", email: "till@lagged.io") let docs = session() await signIn(docs) let paul = DocsOficinaSession.accountID(try XCTUnwrap(docs.signedIn)) docs.model.useAnother() XCTAssertTrue(docs.model.confirmingReplace) docs.model.confirmReplace() XCTAssertNil(docs.transport(for: paul)(), "the replaced identity's workspaces get no session") XCTAssertNil(docs.mounted) await signIn(docs, email: "till@lagged.io") let till = DocsOficinaSession.accountID(try XCTUnwrap(docs.signedIn)) XCTAssertNotEqual(till, paul) XCTAssertNotNil(docs.transport(for: till)()) XCTAssertNil(docs.transport(for: paul)(), "and never comes back") } func testAReMintRestartsAnOutboxStoppedByTheEndedSession() async throws { onePaulTeam() let docs = session() await signIn(docs) let account = DocsOficinaSession.accountID(try XCTUnwrap(docs.signedIn)) var supplied: NativeTransport? = nil let offline = DocsOfflineAccount(store: EphemeralDocsStore(), accountID: account, connectivity: NativeConnectivity(source: ScriptedPathSource(.satisfied)), transport: { supplied }) DocsOfflineAccount.accounts[account] = offline defer { DocsOfflineAccount.accounts[account] = nil } try await offline.outbox.enqueue(lane: "doc:k", kind: "update", payload: Data([1])) let stopped = await offline.drainer.drain() XCTAssertEqual(stopped, .sessionEnded) XCTAssertTrue(offline.drainer.sessionEnded) supplied = docs.transport(for: account)() await docs.rejected(account) XCTAssertFalse(offline.drainer.sessionEnded, "the new session restarts the stopped outbox") } func testA401WithHomeDownKeepsTheWorkspaceMounted() async throws { onePaulTeam() let docs = session() await signIn(docs) let first = try XCTUnwrap(docs.signedIn) let account = DocsOficinaSession.accountID(first) service.expire(session: first.session) service.failNext("assert", with: .offline) await docs.rejected(account) guard case .unavailable = docs.model.step else { return XCTFail("Home down: \(docs.model.step)") } XCTAssertEqual(docs.mounted, first, "the open workspace stays, under the Can't reach line") XCTAssertNotNil(docs.transport(for: account)()) await docs.model.retry() let second = try XCTUnwrap(docs.signedIn) XCTAssertEqual(docs.mounted, second) XCTAssertNotEqual(second.session.value, first.session.value) XCTAssertEqual(docs.client(for: account)?.credential?.value, second.session.value) } func testOnlyASignInMadeHereCountsNotARestore() async throws { onePaulTeam() let device = device() let first = session(on: device) await signIn(first) XCTAssertNotNil(first.signedIn) XCTAssertEqual(first.signIns, 1) // Docs launched again: the team comes back with no sign-in. let again = session(on: device) await again.start() XCTAssertNotNil(again.signedIn) XCTAssertEqual(again.signIns, 0, "a restored identity must not change the route someone chose") } func testRenewAfterADayGoesThroughTheSession() async throws { onePaulTeam() let docs = session() await signIn(docs) let first = try XCTUnwrap(docs.signedIn) let account = DocsOficinaSession.accountID(first) await docs.renewIfNeeded() XCTAssertEqual(exchanges(at: paulca), 1, "a fresh session is kept") clock.date.addTimeInterval(25 * 3600) await docs.renewIfNeeded() XCTAssertEqual(exchanges(at: paulca), 2) let renewed = try XCTUnwrap(docs.signedIn) XCTAssertNotEqual(renewed.session.value, first.session.value) XCTAssertEqual(docs.client(for: account)?.credential?.value, renewed.session.value) } func testTeamsRefreshAtLaunchOnTheMenuAndOnA403() async throws { onePaulTeam() let device = device() await signIn(session(on: device)) let titoTeam = team("t2", "Tito", "tito") service.setTeams([team("t1", "Paul", "paulca"), titoTeam], for: "id-paul") let teamsCalls = { self.service.calls.filter { $0 == "teams" }.count } clock.date.addTimeInterval(301) let docs = session(on: device) await docs.start() XCTAssertEqual(docs.model.store.teams("id-paul")?.teams.map(\.sqid), ["t1", "t2"], "launch refreshes") let afterLaunch = teamsCalls() await docs.pickerOpened() XCTAssertEqual(teamsCalls(), afterLaunch, "the menu waits five minutes") service.setTeams([team("t1", "Paul", "paulca")], for: "id-paul") await docs.refused() XCTAssertEqual(docs.model.store.teams("id-paul")?.teams.map(\.sqid), ["t1"], "a 403 refreshes at once") await docs.refused() XCTAssertEqual(teamsCalls(), afterLaunch + 1, "at most once a minute") clock.date.addTimeInterval(301) await docs.pickerOpened() XCTAssertEqual(teamsCalls(), afterLaunch + 2) } func testTheWatchReports403sAsRefusals() async throws { final class Count: @unchecked Sendable { var rejected = 0, refused = 0 } let count = Count() let watch = DocsSessionWatch(inner: ScriptedTransport([.respond(status: 403), .respond(status: 200)]), rejected: { count.rejected += 1 }, refused: { count.refused += 1 }) _ = try await watch.responseDetails("/", method: "GET", body: nil, contentType: "application/json", maxBytes: 1024) _ = try await watch.responseDetails("/", method: "GET", body: nil, contentType: "application/json", maxBytes: 1024) XCTAssertEqual(count.refused, 1) XCTAssertEqual(count.rejected, 0) } func testSharingExportImagesAndJumpUseTheCurrentSession() async throws { onePaulTeam() let docs = session() await signIn(docs) let first = try XCTUnwrap(docs.signedIn) let account = DocsOficinaSession.accountID(first) let opened = first.client() service.expire(session: first.session) await docs.rejected(account) let renewed = try XCTUnwrap(docs.signedIn) let live = DocsWorkspace.liveClient(docs.transport(for: account), fallback: opened) let watched = try XCTUnwrap(live as? DocsSessionWatch, "watched for 401s") XCTAssertEqual((watched.inner as? NativeHTTP)?.credential?.value, renewed.session.value) // A window without a supplier (a server account's) keeps its client. XCTAssertTrue(DocsWorkspace.liveClient(nil, fallback: opened) as AnyObject === opened) } // MARK: The store key outlives an origin change /// A keychain in memory, one item per KeychainKeyProvider account. final class MemoryKeychain: @unchecked Sendable { let lock = NSLock() var items: [String: StoreKeyState] = [:] struct Keys: KeyProvider { let chain: MemoryKeychain, account: String func copyKey() -> (OSStatus, SymmetricKey?) { chain.lock.withLock { chain.items[account].map { (errSecSuccess, SymmetricKey(data: $0.current)) } ?? (errSecItemNotFound, nil) } } func addKey(_ key: SymmetricKey) -> OSStatus { chain.lock.withLock { guard chain.items[account] == nil else { return errSecDuplicateItem } chain.items[account] = StoreKeyState(current: key.withUnsafeBytes { Data($0) }); return errSecSuccess } } func deleteKey() -> OSStatus { chain.lock.withLock { chain.items[account] = nil }; return errSecSuccess } func sealState() -> (OSStatus, StoreKeyState?) { chain.lock.withLock { chain.items[account].map { (errSecSuccess, $0) } ?? (errSecItemNotFound, nil) } } func saveSealState(_ state: StoreKeyState) -> OSStatus { chain.lock.withLock { chain.items[account] = state }; return errSecSuccess } } func keys(_ account: String, origin: URL) -> Keys { Keys(chain: self, account: DocsOfflineAccount.keys(accountID: account, origin: origin).account) } } func testAnOficinaTeamsStoreAndOutboxSurviveAnOriginChange() async throws { let root = FileManager.default.temporaryDirectory.appendingPathComponent("docs-origin-\(UUID().uuidString)") defer { try? FileManager.default.removeItem(at: root) } let chain = MemoryKeychain() let account = DocsOficinaSession.accountID(identity: "id-paul", team: "t1") let old = URL(string: "https://paul.docs.oficina.works")!, moved = URL(string: "https://paulca.docs.oficina.works")! let before = Outbox(store: NativeSealedStore(root: root, accountID: account, keys: chain.keys(account, origin: old)), account: account) try await before.enqueue(lane: "doc:k", kind: "update", payload: Data([7])) let after = Outbox(store: NativeSealedStore(root: root, accountID: account, keys: chain.keys(account, origin: moved)), account: account) try await after.load() let kept = await after.entries(lane: "doc:k", excludingInFlight: false) XCTAssertEqual(kept.map(\.payload), [Data([7])], "the label moved; the unsent change did not go with it") // A server account is its host: a new origin is a new account. let server = UUID().uuidString XCTAssertNotEqual(DocsOfflineAccount.keys(accountID: server, origin: old).account, DocsOfflineAccount.keys(accountID: server, origin: moved).account) } func testUnsentChangesLeftOnDiskBlockSigningOutOfThatIdentity() async throws { let root = FileManager.default.temporaryDirectory.appendingPathComponent("docs-unsent-\(UUID().uuidString)") defer { try? FileManager.default.removeItem(at: root) } let chain = MemoryKeychain() let account = DocsOficinaSession.accountID(identity: "id-paul", team: "t2") let keys: (String) -> KeyProvider = { chain.keys($0, origin: DocsOfflineAccount.oficinaKeyOrigin) } // An outbox a crash left behind, for a team not opened this run. let left = Outbox(store: NativeSealedStore(root: root.appendingPathComponent(account), accountID: account, keys: keys(account)), account: account) try await left.enqueue(lane: "doc:k", kind: "update", payload: Data([1])) let paul = await DocsOfflineAccount.hasUnsent(identity: "id-paul", root: root, keys: keys) let till = await DocsOfflineAccount.hasUnsent(identity: "id-till", root: root, keys: keys) XCTAssertTrue(paul) XCTAssertFalse(till) // Once sent, nothing blocks. let entries = await left.entries(lane: "doc:k", excludingInFlight: false) try await left.ack(entries.map(\.id)) let sent = await DocsOfflineAccount.hasUnsent(identity: "id-paul", root: root, keys: keys) XCTAssertFalse(sent) } func testTheLeaveGuardOrdersOpenDocumentsFirst() async { let open = await DocsLeaveBlock.check(identity: "id-nobody", openDocuments: true, unsentHere: true) XCTAssertEqual(open, .openDocuments) let unsent = await DocsLeaveBlock.check(identity: "id-nobody", openDocuments: false, unsentHere: true) XCTAssertEqual(unsent, .sending) XCTAssertFalse(DocsLeaveBlock.sending.message.isEmpty) XCTAssertNotEqual(DocsLeaveBlock.sending.message, "native.leave.sending", "the line is translated, not a key") } // MARK: Straight in (Paul, 2026-11-19; spec §9, rule 0) /// Paul on one team with Docs and Sheets, signed in on `device` by /// Sheets: the saved identity Docs finds at launch. A fixture that /// cannot sign in fails the test (never a skip, which would hide what /// depends on it). @discardableResult private func savedIdentity(on device: Device) async throws -> OficinaTeam { let paul = team("t1", "Paul", "paulca", apps: ["docs", "sheets"]) service.addPerson(email: "paul@tito.io", identityID: "id-paul") service.setTeams([paul], for: "id-paul") service.admit("id-paul", at: paulca, as: .linked) service.admit("id-paul", at: URL(string: "https://paulca.sheets.oficina.works")!, as: .linked) let clock = self.clock! let sheets = OficinaIDModel(configuration: OficinaIDConfiguration(app: "sheets", appName: "Sheets"), store: OficinaIDStore(shared: device.shared, appPrivate: OficinaMemoryStore(), group: device.group), service: service, passkeys: FakePasskeys(), makeKey: { OficinaSoftwareKey() }, now: { clock.date }, appDefaults: defaults()) await sheets.start() sheets.continueWithEmail() sheets.email = "paul@tito.io" await sheets.submitEmail() sheets.code = FakeOficinaIDService.goodCode await sheets.submitCode() guard case .signedIn = sheets.step else { XCTFail("Sheets did not sign in: \(sheets.step)") throw CancellationError() } return paul } /// One Oficina ID on the device: Docs opens its team with no screen, and /// the launch is not a sign-in made here (the route stays as chosen). func testASavedIdentitySignsDocsStraightIn() async throws { let device = device() let paul = try await savedIdentity(on: device) let docs = session(on: device) var steps: [String] = [] let watching = docs.model.$step.sink { steps.append("\($0)".components(separatedBy: "(").first ?? "") } await docs.start() watching.cancel() let mounted = try XCTUnwrap(docs.mounted, "straight in: \(docs.model.step)") XCTAssertEqual(mounted.team, paul) XCTAssertEqual(mounted.origin, paulca) XCTAssertEqual(Set(steps), ["loading", "signedIn"], "no screen on the way in") XCTAssertEqual(docs.signIns, 0, "going straight in does not choose the route") XCTAssertEqual(service.calls.filter { $0.hasPrefix("startCode") }.count, 1, "one sign-in for both apps") XCTAssertNotNil(docs.transport(for: DocsOficinaSession.accountID(mounted))()) } /// Docs' last route was its own sign-in: nothing goes straight in, and /// nothing touches the network, until the route is Oficina ID again. func testTheServerRouteSuspendsStraightIn() async throws { let device = device() try await savedIdentity(on: device) let docs = session(on: device) let calls = service.calls.count await docs.start(serverRoute: true) XCTAssertTrue(docs.model.straightInSuspended) XCTAssertNil(docs.mounted) XCTAssertEqual(docs.model.step, .welcome) XCTAssertEqual(service.calls.count, calls, "no network while Docs' own sign-in is the route") await docs.routeChanged(to: .oficinaID) XCTAssertFalse(docs.model.straightInSuspended) XCTAssertEqual(docs.mounted?.origin, paulca, "straight in once the route is Oficina ID") XCTAssertEqual(docs.signIns, 0) } /// The route alone decides: flipping to the server route while signed /// in suspends straight in and disturbs nothing; flipping back resumes /// without a second sign-in. func testTheRouteAloneDecidesTheSuspension() async throws { let device = device() try await savedIdentity(on: device) let docs = session(on: device) await docs.start() let mounted = try XCTUnwrap(docs.mounted) let exchangesBefore = exchanges(at: paulca) await docs.routeChanged(to: .server) XCTAssertTrue(docs.model.straightInSuspended) XCTAssertEqual(docs.mounted, mounted, "signed in, suspending changes nothing") XCTAssertNotNil(docs.transport(for: DocsOficinaSession.accountID(mounted))(), "the session stays usable") await docs.routeChanged(to: .oficinaID) XCTAssertFalse(docs.model.straightInSuspended) XCTAssertEqual(docs.mounted, mounted) XCTAssertEqual(exchanges(at: paulca), exchangesBefore, "resuming a signed-in model mints nothing") } /// "Use another Oficina ID" is asked only while signed in to the /// identity, never with one of its document windows open, never over an /// outage (the team stays mounted, but there is no dialog to ask with). func testUseAnotherIsRefusedWithAnOpenDocumentOrOverAnOutage() async throws { let device = device() let paul = try await savedIdentity(on: device) let docs = session(on: device) await docs.start() let state = try XCTUnwrap(docs.mounted) XCTAssertFalse(docs.useAnother(identity: state.identity.id, canLeave: false), "a document window is open") XCTAssertFalse(docs.model.confirmingReplace) XCTAssertFalse(docs.useAnother(identity: "id-someone-else", canLeave: true), "another identity's menu") XCTAssertFalse(docs.model.confirmingReplace) service.expire(session: state.session) service.failNext("exchange", at: paulca.absoluteString, with: .offline) await docs.rejected(DocsOficinaSession.accountID(state)) XCTAssertEqual(docs.model.step, .unavailable(paul)) XCTAssertNotNil(docs.mounted, "the workspace stays over the outage") XCTAssertFalse(docs.useAnother(identity: state.identity.id, canLeave: true), "over an outage") XCTAssertFalse(docs.model.confirmingReplace) await docs.model.retry() XCTAssertTrue(docs.useAnother(identity: state.identity.id, canLeave: true)) XCTAssertTrue(docs.model.confirmingReplace) } /// From the menu it only asks: cancelling changes nothing; confirming /// signs the identity out on every app and goes to Email, and its /// workspaces get no session. func testUseAnotherFromTheMenuAsksThenReplaces() async throws { let device = device() try await savedIdentity(on: device) let docs = session(on: device) await docs.start() let state = try XCTUnwrap(docs.mounted) let account = DocsOficinaSession.accountID(state) XCTAssertTrue(docs.useAnother(identity: state.identity.id, canLeave: true)) docs.model.cancelReplace() XCTAssertEqual(docs.mounted, state, "cancelling changes nothing") XCTAssertEqual(docs.client(for: account)?.credential?.value, state.session.value) XCTAssertTrue(service.isLive(session: state.session)) XCTAssertTrue(docs.useAnother(identity: state.identity.id, canLeave: true)) docs.model.confirmReplace() await docs.model.cleanup?.value XCTAssertNil(docs.mounted) XCTAssertEqual(docs.model.step, .email) XCTAssertEqual(try docs.model.store.identities(), [], "signed out on every app") XCTAssertNil(docs.transport(for: account)()) } /// #130, finding 1: with changes unsent, "Use another" is refused before /// the kit asks. The confirmation used to go up, and be confirmable, /// while the outbox was being checked, then be withdrawn. func testUseAnotherWithUnsentChangesIsRefusedBeforeItAsks() async throws { let device = device() try await savedIdentity(on: device) let docs = session(on: device) await docs.start() let state = try XCTUnwrap(docs.mounted) let account = DocsOficinaSession.accountID(state) let offline = DocsOfflineAccount(store: EphemeralDocsStore(), accountID: account, connectivity: NativeConnectivity(source: ScriptedPathSource(.satisfied)), transport: { nil }) DocsOfflineAccount.accounts[account] = offline defer { DocsOfflineAccount.accounts[account] = nil } try await offline.outbox.enqueue(lane: "doc:k", kind: "update", payload: Data([1])) var asked = 0 let watch = docs.model.$confirmingReplace.sink { if $0 { asked += 1 } } defer { watch.cancel() } let refused = await docs.requestUseAnother(identity: state.identity.id, openDocuments: { false }) XCTAssertEqual(refused, .sending) XCTAssertEqual(asked, 0, "the confirmation never went up") XCTAssertEqual(docs.mounted, state) // A document window opened while the outbox was checked refuses too. DocsOfflineAccount.accounts[account] = nil var windowOpen = false let opened = await docs.requestUseAnother(identity: state.identity.id, openDocuments: { defer { windowOpen = true } return windowOpen }) XCTAssertEqual(opened, .openDocuments) XCTAssertEqual(asked, 0) // Nothing unsent, no window: the kit asks. let clear = await docs.requestUseAnother(identity: state.identity.id, openDocuments: { false }) XCTAssertNil(clear) XCTAssertEqual(asked, 1) XCTAssertTrue(docs.model.confirmingReplace) } /// #130, finding 4: a write sent on the old cookie comes back "signed /// out" after another request's re-mint has already replaced the /// session. It must not leave the outbox stopped ("needs sign-in") with /// a good session, nor mint again. func testARefusalOfAnAlreadyReplacedSessionRestartsTheOutbox() async throws { onePaulTeam() let docs = session() await signIn(docs) let first = try XCTUnwrap(docs.signedIn) let account = DocsOficinaSession.accountID(first) // The outbox's write goes out on the first session... let server = ScriptedTransport([.respond(status: 403, body: Data("signed out\n".utf8))]) let stale = docs.watch(server, account: account, session: first.session.value) let offline = DocsOfflineAccount(store: EphemeralDocsStore(), accountID: account, connectivity: NativeConnectivity(source: ScriptedPathSource(.satisfied)), transport: { stale }) DocsOfflineAccount.accounts[account] = offline defer { DocsOfflineAccount.accounts[account] = nil } try offline.saveMetadata(DocsOfflineMetadata(detail: DocumentDetail(sqid: "k", title: "Notes", guid: "g", can_write: true, can_share: true), pendingTitle: "Plans"), key: "k") try await offline.outbox.enqueue(lane: "doc:k", kind: "metadata", payload: Data()) // ...and another request's re-mint completes first. service.expire(session: first.session) await docs.rejected(account) XCTAssertNotEqual(try XCTUnwrap(docs.signedIn).session.value, first.session.value) let exchanged = exchanges(at: paulca) // Then the write's "signed out" lands and stops the outbox. let stopped = await offline.drainer.drain() XCTAssertEqual(stopped, .sessionEnded) XCTAssertEqual(server.calls.map(\.path), ["/d/k/title"]) let deadline = Date().addingTimeInterval(2) while offline.drainer.sessionEnded, Date() < deadline { try await Task.sleep(for: .milliseconds(10)) } XCTAssertFalse(offline.drainer.sessionEnded, "the outbox sends again on the session it now has") XCTAssertEqual(exchanges(at: paulca), exchanged, "a refusal of a replaced session mints nothing") } /// Docs' guards answer a write with an ended session 403 "signed out" /// (internal/docs/native_contract_test.go): that is the session, not /// the request, so it re-mints and reads as unauthorized. Any other 403 /// stays a refusal of the request. func testASignedOut403IsAnEndedSession() async throws { final class Counts: @unchecked Sendable { var rejected = 0, refused = 0 } let counts = Counts() let server = ScriptedTransport([ .respond(status: 403, body: Data("signed out\n".utf8)), .respond(status: 403, body: Data("Something went wrong.\n".utf8)), .respond(status: 403, body: Data("signed out".utf8)), ]) let watch = DocsSessionWatch(inner: server, rejected: { counts.rejected += 1 }, refused: { counts.refused += 1 }) let ended = try await watch.responseDetails("/documents", method: "POST", body: Data("{}".utf8), contentType: "application/json", maxBytes: 1024) XCTAssertEqual(ended.status, 401) XCTAssertEqual(counts.rejected, 1) XCTAssertEqual(counts.refused, 0) for _ in 0..<2 { let refusal = try await watch.responseDetails("/documents", method: "POST", body: Data("{}".utf8), contentType: "application/json", maxBytes: 1024) XCTAssertEqual(refusal.status, 403) } XCTAssertEqual(counts.rejected, 1, "only the exact bytes are an ended session") XCTAssertEqual(counts.refused, 2) } /// What the signed-in window's body builds, built under observation as /// a body is: the transport and the workspace, with "Use another". None /// of it may change anything a view watches, or each body pass would /// invalidate the next (84d1008). func testBuildingTheSignedInWorkspaceChangesNothingAViewWatches() async throws { let device = device() try await savedIdentity(on: device) let docs = session(on: device) await docs.start() let state = try XCTUnwrap(docs.mounted) let account = DocsOficinaSession.accountID(state) let offline = DocsOfflineAccount(store: EphemeralDocsStore(), accountID: account, connectivity: NativeConnectivity(source: ScriptedPathSource(.satisfied)), transport: docs.transport(for: account)) DocsOfflineAccount.accounts[account] = offline defer { DocsOfflineAccount.accounts[account] = nil } let client = try XCTUnwrap(docs.client(for: account)) var published = 0 let watches = [docs.objectWillChange.sink { _ in published += 1 }, docs.model.objectWillChange.sink { _ in published += 1 }] let changed = Mutex(false) withObservationTracking { _ = offline.drainer.status() _ = offline.drainer.sessionEnded _ = DocsWorkspace(client: client, accountID: account, transport: docs.transport(for: account), accounts: {}, signOut: {}, accountsLabel: DocsOficinaSession.teamsTitle, signOutLabel: "Sign out", useAnother: {}) _ = docs.mounted _ = docs.model.step } onChange: { changed.withLock { $0 = true } } for _ in 0..<3 { _ = DocsWorkspace(client: client, accountID: account, transport: docs.transport(for: account), signOut: {}, useAnother: {}) } watches.forEach { $0.cancel() } XCTAssertFalse(changed.withLock { $0 }, "building the signed-in workspace must not invalidate its window") XCTAssertEqual(published, 0, "nor publish from the session or the model") } #if os(macOS) func testTheLaunchCheckFailsWithoutTheEntitlements() { // The test runner is not signed with Docs' entitlements: every check // that needs them must say FAIL, or the gate could not catch a build // that lost them. let result = DocsOficinaLaunchCheck.run() XCTAssertFalse(result.passed) for name in ["keychain-access-groups", "shared group", "Docs' group", "App Group", "associated domains"] { XCTAssertTrue(result.lines.contains { $0.hasPrefix("FAIL \(name)") }, "\(name): \(result.lines)") } } #endif }