Keep each account's answers to that account
Review finding 1 (Astra on 3e62cfb, blocker): BaseSession's refresh published whatever came back, so an account's /me and /home answering after a sign-out, or after another account had signed in, landed in the new session. The session now has a generation, bumped whenever the account (identity and Base) changes or ends; a refresh publishes only under the generation it started in, old work is cancelled, and a client's 401 reaches the kit only while its account is still the one. The kit's Loading step no longer reads as a sign-out.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
4 files changed,
+190
−15
native/apple/Sources/BaseKit/API/Client.swift+3 −0native/apple/Sources/BaseKit/Session/BaseSession.swift+50 −15native/apple/Tests/BaseKitTests/SessionTests.swift+86 −0native/apple/Tests/BaseKitTests/Support.swift+51 −0
diff --git a/native/apple/Sources/BaseKit/API/Client.swift b/native/apple/Sources/BaseKit/API/Client.swift| index 5381e53..987502e 100644 |
| --- a/native/apple/Sources/BaseKit/API/Client.swift |
| +++ b/native/apple/Sources/BaseKit/API/Client.swift |
| @@ -39,6 +39,9 @@ public struct BaseClient: Sendable { |
| public var origin: URL { transport.origin } |
| + /// What a refused session calls, for tests. |
| + func rejectedForTests() async { await rejected() } |
| + |
| // MARK: Reads |
| public func me() async throws(BaseAPIError) -> Me { try await get("/api/v1/me") } |
diff --git a/native/apple/Sources/BaseKit/Session/BaseSession.swift b/native/apple/Sources/BaseKit/Session/BaseSession.swift| index 8850d04..a488a30 100644 |
| --- a/native/apple/Sources/BaseKit/Session/BaseSession.swift |
| +++ b/native/apple/Sources/BaseKit/Session/BaseSession.swift |
| @@ -49,43 +49,75 @@ import RastrilloApple |
| /// The kit moved: signed in (perhaps with a fresh session), or out. |
| func stepChanged(_ step: OficinaIDModel.Step) { |
| + // Loading is the kit reading its store, not a sign-out. |
| + if step == .loading { return } |
| guard case .signedIn(let state) = step else { |
| - if signedIn != nil { signedOut() } |
| + if account != nil { end() } |
| return |
| } |
| - let http = state.client() |
| - if let transport, let current = signedIn, current.origin == state.origin, current.identity.id == state.identity.id { |
| + begin(identity: state.identity.id, origin: state.origin, transport: state.client(), state: state) |
| + } |
| + |
| + /// Who the session is for: an identity at a Base. Anything that |
| + /// started for one account publishes nothing once the account changes. |
| + struct Account: Equatable { let identity: String; let origin: URL } |
| + @ObservationIgnored private(set) var account: Account? |
| + /// Bumped whenever the account changes or ends: work started under an |
| + /// older generation publishes nothing. |
| + @ObservationIgnored private(set) var generation = 0 |
| + @ObservationIgnored private(set) var refreshing: Task<Void, Never>? |
| + /// Base refused the session: the kit mints a new one silently. |
| + @ObservationIgnored lazy var rejected: @MainActor () async -> Void = { [oficina] in await oficina.sessionRejected() } |
| + |
| + /// Signed in as `identity` at `origin`. The same account again (the kit |
| + /// renewed its session) swaps the session under the client; another |
| + /// account starts afresh, and nothing of the old one lands. |
| + func begin(identity: String, origin: URL, transport http: NativeTransport, state: OficinaSignedIn? = nil) { |
| + let next = Account(identity: identity, origin: origin) |
| + if let transport, account == next { |
| transport.swap(http) |
| signedIn = state |
| return |
| } |
| - ask?.pause() |
| + end() |
| + let epoch = generation |
| let swappable = SwappableTransport(http) |
| - let oficina = self.oficina |
| - let client = BaseClient(transport: swappable) { await oficina.sessionRejected() } |
| + // A 401 is only this account's to act on while it is still the one. |
| + let client = BaseClient(transport: swappable) { [weak self] in |
| + guard let self, await self.generation == epoch else { return } |
| + await self.rejected() |
| + } |
| + account = next |
| transport = swappable |
| self.client = client |
| signedIn = state |
| - me = nil |
| - home = nil |
| ask = AskModel(client: client) |
| - Task { await self.refresh() } |
| + refreshing = Task { await self.refresh() } |
| } |
| - private func signedOut() { |
| + /// Signed out, or about to be someone else: the old account's work is |
| + /// cancelled and anything still in flight lands on nothing. |
| + func end() { |
| + generation += 1 |
| + refreshing?.cancel() |
| + refreshing = nil |
| ask?.pause() |
| - ask = nil; client = nil; transport = nil |
| + ask = nil; client = nil; transport = nil; account = nil |
| signedIn = nil; me = nil; home = nil |
| } |
| - /// Reads the member, Home and Ask afresh. |
| + /// Reads the member, Home and Ask afresh, for the account it started |
| + /// under only. |
| public func refresh() async { |
| guard let client else { return } |
| + let epoch = generation |
| async let me = try? client.me() |
| async let home = try? client.home() |
| await ask?.load() |
| - if let me = await me { self.me = me } |
| - if let home = await home { self.home = home } |
| + let (newMe, newHome) = await (me, home) |
| + guard generation == epoch, !Task.isCancelled else { return } |
| + if let newMe { self.me = newMe } |
| + if let newHome { self.home = newHome } |
| } |
| /// The app came forward. |
| @@ -104,18 +136,21 @@ import RastrilloApple |
| /// failure puts the old one back. |
| public func setAppearance(_ appearance: BaseAppearance) async { |
| guard let client, var me else { return } |
| + let epoch = generation |
| let before = me.appearance |
| me.appearance = appearance |
| self.me = me |
| do { try await client.setAppearance(appearance) } catch { |
| - self.me?.appearance = before |
| + if generation == epoch { self.me?.appearance = before } |
| } |
| } |
| /// Settings' Disconnect for Ask, then Ask as it is now. |
| public func disconnectAsk() async { |
| guard let client else { return } |
| + let epoch = generation |
| try? await client.disconnectAsk() |
| + guard generation == epoch else { return } |
| await ask?.load() |
| } |
diff --git a/native/apple/Tests/BaseKitTests/SessionTests.swift b/native/apple/Tests/BaseKitTests/SessionTests.swift| new file mode 100644 |
| index 0000000..04397b5 |
| --- /dev/null |
| +++ b/native/apple/Tests/BaseKitTests/SessionTests.swift |
| @@ -0,0 +1,86 @@ |
| +@testable import BaseKit |
| +import Foundation |
| +import RastrilloApple |
| +import RastrilloTestSupport |
| +import XCTest |
| + |
| +/// Review finding 1 (Astra, 3e62cfb): nothing one account started may land |
| +/// in the next account's session, or after signing out. |
| +@MainActor final class SessionTests: XCTestCase { |
| + func me(_ id: String, _ base: String) -> String { |
| + #"{"member":{"id":"\#(id)","name":"\#(id)","email":"\#(id)@x.example","initials":"X","owner":false},"base":{"name":"\#(base)","slug":"x","origin":"https://x.example","timezone":"UTC"},"appearance":"system","equipo_origin":null}"# |
| + } |
| + func home(_ greeting: String) -> String { #"{"greeting":"\#(greeting)","lede":"","steps":[],"apps":[]}"# } |
| + let unavailable = #"{"state":"unavailable","messages":[],"jobs":[],"cards":[],"turn":null,"status":"","cursor":0}"# |
| + |
| + func gated(_ id: String, _ base: String, _ greeting: String) -> GatedTransport { |
| + let t = GatedTransport() |
| + t.answer("/api/v1/me", me(id, base)) |
| + t.answer("/api/v1/home", home(greeting)) |
| + t.answer("/ask/state", unavailable) |
| + return t |
| + } |
| + |
| + func testAnOldAccountsAnswersNeverLandInTheNext() async { |
| + let session = BaseSession(oficina: memoryOficina()) |
| + let alice = gated("alice", "Alice's", "Hello Alice") |
| + session.begin(identity: "id-alice", origin: URL(string: "https://alice.example")!, transport: alice) |
| + let aliceRefresh = session.refreshing |
| + session.end() |
| + let bob = gated("bob", "Bob's", "Hello Bob") |
| + for path in ["/api/v1/me", "/api/v1/home", "/ask/state"] { bob.release(path) } |
| + session.begin(identity: "id-bob", origin: URL(string: "https://bob.example")!, transport: bob) |
| + await session.refreshing?.value |
| + XCTAssertEqual(session.me?.member.id, "bob") |
| + for path in ["/api/v1/me", "/api/v1/home", "/ask/state"] { alice.release(path) } |
| + await aliceRefresh?.value |
| + XCTAssertEqual(session.me?.member.id, "bob", "Alice's answer must not land in Bob's session") |
| + XCTAssertEqual(session.home?.greeting, "Hello Bob") |
| + } |
| + |
| + func testNothingLandsAfterSigningOut() async { |
| + let session = BaseSession(oficina: memoryOficina()) |
| + let alice = gated("alice", "Alice's", "Hello Alice") |
| + session.begin(identity: "id-alice", origin: URL(string: "https://alice.example")!, transport: alice) |
| + let refresh = session.refreshing |
| + session.end() |
| + for path in ["/api/v1/me", "/api/v1/home", "/ask/state"] { alice.release(path) } |
| + await refresh?.value |
| + XCTAssertNil(session.me) |
| + XCTAssertNil(session.home) |
| + XCTAssertNil(session.ask) |
| + } |
| + |
| + func testTheSameAccountKeepsItsModelsWhenItsSessionIsRenewed() async { |
| + let session = BaseSession(oficina: memoryOficina()) |
| + let first = gated("alice", "Alice's", "Hello Alice") |
| + for path in ["/api/v1/me", "/api/v1/home", "/ask/state"] { first.release(path) } |
| + let origin = URL(string: "https://alice.example")! |
| + session.begin(identity: "id-alice", origin: origin, transport: first) |
| + await session.refreshing?.value |
| + let ask = session.ask |
| + session.begin(identity: "id-alice", origin: origin, transport: gated("alice", "Alice's", "Hello Alice")) |
| + XCTAssertTrue(session.ask === ask, "a renewed session swaps under the client") |
| + XCTAssertEqual(session.me?.member.id, "alice") |
| + } |
| +} |
| + |
| +extension SessionTests { |
| + /// An old account's 401, arriving late, doesn't sign the new one in again. |
| + func testAnOldAccountsRefusalIsNotTheNewOnes() async throws { |
| + let session = BaseSession(oficina: memoryOficina()) |
| + var rejections = 0 |
| + session.rejected = { rejections += 1 } |
| + let alice = ScriptedTransport([json(401, #"{"code":"unauthenticated"}"#)]) |
| + session.begin(identity: "id-alice", origin: URL(string: "https://alice.example")!, transport: GatedTransport()) |
| + let old = try XCTUnwrap(session.client) |
| + session.end() |
| + session.begin(identity: "id-bob", origin: URL(string: "https://bob.example")!, transport: GatedTransport()) |
| + // Alice's client, refused after Bob signed in. |
| + let refused = BaseClient(transport: alice, rejected: { await old.rejectedForTests() }) |
| + _ = try? await refused.me() |
| + XCTAssertEqual(rejections, 0) |
| + _ = try? await session.client!.rejectedForTests() |
| + XCTAssertEqual(rejections, 1, "the current account's refusal still reaches the kit") |
| + } |
| +} |
diff --git a/native/apple/Tests/BaseKitTests/Support.swift b/native/apple/Tests/BaseKitTests/Support.swift| index 6167acc..e48a8e7 100644 |
| --- a/native/apple/Tests/BaseKitTests/Support.swift |
| +++ b/native/apple/Tests/BaseKitTests/Support.swift |
| @@ -83,3 +83,54 @@ final class LocalServer: @unchecked Sendable { |
| deinit { listener.cancel() } |
| } |
| + |
| +/// A transport whose answers wait until the test releases them, path by |
| +/// path: for races (an old account's answer landing after a new sign-in). |
| +final class GatedTransport: NativeTransport, @unchecked Sendable { |
| + let origin: URL |
| + private let lock = NSLock() |
| + private var answers: [String: (Int, Data)] = [:] |
| + private var waiting: [String: [CheckedContinuation<Void, Never>]] = [:] |
| + private var released: Set<String> = [] |
| + private var seen: [String] = [] |
| + init(origin: URL = URL(string: "https://gated.invalid")!) { self.origin = origin } |
| + var calls: [String] { lock.withLock { seen } } |
| + |
| + /// What `path` answers once released. |
| + func answer(_ path: String, status: Int = 200, _ body: String) { lock.withLock { answers[path] = (status, Data(body.utf8)) } } |
| + func release(_ path: String) { |
| + let ready = lock.withLock { () -> [CheckedContinuation<Void, Never>] in |
| + released.insert(path) |
| + defer { waiting[path] = nil } |
| + return waiting[path] ?? [] |
| + } |
| + for c in ready { c.resume() } |
| + } |
| + func responseDetails(_ path: String, method: String, body: Data?, contentType: String, maxBytes: Int) async throws -> NativeResponse { |
| + await withCheckedContinuation { (c: CheckedContinuation<Void, Never>) in |
| + let go = lock.withLock { () -> Bool in |
| + seen.append(path) |
| + if released.contains(path) { return true } |
| + waiting[path, default: []].append(c) |
| + return false |
| + } |
| + if go { c.resume() } |
| + } |
| + let (status, data) = lock.withLock { answers[path] ?? (404, Data()) } |
| + return NativeResponse(data: data, status: status, headers: [:]) |
| + } |
| + func stream(_ path: String, onOpen: @Sendable () async throws -> Void, onLine: @Sendable (String) async throws -> Void) async throws { |
| + lock.withLock { seen.append(path) } |
| + try await Task.sleep(for: .seconds(3600)) |
| + } |
| + func download(_ path: String, to destination: URL) async throws {} |
| +} |
| + |
| +/// A kit model that never touches the keychain, App Group or network. |
| +@MainActor func memoryOficina() -> OficinaIDModel { |
| + let suite = "BaseKitTests.\(UUID().uuidString)" |
| + let defaults = UserDefaults(suiteName: suite)! |
| + let store = OficinaIDStore(shared: OficinaMemoryStore(), appPrivate: OficinaMemoryStore(), group: defaults) |
| + return OficinaIDModel(configuration: BaseSession.configuration, store: store, service: FakeOficinaIDService(), |
| + passkeys: FakePasskeys(), appDefaults: defaults) |
| +} |