From 7e0f4c489fae37c978b116bde097ee459de31d21 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sun, 29 Nov 2026 06:22:18 +0700 Subject: [PATCH 1/4] fix(core-sync): a sign-in on a new device row takes over the state file its removed row left --- .../Services/TeamLibrary/TeamLibrary.swift | 26 +- .../TeamLibrary/TeamLibraryFailure.swift | 8 +- .../Account/AccountSettingsModel.swift | 34 ++- .../TeamLibrary/TeamLibraryPublishing.swift | 2 + .../TeamLibrarySyncStatusView.swift | 3 +- .../TeamLibraryUnsentChanges.swift | 2 + .../TeamLibrary/TeamLibraryTests.swift | 6 +- .../Settings/AccountSettingsModelTests.swift | 24 ++ core/crates/ffi/src/sync/engines.rs | 10 +- core/crates/ffi/src/sync/tests.rs | 67 +++++ core/crates/sync/src/api/state.rs | 21 +- core/crates/sync/src/keys/account_sign_out.rs | 54 ++-- core/crates/sync/src/keys/mod.rs | 2 + core/crates/sync/src/keys/replaced_row.rs | 55 +++++ core/crates/sync/src/state/file.rs | 84 ++++++- core/crates/sync/src/state/integrity/mod.rs | 2 +- .../crates/sync/tests/account_keys/harness.rs | 11 + core/crates/sync/tests/account_keys/main.rs | 1 + .../sync/tests/account_keys/replaced_row.rs | 233 ++++++++++++++++++ ...n-the-core-for-tablepro-sync-and-icloud.md | 2 +- ...-end-to-end-keys-per-account-and-device.md | 2 +- ...s-over-the-state-file-its-last-row-left.md | 30 +++ core/docs/decisions/README.md | 5 +- 23 files changed, 636 insertions(+), 48 deletions(-) create mode 100644 core/crates/sync/src/keys/replaced_row.rs create mode 100644 core/crates/sync/tests/account_keys/replaced_row.rs create mode 100644 core/docs/decisions/0081-a-sign-in-on-a-new-device-row-takes-over-the-state-file-its-last-row-left.md diff --git a/apple/TablePro/Core/Services/TeamLibrary/TeamLibrary.swift b/apple/TablePro/Core/Services/TeamLibrary/TeamLibrary.swift index 5022df35b3..5c8dc46977 100644 --- a/apple/TablePro/Core/Services/TeamLibrary/TeamLibrary.swift +++ b/apple/TablePro/Core/Services/TeamLibrary/TeamLibrary.swift @@ -336,19 +336,19 @@ internal final class TeamLibrary: ObservableObject { // MARK: - Sign Out // The edits Sign Out lists, read from the engine whatever shows, since a lost team_library hides the library but - // keeps its edits. Nil when they could not be read. - func unsentChanges() async -> [String]? { - guard let owner else { return nil } + // keeps its edits. The failure says why they could not be read. + func unsentChanges() async -> Result<[String], TeamLibraryFailure> { + guard let owner else { return .failure(.unavailable) } do { - return try await source.engine().unsentTeamEdits(expectedOwner: owner).map(Self.name(of:)) + return .success(try await source.engine().unsentTeamEdits(expectedOwner: owner).map(Self.name(of:))) } catch { Self.logger.error("Listing the unsent Team Library edits failed: \(error.publicLogShape, privacy: .public)") - return nil + return .failure(TeamLibraryFailure(error)) } } - // Upload: one pass now. What the team has still not taken comes back, with why; nil when it could not be read. - func upload() async -> (unsent: [String]?, failure: TeamLibraryFailure?) { + // Upload: one pass now. What the team has still not taken comes back, with why. + func upload() async -> (unsent: Result<[String], TeamLibraryFailure>, failure: TeamLibraryFailure?) { var failure: TeamLibraryFailure? do { try await source.engine().syncNow(why: .person) @@ -356,10 +356,16 @@ internal final class TeamLibrary: ObservableObject { failure = TeamLibraryFailure(error) } await refresh() - guard let left = await unsentChanges() else { return (nil, failure ?? .unavailable) } - guard !left.isEmpty else { return ([], nil) } + let left: [String] + switch await unsentChanges() { + case .success(let listed): + left = listed + case .failure(let listing): + return (.failure(listing), failure ?? listing) + } + guard !left.isEmpty else { return (.success([]), nil) } let problem = lastStatuses.lazy.compactMap(\.problem).first.map(TeamLibraryFailure.init(code:)) - return (left, failure ?? problem ?? .offline) + return (.success(left), failure ?? problem ?? .offline) } // The sign-out of `session`, then all of the account's Team Library data, verified gone: the engine's, through the diff --git a/apple/TablePro/Core/Services/TeamLibrary/TeamLibraryFailure.swift b/apple/TablePro/Core/Services/TeamLibrary/TeamLibraryFailure.swift index 5e0be61301..db29fd5e16 100644 --- a/apple/TablePro/Core/Services/TeamLibrary/TeamLibraryFailure.swift +++ b/apple/TablePro/Core/Services/TeamLibrary/TeamLibraryFailure.swift @@ -20,6 +20,8 @@ internal enum TeamLibraryFailure: Error, Equatable, Sendable { case refused // The last account's Team Library data is not deleted yet, so nothing of it is read or sent. case deletePending + // This Mac's sync state for the account can't be opened, so nothing of it can be read or sent. + case stateUnreadable case unavailable // The engine's code for a pass, a publish or a refused edit (core ADR 0051, Whole-request refusals). @@ -44,6 +46,8 @@ internal enum TeamLibraryFailure: Error, Equatable, Sendable { self = .deletePending case "sync.unimplemented", "sync.not_allowed": self = .unavailable + case "sync.state.wrong_identity", "sync.state.integrity": + self = .stateUnreadable default: self = .refused } @@ -68,6 +72,7 @@ internal enum TeamLibraryFailure: Error, Equatable, Sendable { case .licenseExpired: "licenseExpired" case .refused: "refused" case .deletePending: "deletePending" + case .stateUnreadable: "stateUnreadable" case .unavailable: "unavailable" } } @@ -77,7 +82,8 @@ internal enum TeamLibraryFailure: Error, Equatable, Sendable { switch self { case .offline, .rateLimited, .server: true - case .signedOut, .unreadable, .writeForbidden, .licenseExpired, .refused, .deletePending, .unavailable: + case .signedOut, .unreadable, .writeForbidden, .licenseExpired, .refused, .deletePending, .stateUnreadable, + .unavailable: false } } diff --git a/apple/TablePro/Views/Settings/Account/AccountSettingsModel.swift b/apple/TablePro/Views/Settings/Account/AccountSettingsModel.swift index 53d6e88356..40a05db8ed 100644 --- a/apple/TablePro/Views/Settings/Account/AccountSettingsModel.swift +++ b/apple/TablePro/Views/Settings/Account/AccountSettingsModel.swift @@ -17,25 +17,41 @@ internal struct AccountActionFailure: Equatable, Identifiable { internal struct AccountSignOutConfirmation: Equatable { // The Team Library edits the team has not taken yet, read just before the question; nil when they could not be - // read, so the question still offers Upload. + // read, so the question still offers Upload unless the reason rules every upload out. let teamChanges: [String]? var uploadFailure: TeamLibraryFailure? let removesOfflineFile: Bool // Sign Out erases this Mac's end-to-end keys, so it needs approval again after the next sign-in. var erasesKeys = false + // Why `teamChanges` could not be read. + var listFailure: TeamLibraryFailure? - var asksAboutTeamChanges: Bool { + // Edits that could not be read may still be there. + private var mayHoldTeamChanges: Bool { teamChanges.map { !$0.isEmpty } ?? true } + // With this Mac's sync data unreadable no upload can run, so there is nothing to ask. + private var uploadIsPossible: Bool { + teamChanges != nil || listFailure != .stateUnreadable + } + + var asksAboutTeamChanges: Bool { + mayHoldTeamChanges && uploadIsPossible + } + var discardsSomething: Bool { - asksAboutTeamChanges || removesOfflineFile || erasesKeys + mayHoldTeamChanges || removesOfflineFile || erasesKeys } var message: String { var sentences = [String(localized: "Paid features stop on this Mac until you sign in again.")] if let teamChanges, !teamChanges.isEmpty { sentences.append(TeamLibraryUnsentChanges.message(teamChanges, failure: uploadFailure)) + } else if teamChanges == nil, !uploadIsPossible { + sentences.append(String( + localized: "TablePro couldn't read this Mac's sync data for the account, so no Team Library change can be uploaded. Signing out discards any there are." + )) } else if teamChanges == nil { if let uploadFailure { sentences.append(String( @@ -269,10 +285,11 @@ internal final class AccountSettingsModel: ObservableObject { while isCurrent() { asksSignOut = true let answer = await askSignOut(AccountSignOutConfirmation( - teamChanges: changes, + teamChanges: try? changes.get(), uploadFailure: failure, removesOfflineFile: services.access.state.entitlement?.isOffline == true, - erasesKeys: erasesKeys + erasesKeys: erasesKeys, + listFailure: Self.failure(of: changes) )) asksSignOut = false guard isCurrent() else { return } @@ -284,7 +301,7 @@ internal final class AccountSettingsModel: ObservableObject { return case .upload: (changes, failure) = await teamLibrary.upload() - if changes?.isEmpty == true, isCurrent() { + if (try? changes.get())?.isEmpty == true, isCurrent() { await finishSignOut(teamLibrary, session: session, isCurrent: isCurrent) return } @@ -292,6 +309,11 @@ internal final class AccountSettingsModel: ObservableObject { } } + private static func failure(of listed: Result<[String], TeamLibraryFailure>) -> TeamLibraryFailure? { + guard case .failure(let failure) = listed else { return nil } + return failure + } + private func finishSignOut( _ teamLibrary: TeamLibrary, session: String?, diff --git a/apple/TablePro/Views/TeamLibrary/TeamLibraryPublishing.swift b/apple/TablePro/Views/TeamLibrary/TeamLibraryPublishing.swift index ab61caf520..8a88896655 100644 --- a/apple/TablePro/Views/TeamLibrary/TeamLibraryPublishing.swift +++ b/apple/TablePro/Views/TeamLibrary/TeamLibraryPublishing.swift @@ -89,6 +89,8 @@ internal enum TeamLibraryPublishing { return String(localized: "The team library refused the change. It may be too large or hold a field the library never stores.") case .deletePending: return String(localized: "TablePro is still deleting the Team Library data of the last account on this Mac. Team Library stays off until it is gone.") + case .stateUnreadable: + return String(localized: "TablePro couldn't read this Mac's sync data for the account.") case .unavailable: return String(localized: "Team Library isn't available on this Mac right now.") } diff --git a/apple/TablePro/Views/TeamLibrary/TeamLibrarySyncStatusView.swift b/apple/TablePro/Views/TeamLibrary/TeamLibrarySyncStatusView.swift index 11805b819f..e960a4d76c 100644 --- a/apple/TablePro/Views/TeamLibrary/TeamLibrarySyncStatusView.swift +++ b/apple/TablePro/Views/TeamLibrary/TeamLibrarySyncStatusView.swift @@ -85,7 +85,8 @@ internal enum TeamLibrarySyncDescription { switch failure { case .offline, .rateLimited, .server: return String(format: String(localized: "%@ TablePro tries again shortly."), TeamLibraryPublishing.failureText(failure)) - case .signedOut, .unreadable, .writeForbidden, .licenseExpired, .refused, .deletePending, .unavailable: + case .signedOut, .unreadable, .writeForbidden, .licenseExpired, .refused, .deletePending, .stateUnreadable, + .unavailable: return TeamLibraryPublishing.failureText(failure) } } diff --git a/apple/TablePro/Views/TeamLibrary/TeamLibraryUnsentChanges.swift b/apple/TablePro/Views/TeamLibrary/TeamLibraryUnsentChanges.swift index 53ae104090..c631a02933 100644 --- a/apple/TablePro/Views/TeamLibrary/TeamLibraryUnsentChanges.swift +++ b/apple/TablePro/Views/TeamLibrary/TeamLibraryUnsentChanges.swift @@ -34,6 +34,8 @@ internal enum TeamLibraryUnsentChanges { why = String(localized: "no seat in the team") case .offline, .rateLimited, .server: why = String(localized: "the upload did not go through") + case .stateUnreadable: + why = String(localized: "this Mac's sync data couldn't be read") default: why = String(localized: "the team library refused it") } diff --git a/apple/TableProTests/TeamLibrary/TeamLibraryTests.swift b/apple/TableProTests/TeamLibrary/TeamLibraryTests.swift index 3471239bff..53fa9bbe82 100644 --- a/apple/TableProTests/TeamLibrary/TeamLibraryTests.swift +++ b/apple/TableProTests/TeamLibrary/TeamLibraryTests.swift @@ -384,7 +384,7 @@ struct TeamLibraryTests { let answer = await fixture.library.upload() #expect(engine.passes == 1) - #expect(answer.unsent == [TeamLibraryUnsentChanges.refused("Huge", because: .refused)]) + #expect((try? answer.unsent.get()) == [TeamLibraryUnsentChanges.refused("Huge", because: .refused)]) #expect(answer.failure != nil) } @@ -398,10 +398,10 @@ struct TeamLibraryTests { _ = await fixture.account.services.refreshEntitlement() try await waitUntil { fixture.library.writableTeams.isEmpty } - #expect(await fixture.library.unsentChanges() == ["Orders"]) + #expect((try? await fixture.library.unsentChanges().get()) == ["Orders"]) engine.failUnsentReads(with: TeamConflictFixture.failure("sync.state.io")) - #expect(await fixture.library.unsentChanges() == nil) + #expect((try? await fixture.library.unsentChanges().get()) == nil) } @Test("Sign Out deletes the account's Team Library data once signed out, through the service of that sign-in") diff --git a/apple/TableProTests/Views/Settings/AccountSettingsModelTests.swift b/apple/TableProTests/Views/Settings/AccountSettingsModelTests.swift index 1186c47015..bade74cf8d 100644 --- a/apple/TableProTests/Views/Settings/AccountSettingsModelTests.swift +++ b/apple/TableProTests/Views/Settings/AccountSettingsModelTests.swift @@ -446,6 +446,30 @@ struct AccountSettingsModelTests { #expect(fixture.account.services.isSignedIn) } + @Test("Sync data this Mac can't read offers no Upload and never says an upload failed (E2E F36)") + func unreadableSyncDataOffersNoUpload() async throws { + let engine = FakeTeamLibraryEngine() + engine.failUnsentReads(with: TeamConflictFixture.failure("sync.state.wrong_identity")) + let fixture = try await TeamLibraryFixture(engine: engine) + try await fixture.start() + let prompt = ScriptedSignOutPrompt([.discard]) + let model = AccountSettingsModel(services: fixture.account.services, teamLibrary: { fixture.library }, keys: .untouched, askSignOut: prompt.ask) + + await model.signOut() + + let asked = try #require(prompt.asked.first) + #expect(prompt.asked.count == 1) + #expect(asked.teamChanges == nil) + #expect(asked.listFailure == .stateUnreadable) + #expect(!asked.asksAboutTeamChanges) + #expect(asked.discardsSomething) + #expect(asked.message.contains(String(localized: "TablePro couldn't read this Mac's sync data for the account, so no Team Library change can be uploaded. Signing out discards any there are."))) + #expect(!asked.message.contains(String(localized: "The upload did not finish. %@").replacingOccurrences(of: " %@", with: ""))) + #expect(!asked.message.contains(String(localized: "TablePro couldn't list the Team Library changes not uploaded yet. Discarding loses any there are."))) + #expect(engine.passes == 0) + #expect(!fixture.account.services.isSignedIn) + } + @Test("A delete that fails after Sign Out says the data is still on this Mac") func failedDeleteIsReported() async throws { let engine = FakeTeamLibraryEngine() diff --git a/core/crates/ffi/src/sync/engines.rs b/core/crates/ffi/src/sync/engines.rs index 4a4ba1e1d7..b52298105e 100644 --- a/core/crates/ffi/src/sync/engines.rs +++ b/core/crates/ffi/src/sync/engines.rs @@ -287,7 +287,7 @@ impl ServiceEngine { // Called on the runtime: it opens the sign-in's state file, and the scheduler's task needs the runtime. A sign-in // to another account or server than `last` named counts what that file held unsent, for the Move my data or Start // empty prompt, and lets the file go, as iCloud does with the last account's file (0054, Another account or - // server). + // server). A new row of the same account takes over the file its last row left (0081). pub(crate) async fn start( hosts: &Hosts, link: ServiceLink, @@ -302,7 +302,13 @@ impl ServiceEngine { account: link.account, device_row: link.device_row.clone(), }; - let state = hosts.files.open(identity).await?; + let state = tablepro_sync::keys::open_service_state( + hosts.files.as_ref(), + identity, + &hosts.device_store, + &link.transport, + ) + .await?; let previous = last.filter(|previous| another_sign_in(previous, &link.origin, link.account)); let follows = match &previous { Some(previous) => { diff --git a/core/crates/ffi/src/sync/tests.rs b/core/crates/ffi/src/sync/tests.rs index a9e7cbfb47..ea08786c3e 100644 --- a/core/crates/ffi/src/sync/tests.rs +++ b/core/crates/ffi/src/sync/tests.rs @@ -1280,6 +1280,73 @@ async fn a_choice_on_a_restored_wait_keeps_the_engine_s_own_file() { assert_eq!(restored.service.service_account(), kept); } +// E2E F36: the server removed this Mac's row, the Mac signed itself out, and its next sign-in to the same account got a +// new row. The state file still named the removed row, so every call answered `sync.state.wrong_identity`. The start +// now takes the file over: the Mac syncs again and asks for approval as a new device, and the removed row's keys are +// gone. +#[tokio::test] +async fn a_sign_in_on_a_new_row_after_a_removal_starts_as_a_new_device() { + use tablepro_sync::api::device_store::DeviceItem; + + let tasks = runtime::tasks().unwrap(); + let server = FakeServer::new(); + let account = AccountId(Uuid::new_v4()); + server.add_team(TeamId(Uuid::new_v4()), &[(account, Role::Owner)]); + let dir = tempfile::tempdir().unwrap(); + let device_store = Arc::new(FakeDeviceStore::new()); + let files: Arc = Arc::new(SqliteStateFiles::at(dir.path().join("sync"), device_store.clone())); + let removed = link(&server, account); + let removed_keys = DeviceItem::DeviceKeys { + origin: removed.origin.clone(), + account, + device_row: removed.device_row.clone(), + }; + let first = open( + &tasks, + on_one_mac(&files, &device_store, removed.clone(), SyncProviderTag::Off), + ) + .await; + first_upload(&first.service).await; + let kept = first.service.service_account(); + drop(first); + server.remove_row(&removed.device_row); + let held_before = device_store.holds(&removed_keys); + + let again = open(&tasks, |parts| OpenParts { + config: SyncConfig { + service_account: kept.clone(), + ..config(SyncProviderTag::TableproSync) + }, + files: Some(Arc::clone(&files)), + device_store: Some(device_store.clone() as Arc), + link: Ok(second_link(&server, account)), + ..parts + }) + .await; + let passed = again.service.sync_now(PassReasonTag::Person).await; + let mut keys = again.service.key_state().await; + for _ in 0..100 { + if matches!(keys, Ok(KeyStateInfo::NeedsApproval { .. })) { + break; + } + tokio::time::sleep(Duration::from_millis(50)).await; + keys = again.service.key_state().await; + } + let approvals = again.service.approvals().await; + + assert!(held_before); + assert!(passed.is_ok(), "{:?}", passed.map_err(|error| code(&error).to_owned())); + assert!( + approvals.is_ok(), + "{:?}", + approvals.map_err(|error| code(&error).to_owned()) + ); + let keys = keys.map_err(|error| code(&error).to_owned()).unwrap(); + assert!(matches!(keys, KeyStateInfo::NeedsApproval { .. }), "{keys:?}"); + assert!(!device_store.holds(&removed_keys)); + assert_ne!(again.service.service_account(), kept); +} + // A sign-in to another account than the one whose file this device used last pushes nothing personal until the person // picks Move my data or Start empty; a new sign-in of the same account is no switch (core ADR 0054, Another account or // server). diff --git a/core/crates/sync/src/api/state.rs b/core/crates/sync/src/api/state.rs index 89266cde24..46fc1c33e7 100644 --- a/core/crates/sync/src/api/state.rs +++ b/core/crates/sync/src/api/state.rs @@ -7,7 +7,7 @@ use tablepro_keys::trust::{PinHow, Replaced}; use uuid::Uuid; use super::error::StateError; -use super::ids::{ChangeTag, Cursor, EpochId, FileId, IdempotencyKey, KindName, RecordKey, ScopeName}; +use super::ids::{ChangeTag, Cursor, DeviceRowId, EpochId, FileId, IdempotencyKey, KindName, RecordKey, ScopeName}; use super::scopes::{LineageEpoch, Role, ScopePolicies}; use super::transport::{DeletedReason, PulledRecord}; @@ -44,6 +44,14 @@ pub trait StateStore: Send + Sync { let _ = at_ms; Ok(()) } + + // Binds the file to another row of the account it is bound to, once its key tables are empty: the server gave this + // device a new row, and the old row's keys are gone (0081). The store then still names the old row, so the caller + // opens the file again. A store that keeps one file per identity never meets a file of another row. + async fn move_to_row(&self, device_row: DeviceRowId) -> Result<(), StateError> { + let _ = device_row; + Err(StateError::WrongIdentity) + } } // What ends the distrust an open found of the key tables (0054, A stale file). @@ -84,6 +92,15 @@ pub trait StateFiles: Send + Sync { async fn open(&self, identity: StateIdentity) -> Result, StateError>; async fn delete(&self, identity: StateIdentity) -> Result<(), StateError>; + + // The identity of the file at `identity`'s place when it is bound to another device row of the same account, as + // after the server removed this device's row and a sign-in got a new one (0081). None when there is no file, or it + // is this row's, another account's or another server's. Read before the file verifies: an open under the identity + // returned checks it. + async fn other_row(&self, identity: &StateIdentity) -> Result, StateError> { + let _ = identity; + Ok(None) + } } #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] @@ -100,7 +117,7 @@ pub enum StateIdentity { // The sign-in key, which names the server and the account file (tablepro-account). sign_in: String, account: AccountId, - device_row: super::ids::DeviceRowId, + device_row: DeviceRowId, }, ICloud { user_record_name: String, diff --git a/core/crates/sync/src/keys/account_sign_out.rs b/core/crates/sync/src/keys/account_sign_out.rs index 49de9eb8a7..756dff1bea 100644 --- a/core/crates/sync/src/keys/account_sign_out.rs +++ b/core/crates/sync/src/keys/account_sign_out.rs @@ -22,23 +22,40 @@ use crate::api::transport::{DpopKey, TransportError}; impl KeyService { pub(crate) async fn erase_on_sign_out(&self) -> Result { let _serial = self.serialized().await; - // A device with no store holds no keys, so there is nothing to revoke or erase. One whose store is only away - // this session still holds them there, and is not told it signed out. - if let Err(SyncError::DeviceStore(DeviceStoreError::Unavailable { detail })) = self.signing_out().await { - if self.holds_key_state().await? { - return Err(DeviceStoreError::Unavailable { detail }.into()); - } - return Ok(SignOutOutcome::Revoked); + match self.record_sign_out().await? { + Some(signing_out) => self.finish_signing_out(&signing_out).await, + None => Ok(SignOutOutcome::Revoked), + } + } + + // The keys of a row the server replaced, as a sign-in on the account's new row finds them (0081): Sign Out's + // erase with no revoke, since that sign-in proves only its own row. A cut-off run finishes the same way. + pub async fn erase_replaced_row(&self) -> Result<(), SyncError> { + let _serial = self.serialized().await; + match self.record_sign_out().await? { + Some(signing_out) => self.erase_signed_out(&signing_out).await, + None => Ok(()), } - let signing_out = match self.signing_out().await? { - Some(signing_out) => signing_out, - None => { + } + + // What the erase takes, written down before anything goes. None for a device with no store, which holds no keys; + // one whose store is only away this session still holds them there, and is not told they are gone. + async fn record_sign_out(&self) -> Result, SyncError> { + match self.signing_out().await { + Ok(Some(signing_out)) => Ok(Some(signing_out)), + Ok(None) => { let signing_out = self.what_sign_out_erases().await?; self.start_signing_out(&signing_out).await?; - signing_out + Ok(Some(signing_out)) + } + Err(SyncError::DeviceStore(DeviceStoreError::Unavailable { detail })) => { + if self.holds_key_state().await? { + return Err(DeviceStoreError::Unavailable { detail }.into()); + } + Ok(None) } - }; - self.finish_signing_out(&signing_out).await + Err(error) => Err(error), + } } // A Sign Out a crash cut off finishes before anything else reads the device's keys. @@ -97,6 +114,12 @@ impl KeyService { } async fn finish_signing_out(&self, signing_out: &SigningOut) -> Result { + let outcome = self.revoke_signed_out(signing_out).await?; + self.erase_signed_out(signing_out).await?; + Ok(outcome) + } + + async fn revoke_signed_out(&self, signing_out: &SigningOut) -> Result { let mut proofs: Vec = Vec::new(); let mut held = [&signing_out.keys.current, &signing_out.keys.pending] .into_iter() @@ -128,7 +151,10 @@ impl KeyService { } } } + Ok(outcome) + } + async fn erase_signed_out(&self, signing_out: &SigningOut) -> Result<(), SyncError> { for av in self.account_key_avs().await? { self.erase_account_keys(av).await?; } @@ -138,7 +164,7 @@ impl KeyService { self.clear_key_state().await?; // Last, since it holds the record of what this Sign Out erases. self.erase_device_keys().await?; - Ok(outcome) + Ok(()) } async fn holds_key_state(&self) -> Result { diff --git a/core/crates/sync/src/keys/mod.rs b/core/crates/sync/src/keys/mod.rs index 2cae95eafc..6b2ad867b4 100644 --- a/core/crates/sync/src/keys/mod.rs +++ b/core/crates/sync/src/keys/mod.rs @@ -14,6 +14,7 @@ pub mod personal; mod personal_envelopes; pub mod pins; mod pins_alerts; +mod replaced_row; mod reset; mod restore; mod rotation; @@ -50,6 +51,7 @@ pub use account::{AccountObjectsPlan, HeldDeviceKeys, KeptDevice, OwnAccount, Re // The restore tests' state in memory and the vectors' world, for the unit tests of other modules. pub use personal::{CurrentPersonal, ScopeKeyPlan}; pub use pins::{IkStanding, PinChange}; +pub use replaced_row::open_service_state; #[cfg(test)] pub(crate) use restore::tests::{fakes as test_fakes, world as test_world}; diff --git a/core/crates/sync/src/keys/replaced_row.rs b/core/crates/sync/src/keys/replaced_row.rs new file mode 100644 index 0000000000..42ff004561 --- /dev/null +++ b/core/crates/sync/src/keys/replaced_row.rs @@ -0,0 +1,55 @@ +// A sign-in that the server put on a new device row of the same account finds the state file its last row left, bound +// to that row: after a removal, a reset by another device, or a row the server dropped while signed out (0081). The +// old row's keys go as Sign Out takes them, and the file moves to the new row with its sync tables, so nothing the +// person has not sent is lost and the device joins as a new one. Each step can run again after a crash. + +use std::sync::Arc; + +use super::{KeyService, KeyServiceParts, SystemClock}; +use crate::api::device_store::HostDeviceStore; +use crate::api::error::{StateError, SyncError}; +use crate::api::state::{StateFiles, StateIdentity, StateStore}; +use crate::api::transport::ServiceTransport; +use crate::engine::{EngineHooks, Wake}; + +// The state file of a TablePro Sync sign-in. A file of another account or server at its place stays refused. +pub async fn open_service_state( + files: &dyn StateFiles, + identity: StateIdentity, + device_store: &Arc, + transport: &Arc, +) -> Result, SyncError> { + match files.open(identity.clone()).await { + Err(StateError::WrongIdentity) => {} + opened => return Ok(opened?), + } + let (Some(left), StateIdentity::Service { device_row, .. }) = (files.other_row(&identity).await?, &identity) else { + return Err(StateError::WrongIdentity.into()); + }; + let StateIdentity::Service { + origin, + account, + device_row: left_row, + .. + } = left.clone() + else { + return Err(StateError::WrongIdentity.into()); + }; + let state = files.open(left).await?; + let keys = KeyService::new(KeyServiceParts { + origin, + account, + device_row: left_row, + state: Arc::clone(&state), + device_store: Arc::clone(device_store), + // Never called: the erase sends nothing. + transport: Arc::clone(transport), + hooks: Arc::new(EngineHooks::new(Wake::new(), None)), + clock: Arc::new(SystemClock), + }); + keys.erase_replaced_row().await?; + drop(keys); + state.move_to_row(device_row.clone()).await?; + drop(state); + Ok(files.open(identity).await?) +} diff --git a/core/crates/sync/src/state/file.rs b/core/crates/sync/src/state/file.rs index f647efe384..86e03ced21 100644 --- a/core/crates/sync/src/state/file.rs +++ b/core/crates/sync/src/state/file.rs @@ -8,6 +8,7 @@ use sqlx::sqlite::{ SqliteConnectOptions, SqliteJournalMode, SqliteLockingMode, SqlitePool, SqlitePoolOptions, SqliteSynchronous, }; use sqlx::{AssertSqlSafe, ConnectOptions, Sqlite, Transaction}; +use tablepro_keys::encoding::Origin; use tablepro_storage::StoragePaths; use uuid::Uuid; @@ -16,7 +17,7 @@ use super::integrity::{self, Bound, Seal, Written}; use super::name::state_path; use crate::api::device_store::HostDeviceStore; use crate::api::error::StateError; -use crate::api::ids::FileId; +use crate::api::ids::{DeviceRowId, FileId}; use crate::api::state::{ BindingRow, Committed, KeysSettled, Opened, Provider, Row, RowKey, RowRange, StateFiles, StateIdentity, StateStore, StateTxn, Table, @@ -295,6 +296,16 @@ async fn bind(tx: &mut Transaction<'static, Sqlite>, identity: &StateIdentity) - } } +async fn open_sealed( + pool: &SqlitePool, + identity: &StateIdentity, + device_store: &Arc, +) -> Result<(Arc, Opened), StateError> { + let mut tx = pool.begin_with("BEGIN IMMEDIATE").await.map_err(sql)?; + let bound = bind(&mut tx, identity).await?; + integrity::open(tx, identity, bound, Arc::clone(device_store)).await +} + #[async_trait] impl StateFiles for SqliteStateFiles { async fn open(&self, identity: StateIdentity) -> Result, StateError> { @@ -302,9 +313,15 @@ impl StateFiles for SqliteStateFiles { let lock = take_lock(&path)?; self.close(&path).await; let pool = connect(&path).await?; - let mut tx = pool.begin_with("BEGIN IMMEDIATE").await.map_err(sql)?; - let bound = bind(&mut tx, &identity).await?; - let (seal, opened) = integrity::open(tx, &identity, bound, Arc::clone(&self.device_store)).await?; + let (seal, opened) = match open_sealed(&pool, &identity, &self.device_store).await { + Ok(sealed) => sealed, + // Closed while the lock is held, so the next open never waits on this connection's exclusive lock, as one + // after a file of another row does (0081). + Err(error) => { + pool.close().await; + return Err(error); + } + }; self.pools().insert(path, pool.clone()); Ok(Arc::new(SqliteState { identity, @@ -333,6 +350,47 @@ impl StateFiles for SqliteStateFiles { drop(lock); Ok(()) } + + async fn other_row(&self, identity: &StateIdentity) -> Result, StateError> { + let StateIdentity::Service { + origin, + sign_in, + account, + device_row, + } = identity + else { + return Ok(None); + }; + let path = self.path(identity); + // An open would make the file; this only reads one that is there. + if !std::fs::exists(&path).map_err(io)? { + return Ok(None); + } + let _lock = take_lock(&path)?; + self.close(&path).await; + let pool = connect(&path).await?; + let held = match pool.begin().await { + Ok(mut tx) => read(&mut tx, &RowKey::Binding).await, + Err(error) => Err(sql(error)), + }; + pool.close().await; + let Some(Row::Binding(binding)) = held? else { + return Ok(None); + }; + let (provider, held_origin, held_account, _) = expected_binding(identity); + let same_account = binding.provider == provider + && binding.origin.as_ref().map(Origin::as_str) == held_origin.as_deref() + && binding.account == held_account; + if !same_account || binding.device == device_row.0 { + return Ok(None); + } + Ok(Some(StateIdentity::Service { + origin: origin.clone(), + sign_in: sign_in.clone(), + account: *account, + device_row: DeviceRowId(binding.device), + })) + } } #[derive(Debug)] @@ -398,6 +456,24 @@ impl StateStore for SqliteState { .map_err(sql)?; Ok(()) } + + // Key state never crosses rows: keys belong to (origin, account, device row) (0056, Keys). + async fn move_to_row(&self, device_row: DeviceRowId) -> Result<(), StateError> { + if self.seal.provider() != Provider::Service { + return Err(StateError::WrongIdentity); + } + let mut tx = self.pool.begin_with("BEGIN IMMEDIATE").await.map_err(sql)?; + if integrity::holds_key_rows(&mut tx).await? { + return Err(StateError::WrongIdentity); + } + let Some(Row::Binding(mut binding)) = read(&mut tx, &RowKey::Binding).await? else { + return Err(StateError::Integrity); + }; + binding.device = device_row.0; + write(&mut tx, &Row::Binding(binding)).await?; + integrity::commit(&self.seal, tx, Written::default()).await?; + Ok(()) + } } struct SqliteTxn { diff --git a/core/crates/sync/src/state/integrity/mod.rs b/core/crates/sync/src/state/integrity/mod.rs index cb8246edcb..a6b7d25b52 100644 --- a/core/crates/sync/src/state/integrity/mod.rs +++ b/core/crates/sync/src/state/integrity/mod.rs @@ -227,7 +227,7 @@ async fn canonical_rows(tx: &mut Transaction<'static, Sqlite>) -> Result) -> Result { +pub(crate) async fn holds_key_rows(tx: &mut Transaction<'static, Sqlite>) -> Result { for table in Table::KEY { let statement = format!("SELECT EXISTS (SELECT 1 FROM {})", table.name()); let held: bool = sqlx::query_scalar(AssertSqlSafe(statement)) diff --git a/core/crates/sync/tests/account_keys/harness.rs b/core/crates/sync/tests/account_keys/harness.rs index 8c9bba2374..a57dd4fd77 100644 --- a/core/crates/sync/tests/account_keys/harness.rs +++ b/core/crates/sync/tests/account_keys/harness.rs @@ -165,6 +165,17 @@ impl Device { }; files.set_opened(identity.clone(), opened); let state = files.open(identity).await.unwrap(); + Self::over(server, account, row, store, state) + } + + // A device over a state file the test opened, as one on disk. + pub fn over( + server: &Arc, + account: AccountId, + row: DeviceRowId, + store: Arc, + state: Arc, + ) -> Self { let transport = Arc::new(Recorded { client: server.client(account, row.clone()), revokes: Mutex::new(Vec::new()), diff --git a/core/crates/sync/tests/account_keys/main.rs b/core/crates/sync/tests/account_keys/main.rs index 0f9e222924..c60ef19671 100644 --- a/core/crates/sync/tests/account_keys/main.rs +++ b/core/crates/sync/tests/account_keys/main.rs @@ -17,5 +17,6 @@ mod hostile; mod personal; mod pins; mod replace; +mod replaced_row; mod sign_out; mod vectors; diff --git a/core/crates/sync/tests/account_keys/replaced_row.rs b/core/crates/sync/tests/account_keys/replaced_row.rs new file mode 100644 index 0000000000..3120a48cca --- /dev/null +++ b/core/crates/sync/tests/account_keys/replaced_row.rs @@ -0,0 +1,233 @@ +// E2E F36: a Mac whose row the server removed signs itself out (F33), then signs in again to the same account on a new +// row. The state file still named the removed row, so every call answered `sync.state.wrong_identity` for good. The +// sign-in now takes the file over as a new device: the removed row's keys go as Sign Out takes them, with no revoke, +// and the file's sync rows move to the new row. + +use std::path::Path; +use std::sync::{Arc, Mutex}; + +use serde_json::json; +use tablepro_keys::encoding::{AccountId, Version}; +use tablepro_records::Kind; +use tablepro_sync::api::device_store::{DeviceItem, HostDeviceStore}; +use tablepro_sync::api::error::{StateError, SyncError}; +use tablepro_sync::api::ids::{ChangeTag, DeviceRowId, RecordKey, ScopeName}; +use tablepro_sync::api::key_flows::KeyState; +use tablepro_sync::api::state::{BaseRow, Row, RowKey, RowRange, StateFiles, StateIdentity, Table}; +use tablepro_sync::api::transport::ServiceTransport; +use tablepro_sync::keys::open_service_state; +use tablepro_sync::state::SqliteStateFiles; +use tablepro_sync_testing::{FakeDeviceStore, FakeServer}; + +use crate::harness::{CutOff, Device, new_account, origin}; + +fn identity(account: AccountId, row: &str) -> StateIdentity { + StateIdentity::Service { + origin: origin(), + sign_in: "sign-in".to_owned(), + account, + device_row: DeviceRowId(row.to_owned()), + } +} + +fn files_at(dir: &Path, store: &Arc) -> SqliteStateFiles { + SqliteStateFiles::at(dir.to_path_buf(), Arc::clone(store) as Arc) +} + +fn base() -> Row { + Row::Base(BaseRow { + key: RecordKey::new(ScopeName::Personal, Kind::Connection, "conn-1"), + tag: ChangeTag::Service("t1".to_owned()), + version: Some(1), + revision: Some(1), + epoch: None, + deleted: None, + fields: Some(json!({"name": "Prod"})), + created_ms: None, + }) +} + +async fn key_rows(device: &Device) -> usize { + let mut txn = device.txn().await; + let mut count = 0; + for table in Table::KEY { + count += txn.scan(&RowRange::Table(table)).await.unwrap().len(); + } + count +} + +fn key_items(account: AccountId, row: &str) -> [DeviceItem; 2] { + [ + DeviceItem::DeviceKeys { + origin: origin(), + account, + device_row: DeviceRowId(row.to_owned()), + }, + DeviceItem::AccountKeys { + origin: origin(), + account, + av: Version::FIRST, + }, + ] +} + +// An approved Mac on `dev_a` with a base its next pass judges the person's edits by, whose row the server removed. +async fn removed_mac( + server: &Arc, + account: AccountId, + files: &SqliteStateFiles, + store: &Arc, +) { + let state = files.open(identity(account, "dev_a")).await.unwrap(); + let mac = Device::over( + server, + account, + DeviceRowId("dev_a".to_owned()), + Arc::clone(store), + state, + ); + mac.genesis().await; + mac.put(vec![base()]).await; + server.remove_row(&mac.row); +} + +async fn signed_in_again( + server: &Arc, + account: AccountId, + files: &SqliteStateFiles, + store: &Arc, +) -> Result { + let row = DeviceRowId("dev_b".to_owned()); + let transport: Arc = Arc::new(server.client(account, row.clone())); + let device_store: Arc = Arc::clone(store) as _; + let state = open_service_state(files, identity(account, "dev_b"), &device_store, &transport).await?; + Ok(Device::over(server, account, row, Arc::clone(store), state)) +} + +#[tokio::test] +async fn a_sign_in_on_a_new_row_takes_over_the_removed_row_s_file_as_a_new_device() { + let server = FakeServer::new(); + let account = new_account(); + let dir = tempfile::tempdir().unwrap(); + let store = Arc::new(FakeDeviceStore::new()); + let files = files_at(dir.path(), &store); + removed_mac(&server, account, &files, &store).await; + let refused = files.open(identity(account, "dev_b")).await.err(); + + let mac = signed_in_again(&server, account, &files, &store).await.unwrap(); + + assert_eq!(refused, Some(StateError::WrongIdentity)); + assert_eq!(mac.state.identity(), &identity(account, "dev_b")); + for item in key_items(account, "dev_a") { + assert!(!store.holds(&item), "{item:?}"); + } + assert_eq!(key_rows(&mac).await, 0); + // What the person's unsent edits are judged by stays, so none is lost or sent again as new. + assert_eq!( + mac.get(RowKey::Base(RecordKey::new( + ScopeName::Personal, + Kind::Connection, + "conn-1" + ))) + .await, + Some(base()) + ); + let Some(Row::Scope(scope)) = mac.get(RowKey::Scope(ScopeName::Personal)).await else { + panic!("the scope row stays"); + }; + assert!(scope.cursor.is_none() && scope.key_version.is_none() && !scope.caught_up); + mac.pull().await; + assert_eq!(mac.key_state().await, KeyState::NeedsApproval { request: None }); + drop(mac); + assert_eq!( + files.open(identity(account, "dev_a")).await.err(), + Some(StateError::WrongIdentity) + ); + assert!(files.open(identity(account, "dev_b")).await.is_ok()); +} + +#[tokio::test] +async fn a_take_over_cut_off_partway_finishes_at_the_next_sign_in() { + let server = FakeServer::new(); + let account = new_account(); + let dir = tempfile::tempdir().unwrap(); + let store = Arc::new(FakeDeviceStore::new()); + let files = files_at(dir.path(), &store); + removed_mac(&server, account, &files, &store).await; + let state = files.open(identity(account, "dev_a")).await.unwrap(); + let cut_off = Device::over( + &server, + account, + DeviceRowId("dev_a".to_owned()), + Arc::clone(&store), + state, + ) + .restarted_over(Arc::new(CutOff { + store: Arc::clone(&store), + armed: Mutex::new(true), + })); + let stopped = cut_off.service.erase_replaced_row().await.unwrap_err(); + drop(cut_off); + + let mac = signed_in_again(&server, account, &files, &store).await.unwrap(); + + assert_eq!(stopped.code(), "sync.device_store.failed"); + for item in key_items(account, "dev_a") { + assert!(!store.holds(&item), "{item:?}"); + } + assert_eq!(key_rows(&mac).await, 0); + assert_eq!(mac.state.identity(), &identity(account, "dev_b")); +} + +#[tokio::test] +async fn a_replaced_row_s_keys_go_as_sign_out_takes_them_with_no_revoke() { + let server = FakeServer::new(); + let account = new_account(); + let device = Device::new(&server, account, "dev_a").await; + device.genesis().await; + server.remove_row(&device.row); + + device.service.erase_replaced_row().await.unwrap(); + + assert!(device.transport.revokes.lock().unwrap().is_empty()); + assert!(device.store.is_empty()); + assert_eq!(key_rows(&device).await, 0); +} + +#[tokio::test] +async fn a_file_keeps_its_row_while_it_holds_key_state() { + let server = FakeServer::new(); + let account = new_account(); + let dir = tempfile::tempdir().unwrap(); + let store = Arc::new(FakeDeviceStore::new()); + let files = files_at(dir.path(), &store); + removed_mac(&server, account, &files, &store).await; + let state = files.open(identity(account, "dev_a")).await.unwrap(); + + let refused = state.move_to_row(DeviceRowId("dev_b".to_owned())).await.err(); + + assert_eq!(refused, Some(StateError::WrongIdentity)); + drop(state); + assert!(files.open(identity(account, "dev_a")).await.is_ok()); +} + +#[tokio::test] +async fn only_a_file_another_row_of_the_account_left_names_that_row() { + let account = new_account(); + let dir = tempfile::tempdir().unwrap(); + let store = Arc::new(FakeDeviceStore::new()); + let files = files_at(dir.path(), &store); + + let before = files.other_row(&identity(account, "dev_b")).await.unwrap(); + let made = files.path(&identity(account, "dev_b")).exists(); + drop(files.open(identity(account, "dev_a")).await.unwrap()); + let own = files.other_row(&identity(account, "dev_a")).await.unwrap(); + let other = files.other_row(&identity(account, "dev_b")).await.unwrap(); + let another_account = files.other_row(&identity(new_account(), "dev_b")).await.unwrap(); + + assert_eq!(before, None); + assert!(!made, "a read makes no file"); + assert_eq!(own, None); + assert_eq!(other, Some(identity(account, "dev_a"))); + assert_eq!(another_account, None); +} diff --git a/core/docs/decisions/0054-one-sync-engine-in-the-core-for-tablepro-sync-and-icloud.md b/core/docs/decisions/0054-one-sync-engine-in-the-core-for-tablepro-sync-and-icloud.md index 893af880a4..a9cc4d48e6 100644 --- a/core/docs/decisions/0054-one-sync-engine-in-the-core-for-tablepro-sync-and-icloud.md +++ b/core/docs/decisions/0054-one-sync-engine-in-the-core-for-tablepro-sync-and-icloud.md @@ -1,6 +1,6 @@ # 0054: One sync engine in the core for TablePro Sync and iCloud -- **Status**: Accepted; amends 0010 and 0044; the change journal, what a store is and the restore path amended by 0060; `colorTag` and the personal wire names and values amended by 0061; the stop's cause amended by 0062; `pending_bases`, `stores` rows and the restart hold amended by 0064; refused changes, per-kind refills, `deferred`, the iCloud holds, approval digests, unknown settings categories, the DPoP key, two key table columns and the integrity readings amended by 0066; the move marker, the move row, another account, Start empty and the account choice after a recovery amended by 0073; `key_comparisons`, the device store, `secure_delete` and the table order amended by 0074; the downgrade mirror's readings and SSH route marks amended by 0075; the personal envelope adapter and when a pulled secret lands amended by 0076; the team envelope adapter amended by 0079 +- **Status**: Accepted; amends 0010 and 0044; the change journal, what a store is and the restore path amended by 0060; `colorTag` and the personal wire names and values amended by 0061; the stop's cause amended by 0062; `pending_bases`, `stores` rows and the restart hold amended by 0064; refused changes, per-kind refills, `deferred`, the iCloud holds, approval digests, unknown settings categories, the DPoP key, two key table columns and the integrity readings amended by 0066; the move marker, the move row, another account, Start empty and the account choice after a recovery amended by 0073; `key_comparisons`, the device store, `secure_delete` and the table order amended by 0074; the downgrade mirror's readings and SSH route marks amended by 0075; the personal envelope adapter and when a pulled secret lands amended by 0076; the team envelope adapter amended by 0079; a file another row of the account left amended by 0081 - **Date**: 2026-11-25 ## Context diff --git a/core/docs/decisions/0056-end-to-end-keys-per-account-and-device.md b/core/docs/decisions/0056-end-to-end-keys-per-account-and-device.md index 9628cd8209..9d9a3c54ec 100644 --- a/core/docs/decisions/0056-end-to-end-keys-per-account-and-device.md +++ b/core/docs/decisions/0056-end-to-end-keys-per-account-and-device.md @@ -1,6 +1,6 @@ # 0056: End-to-end keys: an account key pair, device key pairs, scope keys wrapped per member, the recovery key and pinned keys -- **Status**: Accepted; supersedes 0053; amends 0044 (Secrets, and its Consequences line that teammates confirm a person again after a device removal or recovery); amended by 0059 (Errors, Ed25519 validity, the HPKE buffers and one vector row); the first envelope row's destination amended by 0061; a team stop's cause and how each clears amended by 0062; team restarts and the lanes' readings amended by 0064; team envelope deletes while `rotation due` and a restart with no ring amended by 0065; replace points in pins and the trust plaintext amended by 0066; QR and word comparisons amended by 0074 +- **Status**: Accepted; supersedes 0053; amends 0044 (Secrets, and its Consequences line that teammates confirm a person again after a device removal or recovery); amended by 0059 (Errors, Ed25519 validity, the HPKE buffers and one vector row); the first envelope row's destination amended by 0061; a team stop's cause and how each clears amended by 0062; team restarts and the lanes' readings amended by 0064; team envelope deletes while `rotation due` and a restart with no ring amended by 0065; replace points in pins and the trust plaintext amended by 0066; QR and word comparisons amended by 0074; erasing a removed row's keys at the next sign-in amended by 0081 - **Date**: 2026-11-25 ## Context diff --git a/core/docs/decisions/0081-a-sign-in-on-a-new-device-row-takes-over-the-state-file-its-last-row-left.md b/core/docs/decisions/0081-a-sign-in-on-a-new-device-row-takes-over-the-state-file-its-last-row-left.md new file mode 100644 index 0000000000..f2668b39f0 --- /dev/null +++ b/core/docs/decisions/0081-a-sign-in-on-a-new-device-row-takes-over-the-state-file-its-last-row-left.md @@ -0,0 +1,30 @@ +# 0081: A sign-in on a new device row takes over the state file its last row left + +- **Status**: Accepted; amends 0054 and 0056 +- **Date**: 2026-11-29 + +## Context + +[0054](0054-one-sync-engine-in-the-core-for-tablepro-sync-and-icloud.md), The state file, names a TablePro Sync file by the sign-in key and the account, and binds it to the device row it was made for: the engine refuses it for any other. [0056](0056-end-to-end-keys-per-account-and-device.md), Keys, ties device keys to (origin, account, device row), and Erasing says a sign-out the server causes, `device_removed` included, erases nothing. + +Since E2E F33 a device told `device_removed` signs out at once. The row is gone on the server, so its next sign-in to the same account gets a new row. Its file still names the removed row, and every call answered `sync.state.wrong_identity`: Sync Now, the key screens, Team Library, and Sign Out's key erase and Team Library delete. Nothing the device or the person could do cleared it (E2E F36). The same happens after another device's reset removes the row, or after a row the server dropped while this device was signed out. + +## Decision + +- **A new row of the same account takes the file over.** When the service engine starts and the file at its place is bound to another row of the same origin and account, it: + 1. opens the file under the row it is bound to, so the MAC and anchor checks run as on any open; + 2. erases that row's keys as Sign Out does: its device keys, the account keys and reset keys the key tables name, then the key tables, with every scope's cursor cleared so each pull starts from a snapshot. It sends no revoke, since the sign-in it holds proves only the new row; + 3. binds the file to the new row in one commit, which a file that still holds key rows refuses; + 4. opens it under the new row. + + Each step can run again after a crash. Sign Out's record of what it erases is the same, so an erase cut off finishes at the next start. +- **The sync tables stay.** Bases, standing, held and deferred changes, the outbox, approvals and conflicts describe the account's records, not the row. The person's unsent edits, personal and Team Library, are judged against the same bases and go up from the new row: Team Library ones once it syncs, personal ones once the device is approved. +- **The device joins as a new one.** With its key tables empty it asks another device or the recovery key for approval, as after Sign Out (0056, Sign Out). +- **Only the account's own rows.** A file at that place bound to another provider, server or account stays refused with `sync.state.wrong_identity`. +- **The server's signal still erases nothing.** `device_removed` locks the device and signs it out, as before. The erase happens at the person's next sign-in, when the server has given this device another row, and the old row's keys can no longer serve: 0056 refuses a removed device's key device on another row. + +## Consequences + +- A Mac or Windows device stuck on `sync.state.wrong_identity` after a removal heals at its next start while signed in, with no step by the person beyond the approval. +- A server that answers `device_removed` falsely and then gives a new row can make the device erase its keys and ask for approval again, as Sign Out would. It gains nothing it could not get by refusing the device: the approval or the recovery key re-establishes the account's keys, and the approver's trust plaintext its pins (0056, Approving a device). +- Key state never crosses rows: the file moves only once its key tables are empty. diff --git a/core/docs/decisions/README.md b/core/docs/decisions/README.md index ddf1f74b28..fe11c872ac 100644 --- a/core/docs/decisions/README.md +++ b/core/docs/decisions/README.md @@ -59,9 +59,9 @@ The format, the statuses and how a later ADR changes an earlier one follow [the | [0051](0051-sync-protocol-and-record-rules.md) | Sync protocol and record rules | Accepted; the JSON depth count, the personal wire names and which settings kinds sync amended by 0061; the push-back sets, stored nulls, two server columns and key id refusals amended by 0064; restore detection, a missing identity row, the first passkey's step-up, team envelope deletes while `rotation_due` and the install audit page amended by 0065; the restore check's functions and R1's epoch amended by 0072; history tombstones, Team Library's push order and team ids in other case amended by 0075; a team envelope under its connection's conflict amended by 0080 | `sync_records` in scopes, with install-wide random epochs and a cut per scope; a write is conditional on an opaque change tag of epoch, version and random write tag, and a push names its epoch; each change answers `applied`, `conflict` or `rejected` with a code; open kinds beside reserved `key.*`, `secret_envelope`, `history_entry` and library kinds, the server reading only `kv` and the key-object fields 0056 lists and verifying their Ed25519 signatures; 1 MiB a record, pages by count and bytes, a strong ETag over the whole scopes body; DPoP on personal and history calls and on every key-object and envelope write, with a filtered view before approval; content edits revive a deletion and placement edits never do; the system identifier and timeline are checked before any connection serves, and a restore opens an epoch whose cuts tell each device which writes to refill; pull-only past grace; the library moves in behind views under N-1's lock order, and the facade lives until 2% of devices. | | [0052](0052-synced-records-have-canonical-ids.md) | Synced records have canonical ids; saved queries and folders have UUIDs and may have no connection | Accepted; credential profile name collisions and team ids in other case amended by 0075 | A wire id is compared as bytes, a UUID in it upper case as `uuidString` writes it, except the team library's client ids as stored and new ones lower case; favourite tables and databases, table folder items and settings categories take the Mac's derived ids byte for byte, `sha256-` past CloudKit's 255 UTF-16 units; an envelope's id is its parent's kind, id and secret kind, a key object's its owner and its version, recipient or step; saved queries and folders get UUID record ids beside the rowid and an optional connection, with name and keyword collisions settled the same way on every device and no referential actions; history gets a random UUIDv4 record id. | | [0053](0053-end-to-end-keys-under-the-recovery-key.md) | End-to-end keys: the identity under the recovery key, signed logs, envelopes, removal and recovery | Superseded by 0056 | Suite `tp1`: HPKE P-256 only wraps keys, AES-256-GCM under per-record HKDF subkeys of versioned account and team keys, Ed25519 JWS statements; the identity key lives only in a blob sealed under the 256-bit recovery key; identity, device and team logs are hash-chained, and every unwrapped key must match a signed `kid` or public key; devices and members join by five words behind a hash commitment; the server serves personal data only to DPoP keys in the signed device set; envelopes bind immutable ids and seal the destination inside; a lost device is removed with the recovery key; any owner or admin signs team trust; MLS does not fit a vault. | -| [0054](0054-one-sync-engine-in-the-core-for-tablepro-sync-and-icloud.md) | One sync engine in the core for TablePro Sync and iCloud | Accepted; the change journal, what a store is and the restore path amended by 0060; `colorTag` and the personal wire names and values amended by 0061; the stop's cause amended by 0062; `pending_bases`, `stores` rows and the restart hold amended by 0064; refused changes, per-kind refills, `deferred`, the iCloud holds, approval digests, unknown settings categories, the DPoP key, two key table columns and the integrity readings amended by 0066; the move marker, the move row, another account, Start empty and the account choice after a recovery amended by 0073; `key_comparisons`, the device store, `secure_delete` and the table order amended by 0074; the downgrade mirror's readings and SSH route marks amended by 0075; the personal envelope adapter and when a pulled secret lands amended by 0076; the team envelope adapter amended by 0079 | `tablepro-sync` runs TablePro Sync and iCloud as two transports under one engine, CloudKit's an async callback interface the Swift apps implement; the engine owns the record cache, dirty state as a diff against the bases, standing, held and deferred changes, the rebase and batching; one state file per provider and account; iCloud gains no record type; a move merges against the CloudKit base and carries its deletions; the Mac writes the Swift sync metadata while the previous stable runs the Swift engine; a state file is MACed and checked against an anchor in the device store that keeps its counter and its key checkpoint, and a stale one refills and rebuilds its keys on that checkpoint. | +| [0054](0054-one-sync-engine-in-the-core-for-tablepro-sync-and-icloud.md) | One sync engine in the core for TablePro Sync and iCloud | Accepted; the change journal, what a store is and the restore path amended by 0060; `colorTag` and the personal wire names and values amended by 0061; the stop's cause amended by 0062; `pending_bases`, `stores` rows and the restart hold amended by 0064; refused changes, per-kind refills, `deferred`, the iCloud holds, approval digests, unknown settings categories, the DPoP key, two key table columns and the integrity readings amended by 0066; the move marker, the move row, another account, Start empty and the account choice after a recovery amended by 0073; `key_comparisons`, the device store, `secure_delete` and the table order amended by 0074; the downgrade mirror's readings and SSH route marks amended by 0075; the personal envelope adapter and when a pulled secret lands amended by 0076; the team envelope adapter amended by 0079; a file another row of the account left amended by 0081 | `tablepro-sync` runs TablePro Sync and iCloud as two transports under one engine, CloudKit's an async callback interface the Swift apps implement; the engine owns the record cache, dirty state as a diff against the bases, standing, held and deferred changes, the rebase and batching; one state file per provider and account; iCloud gains no record type; a move merges against the CloudKit base and carries its deletions; the Mac writes the Swift sync metadata while the previous stable runs the Swift engine; a state file is MACed and checked against an anchor in the device store that keeps its counter and its key checkpoint, and a stale one refills and rebuilds its keys on that checkpoint. | | [0055](0055-managed-policies-for-the-sync-provider-and-tablepro-app-traffic.md) | Managed policies for the sync provider and tablepro.app traffic | Accepted; what `personalSync` off refuses and tombstones amended by 0051, which keeps the `key.*` kinds; CloudKit fences, forced providers, the policy gate and the arrival pass amended by 0073 | `PersonalSyncProvider` lists the personal sync providers a device may use, one entry forcing it and none leaving sync off; `AllowOtherAccountServers=false` with a company server also stops share-link reads and the AI catalog refresh; the Mac reads `UsageDataAllowed`, `PluginCatalogAllowed` and `ICloudSyncAllowed`; one key table with each type per channel, lists as an ADMX ``; a self-hosted `personalSync` switch, on by default, leaves an install serving Team Library only. | -| [0056](0056-end-to-end-keys-per-account-and-device.md) | End-to-end keys: an account key pair, device key pairs, scope keys wrapped per member, the recovery key and pinned keys | Accepted; amended by 0059 (Errors, Ed25519 validity, the HPKE buffers and one vector row); the first envelope row's destination amended by 0061; a team stop's cause and how each clears amended by 0062; team restarts and the lanes' readings amended by 0064; team envelope deletes while `rotation due` and a restart with no ring amended by 0065; replace points in pins and the trust plaintext amended by 0066; QR and word comparisons amended by 0074 | The 1Password and Bitwarden model on suite `tp1` (HPKE X25519, AES-256-GCM, Ed25519): an identity key derived from the 256-bit recovery key certifies each version of the account's X25519 and Ed25519 keys, which every approved device holds; personal, history and team keys are AES-256-GCM scope keys in HPKE wraps signed by the wrapper; a new device joins by five words behind a commitment, and the server serves personal data only to DPoP keys it certifies; removing a device needs the recovery key and rotates the account and every scope key; teammates pin identity keys on first use, compare six fingerprint words and get an alert on any unendorsed change; an owner or admin confirms each member, and only a holder of a team key's previous version signs the next; a reset waits 7 days. | +| [0056](0056-end-to-end-keys-per-account-and-device.md) | End-to-end keys: an account key pair, device key pairs, scope keys wrapped per member, the recovery key and pinned keys | Accepted; amended by 0059 (Errors, Ed25519 validity, the HPKE buffers and one vector row); the first envelope row's destination amended by 0061; a team stop's cause and how each clears amended by 0062; team restarts and the lanes' readings amended by 0064; team envelope deletes while `rotation due` and a restart with no ring amended by 0065; replace points in pins and the trust plaintext amended by 0066; QR and word comparisons amended by 0074; erasing a removed row's keys at the next sign-in amended by 0081 | The 1Password and Bitwarden model on suite `tp1` (HPKE X25519, AES-256-GCM, Ed25519): an identity key derived from the 256-bit recovery key certifies each version of the account's X25519 and Ed25519 keys, which every approved device holds; personal, history and team keys are AES-256-GCM scope keys in HPKE wraps signed by the wrapper; a new device joins by five words behind a commitment, and the server serves personal data only to DPoP keys it certifies; removing a device needs the recovery key and rotates the account and every scope key; teammates pin identity keys on first use, compare six fingerprint words and get an alert on any unendorsed change; an owner or admin confirms each member, and only a holder of a team key's previous version signs the next; a reset waits 7 days. | | [0057](0057-a-setup-guide-shows-on-an-empty-library.md) | A setup guide shows on an empty library | Accepted | Every app shows a guide while its library is read and empty, under one gate table, step order and handoff; `sources_blocking` lists other apps with an availability that can be Unreadable, a password offer, a ticked and a preselected rule shared with the Swift scanner through `source_list.json`; an import reports the ids it wrote, and one opens unless a file or a link supplied it, several are selected. | | [0058](0058-shortcut-presets-from-one-file.md) | Shortcut presets come from one file | Accepted | `core/crates/core/keymaps.json` holds a preset per import source, its actions named by the macOS `ShortcutAction` raw values and its chords in VS Code's text with `key`, `mac`, `linux` and `windows`; `tablepro_core::keymap` and the FFI's `keymap_preset` read it for a named platform; a preset row wins and the displaced command has no key, bare-key defaults stay, each app drops what its platform refuses. | | [0059](0059-key-errors-name-the-expected-signer-and-two-library-limits-are-written-down.md) | Key errors name the expected signer, and two library limits are written down | Accepted; a replace with no endorsement amended by 0064 | 0056's Errors gain `keys.random` and give a failed signature `keys.not_compared` under the compared DSK, `keys.unendorsed` under the held IK, else `keys.signature`; Ed25519 refuses the sign-bit encodings of the two x = 0 points; rustls's HPKE leaves plaintext buffers unwiped until an upstream fix ships; the encoding vector row names no server code for an encrypted plaintext. | @@ -86,3 +86,4 @@ The format, the statuses and how a later ADR changes an earlier one follow [the | [0078](0078-ssh-profile-names-settle-by-lowest-id.md) | SSH profile names settle by lowest id, as credential profile names do | Accepted; amends 0075 | A pull that brings an SSH profile of a name another holds in any case leaves the name to the lowest id, compared as bytes, and gives the others ` (2)` and on as this device's edit, through the same rule credential profiles settle by. | | [0079](0079-team-connection-secrets-go-up-sealed-with-a-publish-and-open-at-use.md) | Team connection secrets go up sealed with a publish and open at use | Accepted; amends 0054, 0066 and 0076; envelopes under a conflict and an edit's secrets amended by 0080 | A team's envelopes live sealed in `team_library.json` under an adapter that serves team scopes only; a publish seals the full set of secrets a connection signs in with for the copy's destination, keeps a copy that still opens, drops kinds left out, and reports `passwords_off`, `not_confirmed`, `rotation_due` or `passwords_role` when it seals none; a member opens them at use only for the destination the team's copy names; a `rotation_due` refusal lapses once the team is no longer due; no writer signature, as 0056 settled. | | [0080](0080-team-secrets-follow-their-connection-s-conflict-and-an-edit-names-what-it-changes.md) | Team secrets follow their connection's conflict, and an edit names only the secrets it changes | Accepted; amends 0051 and 0079 | A team connection's envelopes written here wait with its open conflict and go up after its own write is taken; a choice keeps the side's envelope that fits the settled copy, the chosen side's first. An edit of a team copy names only the secrets set or cleared; the rest keep the team's envelope, sealed again for a moved copy when it opens here for the copy's destination, else left as it is. | +| [0081](0081-a-sign-in-on-a-new-device-row-takes-over-the-state-file-its-last-row-left.md) | A sign-in on a new device row takes over the state file its last row left | Accepted; amends 0054 and 0056 | When the service engine starts on a file bound to another row of the same account, that row's keys go as Sign Out takes them, with no revoke, and the file moves to the new row with its sync tables in one commit, refused while it holds key rows; the device joins as a new one, and a file of another account or server stays refused. | From 47d0603ff2a9450c71a05a2fcde285e61beb4533 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sun, 29 Nov 2026 06:27:18 +0700 Subject: [PATCH 2/4] fix(core-sync): erase the account keys of every av up to the pin, as a repaired file names no older certificate --- core/crates/sync/src/keys/account_sign_out.rs | 14 +++++++---- .../sync/tests/account_keys/replaced_row.rs | 25 +++++++++++++++++++ ...s-over-the-state-file-its-last-row-left.md | 3 ++- 3 files changed, 36 insertions(+), 6 deletions(-) diff --git a/core/crates/sync/src/keys/account_sign_out.rs b/core/crates/sync/src/keys/account_sign_out.rs index 756dff1bea..212a0cd293 100644 --- a/core/crates/sync/src/keys/account_sign_out.rs +++ b/core/crates/sync/src/keys/account_sign_out.rs @@ -88,15 +88,19 @@ impl KeyService { Ok(SigningOut { keys, resets }) } - // The `av`s whose account keys this device may hold: 1, its own pin's, each own certificate the key tables hold, - // applied or a candidate, and the one after each, since a rotation stores its new keys before it holds its - // candidate. The key tables go only after the erasing, so a Sign Out cut off reads the same ones again. Erasing an - // item that is not there succeeds, so an `av` someone planted costs one delete, never a count up to it. + // The `av`s whose account keys this device may hold: each from 1 to its own pin's, each own certificate the key + // tables hold, applied or a candidate, and the one after each, since a rotation stores its new keys before it holds + // its candidate. Every `av` up to the pin's counts, since older keys stay while a scope key is wrapped to them and a + // file repaired from its checkpoint keeps the pin but no certificate (0081). The pin's `av` is one the device + // verified; an `av` a held object names, which someone may have planted, costs one delete, never a count up to + // it. The key tables go only after the erasing, so a Sign Out cut off reads the same ones again. async fn account_key_avs(&self) -> Result, SyncError> { let mut txn = self.begin().await?; let mut named = BTreeSet::from([Version::FIRST]); if let Some(pin) = self.pin(txn.as_mut(), self.account()).await? { - named.insert(pin.av); + for av in 1..=pin.av.get() { + named.insert(Version::new(av)?); + } } for held in self .held_objects(txn.as_mut(), ScopeName::Personal, KeyKind::Account) diff --git a/core/crates/sync/tests/account_keys/replaced_row.rs b/core/crates/sync/tests/account_keys/replaced_row.rs index 3120a48cca..22132fddfa 100644 --- a/core/crates/sync/tests/account_keys/replaced_row.rs +++ b/core/crates/sync/tests/account_keys/replaced_row.rs @@ -8,6 +8,7 @@ use std::sync::{Arc, Mutex}; use serde_json::json; use tablepro_keys::encoding::{AccountId, Version}; +use tablepro_keys::keys::AccountKeys; use tablepro_records::Kind; use tablepro_sync::api::device_store::{DeviceItem, HostDeviceStore}; use tablepro_sync::api::error::{StateError, SyncError}; @@ -194,6 +195,30 @@ async fn a_replaced_row_s_keys_go_as_sign_out_takes_them_with_no_revoke() { assert_eq!(key_rows(&device).await, 0); } +// A file repaired from its checkpoint keeps the pin but no older certificate; the keys of every `av` up to the pin's +// still go. +#[tokio::test] +async fn account_keys_of_every_av_up_to_the_pin_go_with_the_replaced_row() { + let server = FakeServer::new(); + let account = new_account(); + let device = Device::new(&server, account, "dev_a").await; + device.genesis().await; + let mut pin = device.pin(account).await.unwrap(); + pin.av = Version::new(4).unwrap(); + device.put(vec![Row::KeyPin(pin)]).await; + for av in [2, 3, 4] { + device + .service + .store_account_keys(Version::new(av).unwrap(), &AccountKeys::generate().unwrap()) + .await + .unwrap(); + } + + device.service.erase_replaced_row().await.unwrap(); + + assert!(device.store.is_empty()); +} + #[tokio::test] async fn a_file_keeps_its_row_while_it_holds_key_state() { let server = FakeServer::new(); diff --git a/core/docs/decisions/0081-a-sign-in-on-a-new-device-row-takes-over-the-state-file-its-last-row-left.md b/core/docs/decisions/0081-a-sign-in-on-a-new-device-row-takes-over-the-state-file-its-last-row-left.md index f2668b39f0..cfe3b96f7d 100644 --- a/core/docs/decisions/0081-a-sign-in-on-a-new-device-row-takes-over-the-state-file-its-last-row-left.md +++ b/core/docs/decisions/0081-a-sign-in-on-a-new-device-row-takes-over-the-state-file-its-last-row-left.md @@ -13,7 +13,7 @@ Since E2E F33 a device told `device_removed` signs out at once. The row is gone - **A new row of the same account takes the file over.** When the service engine starts and the file at its place is bound to another row of the same origin and account, it: 1. opens the file under the row it is bound to, so the MAC and anchor checks run as on any open; - 2. erases that row's keys as Sign Out does: its device keys, the account keys and reset keys the key tables name, then the key tables, with every scope's cursor cleared so each pull starts from a snapshot. It sends no revoke, since the sign-in it holds proves only the new row; + 2. erases that row's keys as Sign Out does: its device keys, the account keys of every `av` from 1 to its own pin's and of each own certificate the key tables hold, the reset keys `key_pending` names, then the key tables, with every scope's cursor cleared so each pull starts from a snapshot. It sends no revoke, since the sign-in it holds proves only the new row. Sign Out takes the same `av`s: a file repaired from its checkpoint keeps the pin but no older certificate; 3. binds the file to the new row in one commit, which a file that still holds key rows refuses; 4. opens it under the new row. @@ -28,3 +28,4 @@ Since E2E F33 a device told `device_removed` signs out at once. The row is gone - A Mac or Windows device stuck on `sync.state.wrong_identity` after a removal heals at its next start while signed in, with no step by the person beyond the approval. - A server that answers `device_removed` falsely and then gives a new row can make the device erase its keys and ask for approval again, as Sign Out would. It gains nothing it could not get by refusing the device: the approval or the recovery key re-establishes the account's keys, and the approver's trust plaintext its pins (0056, Approving a device). - Key state never crosses rows: the file moves only once its key tables are empty. +- A file put back from a copy older than its anchor is repaired from the checkpoint, which keeps no `key_pending`. Keys of a reset that row proposed then stay in the device store, as they do after Sign Out on such a file, since the device store lists no items by account. From bf4ef121d0ef35b26fcf909e30051e8dafadf7c6 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sun, 29 Nov 2026 06:54:29 +0700 Subject: [PATCH 3/4] chore(macos): catalog the Sign Out and Team Library strings for unreadable sync data --- apple/TablePro/Resources/Localizable.xcstrings | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/apple/TablePro/Resources/Localizable.xcstrings b/apple/TablePro/Resources/Localizable.xcstrings index 5aa1bd62c9..07edf940ae 100644 --- a/apple/TablePro/Resources/Localizable.xcstrings +++ b/apple/TablePro/Resources/Localizable.xcstrings @@ -207869,6 +207869,12 @@ }, "TablePro couldn't reach the team library." : { + }, + "TablePro couldn't read this Mac's sync data for the account, so no Team Library change can be uploaded. Signing out discards any there are." : { + + }, + "TablePro couldn't read this Mac's sync data for the account." : { + }, "TablePro couldn't save a token for this client to the Keychain, so the client wasn't paired. Try pairing again." : { @@ -229689,6 +229695,9 @@ }, "This Mac's keys can't be checked" : { + }, + "this Mac's sync data couldn't be read" : { + }, "This machine is not activated for this license." : { "localizations" : { From c36915d8d9bcf11691158dd41abc75114979c337 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sun, 29 Nov 2026 06:57:22 +0700 Subject: [PATCH 4/4] docs(sync): changelog fragments for the removed device's sign-in --- apple/changelog.d/4708.fixed.1.md | 1 + apple/changelog.d/4708.fixed.md | 1 + 2 files changed, 2 insertions(+) create mode 100644 apple/changelog.d/4708.fixed.1.md create mode 100644 apple/changelog.d/4708.fixed.md diff --git a/apple/changelog.d/4708.fixed.1.md b/apple/changelog.d/4708.fixed.1.md new file mode 100644 index 0000000000..3322e7850d --- /dev/null +++ b/apple/changelog.d/4708.fixed.1.md @@ -0,0 +1 @@ +Sign Out said an upload failed when it couldn't read this Mac's Team Library changes. diff --git a/apple/changelog.d/4708.fixed.md b/apple/changelog.d/4708.fixed.md new file mode 100644 index 0000000000..518107bf45 --- /dev/null +++ b/apple/changelog.d/4708.fixed.md @@ -0,0 +1 @@ +A Mac signed in again after its removal from the account could no longer sync, set up encryption or read Team Library.