Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 16 additions & 10 deletions apple/TablePro/Core/Services/TeamLibrary/TeamLibrary.swift
Original file line number Diff line number Diff line change
Expand Up @@ -336,30 +336,36 @@ 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)
} catch {
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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand All @@ -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
}
Expand All @@ -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"
}
}
Expand All @@ -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
}
}
Expand Down
9 changes: 9 additions & 0 deletions apple/TablePro/Resources/Localizable.xcstrings
Original file line number Diff line number Diff line change
Expand Up @@ -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." : {

Expand Down Expand Up @@ -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" : {
Expand Down
34 changes: 28 additions & 6 deletions apple/TablePro/Views/Settings/Account/AccountSettingsModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down Expand Up @@ -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 }
Expand All @@ -284,14 +301,19 @@ 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
}
}
}
}

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?,
Expand Down
2 changes: 2 additions & 0 deletions apple/TablePro/Views/TeamLibrary/TeamLibraryPublishing.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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.")
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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")
}
Expand Down
6 changes: 3 additions & 3 deletions apple/TableProTests/TeamLibrary/TeamLibraryTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}

Expand All @@ -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")
Expand Down
24 changes: 24 additions & 0 deletions apple/TableProTests/Views/Settings/AccountSettingsModelTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
1 change: 1 addition & 0 deletions apple/changelog.d/4708.fixed.1.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Sign Out said an upload failed when it couldn't read this Mac's Team Library changes.
1 change: 1 addition & 0 deletions apple/changelog.d/4708.fixed.md
Original file line number Diff line number Diff line change
@@ -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.
10 changes: 8 additions & 2 deletions core/crates/ffi/src/sync/engines.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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) => {
Expand Down
67 changes: 67 additions & 0 deletions core/crates/ffi/src/sync/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<dyn StateFiles> = 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<dyn tablepro_sync::api::HostDeviceStore>),
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).
Expand Down
Loading
Loading