diff --git a/apple/TablePro/Core/Services/TeamLibrary/TeamLibrary.swift b/apple/TablePro/Core/Services/TeamLibrary/TeamLibrary.swift index 34a60d037a..5022df35b3 100644 --- a/apple/TablePro/Core/Services/TeamLibrary/TeamLibrary.swift +++ b/apple/TablePro/Core/Services/TeamLibrary/TeamLibrary.swift @@ -206,28 +206,26 @@ internal final class TeamLibrary: ObservableObject { // MARK: - Publishing - // An edit of the team's copy by an owner, admin or editor, under the team's id for it. Nil secrets keep the team's - // envelopes as they are; otherwise they are the whole set, sealed again for the edited destination. + // An edit of the team's copy by an owner, admin or editor, under the team's id for it. `secretChanges` names only + // the secrets the person set, or cleared with an empty value; the team keeps every other. func publishConnectionEdit( _ edited: DatabaseConnection, of original: TeamLibraryConnection, - secrets: [ConnectionSecretItem: String]?, + secretChanges: [ConnectionSecretItem: String], to destination: TeamLibraryDestination ) async throws(TeamLibraryPublishError) -> TeamLibraryPublishResult { var record = LibraryRecordMapping.record(edited, keeping: nil) record.connection.id = original.id - let arguments = secrets.map { secrets in - ConnectionSecretItem.teamEnvelopeItems.compactMap { item -> TeamSecretArg? in - guard let kind = item.teamEnvelopeKind, let value = secrets[item], !value.isEmpty else { return nil } - return TeamSecretArg(kind: kind, value: value) - } + let changes = ConnectionSecretItem.teamEnvelopeItems.compactMap { item -> TeamSecretChangeArg? in + guard let kind = item.teamEnvelopeKind, let value = secretChanges[item] else { return nil } + return TeamSecretChangeArg(kind: kind, value: value.isEmpty ? nil : value) } return try await publish(to: destination) { engine, owner in try await engine.publishTeamConnectionEdit( expectedOwner: owner, teamId: original.teamID, connection: record, - secrets: arguments + changes: changes ) } } diff --git a/apple/TablePro/Core/Services/TeamLibrary/TeamLibraryEngine.swift b/apple/TablePro/Core/Services/TeamLibrary/TeamLibraryEngine.swift index ba7c880582..6ccafd4674 100644 --- a/apple/TablePro/Core/Services/TeamLibrary/TeamLibraryEngine.swift +++ b/apple/TablePro/Core/Services/TeamLibrary/TeamLibraryEngine.swift @@ -23,7 +23,7 @@ nonisolated protocol TeamLibraryEngine: TeamConflictEngine { expectedOwner: TeamLibraryOwnerArg, teamId: String, connection: LibraryConnectionRecord, - secrets: [TeamSecretArg]? + changes: [TeamSecretChangeArg] ) async throws -> TeamPublishInfo func teamConnectionSecrets( expectedOwner: TeamLibraryOwnerArg, diff --git a/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+TeamCopy.swift b/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+TeamCopy.swift index f284eb01ad..c10369e276 100644 --- a/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+TeamCopy.swift +++ b/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+TeamCopy.swift @@ -81,24 +81,23 @@ extension ConnectionEditorStore { let current = library.content.connection(rowID: target.original.connection.id) ?? target.original let record = enforcingInvariants(edits.applied(to: current.connection, since: since)).record let outcome: TeamLibraryPublishOutcome - switch await teamSecrets(for: record, current: current, changed: changed, library: library) { - case .unreadable: - outcome = .failed(.failed(.unavailable)) - case .secrets(let secrets): - do throws(TeamLibraryPublishError) { - outcome = .finished(try await library.publishConnectionEdit( - record, of: target.original, secrets: secrets, to: target.destination - )) - } catch { - outcome = .failed(error) - } + do throws(TeamLibraryPublishError) { + outcome = .finished(try await library.publishConnectionEdit( + record, + of: target.original, + secretChanges: teamSecretChanges(for: record, current: current, changed: changed), + to: target.destination + )) + } catch { + outcome = .failed(error) } finishTeamPublish(outcome, published: saving) } return .failure(.teamPublishInFlight) } - // What the person changed of the secrets a team envelope carries; an emptied field removes that secret. + // What the person changed of the secrets a team envelope carries; an emptied field clears that secret. A field left + // alone is not here, whether the form could fill it or not. func changedTeamSecrets(of saving: ConnectionDraft) -> [ConnectionSecretItem: String] { var changed: [ConnectionSecretItem: String] = [:] if saving.credentials.password != baseline.credentials.password { @@ -113,42 +112,32 @@ extension ConnectionEditorStore { return changed } - enum TeamCopySecrets { - // Nil keeps the team's envelopes as they are. - case secrets([ConnectionSecretItem: String]?) - // A secret changed or the connection moved, and the team's secrets could not be read to carry the rest. - case unreadable - } - - // Nil while nothing secret changed and the connection still goes where the team's secrets were sealed for. Else - // the whole set: the team's secrets as they are now with the person's changes, and a linked profile's in place of - // the form's, since the copy goes out with that profile's values. A key file's passphrase stays on this Mac. - func teamSecrets( + // The secrets the edit names, an empty value clearing one. The core keeps the team's envelope of every other secret + // and seals it again for a moved copy when it opens on this Mac, so a field the form could not fill never removes + // the team's secret. A linked profile's secrets stand in for the form's, since the copy goes out with that + // profile's values; one the profile does not hold is left as the team has it. A key file's passphrase stays on this + // Mac. + func teamSecretChanges( for record: DatabaseConnection, current: TeamLibraryConnection, - changed: [ConnectionSecretItem: String], - library: TeamLibrary - ) async -> TeamCopySecrets { + changed: [ConnectionSecretItem: String] + ) -> [ConnectionSecretItem: String] { let was = current.connection let moved = record.destination != was.destination || record.username != was.username || record.sshProfileId != was.sshProfileId || record.credentialMode != was.credentialMode - guard moved || !changed.isEmpty else { return .secrets(nil) } - guard var secrets = await library.secrets(for: current) else { - return changed.isEmpty ? .secrets(nil) : .unreadable - } - for (item, value) in changed { - secrets[item] = value.isEmpty ? nil : value - } + guard moved || !changed.isEmpty else { return [:] } + var changes = changed + let stored = { (value: String?) in value.flatMap { $0.isEmpty ? nil : $0 } } if case .profile(let profileId, _) = record.sshTunnelMode { - secrets[.sshPassword] = services.sshProfileStorage.loadSSHPassword(for: profileId) - secrets[.totpSecret] = services.sshProfileStorage.loadTOTPSecret(for: profileId) + changes[.sshPassword] = stored(services.sshProfileStorage.loadSSHPassword(for: profileId)) + changes[.totpSecret] = stored(services.sshProfileStorage.loadTOTPSecret(for: profileId)) } if let profileId = record.credentialMode.profileId { - secrets[.password] = services.credentialProfileStorage.loadPassword(for: profileId) + changes[.password] = stored(services.credentialProfileStorage.loadPassword(for: profileId)) } - return .secrets(secrets.filter { !$0.value.isEmpty }) + return changes } // Edits typed while the publish ran were not in it, so the window stays with them unsaved. diff --git a/apple/TableProTests/TeamLibrary/TeamLibraryFixture.swift b/apple/TableProTests/TeamLibrary/TeamLibraryFixture.swift index 229679c806..dc55a56036 100644 --- a/apple/TableProTests/TeamLibrary/TeamLibraryFixture.swift +++ b/apple/TableProTests/TeamLibrary/TeamLibraryFixture.swift @@ -27,7 +27,7 @@ final class FakeTeamLibraryEngine: FakeTeamConflictEngine, TeamLibraryEngine, @u private var teamReadGate: AsyncGate? private var passGate: AsyncGate? private(set) var connectionPublishes: [(team: String, connections: [LibraryConnectionRecord])] = [] - private(set) var connectionEdits: [(team: String, connection: LibraryConnectionRecord, secrets: [TeamSecretArg]?)] = [] + private(set) var connectionEdits: [(team: String, connection: LibraryConnectionRecord, changes: [TeamSecretChangeArg])] = [] private var heldSecrets: [String: [TeamSecretArg]] = [:] private var secretsFailure: CoreError? private(set) var queryPublishes: [(team: String, folders: [TeamFolderArg], queries: [TeamQueryArg])] = [] @@ -139,12 +139,12 @@ final class FakeTeamLibraryEngine: FakeTeamConflictEngine, TeamLibraryEngine, @u expectedOwner: TeamLibraryOwnerArg, teamId: String, connection: LibraryConnectionRecord, - secrets: [TeamSecretArg]? + changes: [TeamSecretChangeArg] ) async throws -> TeamPublishInfo { try check(expectedOwner) try signedIn() return try state.withLock { - connectionEdits.append((teamId, connection, secrets)) + connectionEdits.append((teamId, connection, changes)) return try publishAnswer.get() } } diff --git a/apple/TableProTests/TeamLibrary/TeamLibrarySecretsTests.swift b/apple/TableProTests/TeamLibrary/TeamLibrarySecretsTests.swift index cfa8b47428..3f60d4a28b 100644 --- a/apple/TableProTests/TeamLibrary/TeamLibrarySecretsTests.swift +++ b/apple/TableProTests/TeamLibrary/TeamLibrarySecretsTests.swift @@ -88,7 +88,7 @@ struct TeamLibrarySecretsTests { #expect(try TeamLibrary.result(of: info) == .publishedWithoutPasswords(0, .off)) } - @Test("An edit goes to its team under the team's id with the whole set of secrets, or none to keep the team's") + @Test("An edit goes to its team under the team's id naming only the secrets set or cleared, and never a key passphrase") func editPublishesUnderTheTeamsId() async throws { let engine = FakeTeamLibraryEngine(teams: [TeamLibraryFixture.acme(role: .editor, items: [ TeamLibraryFixture.connection("c1", name: "Prod") @@ -104,18 +104,18 @@ struct TeamLibrarySecretsTests { let result = try await fixture.library.publishConnectionEdit( edited, of: original, - secrets: [.password: "rotated", .sshPassword: "", .sshKeyPassphrase: "key file"], + secretChanges: [.password: "rotated", .sshPassword: "", .sshKeyPassphrase: "key file"], to: destination ) - _ = try await fixture.library.publishConnectionEdit(edited, of: original, secrets: nil, to: destination) + _ = try await fixture.library.publishConnectionEdit(edited, of: original, secretChanges: [:], to: destination) #expect(result == .published(1)) let first = try #require(engine.connectionEdits.first) #expect(first.team == TeamLibraryFixture.team) #expect(first.connection.connection.id == "c1") #expect(first.connection.connection.port == 5_433) - #expect(first.secrets?.map { "\($0.kind)=\($0.value)" } == ["password=rotated"]) - #expect(engine.connectionEdits.last.map { $0.secrets == nil } == true) + #expect(first.changes.map { "\($0.kind)=\($0.value ?? "cleared")" } == ["password=rotated", "ssh_password=cleared"]) + #expect(engine.connectionEdits.last.map { $0.changes.isEmpty } == true) } @Test("A member's edit is refused before it reaches the engine") @@ -132,7 +132,7 @@ struct TeamLibrarySecretsTests { try await fixture.library.publishConnectionEdit( original.connection, of: original, - secrets: nil, + secretChanges: [:], to: fixture.library.destination(TeamLibraryFixture.team) ) } diff --git a/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreTeamCopyTests.swift b/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreTeamCopyTests.swift index 68c4c15087..19b4aa95bb 100644 --- a/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreTeamCopyTests.swift +++ b/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreTeamCopyTests.swift @@ -42,8 +42,8 @@ struct ConnectionEditorStoreTeamCopyTests { try await waitUntil { dismissed } } - private func secrets(_ edit: (team: String, connection: LibraryConnectionRecord, secrets: [TeamSecretArg]?)?) -> [String]? { - edit?.secrets?.map { "\($0.kind)=\($0.value)" }.sorted() + private func changes(_ edit: (team: String, connection: LibraryConnectionRecord, changes: [TeamSecretChangeArg])?) -> [String]? { + edit?.changes.map { "\($0.kind)=\($0.value ?? "cleared")" }.sorted() } @Test("A team's copy opens with the password its envelopes hold, and is never one the library can delete") @@ -61,8 +61,8 @@ struct ConnectionEditorStoreTeamCopyTests { #expect(editor.storage.loadConnections().isEmpty) } - @Test("A port change publishes under the team's id with the team's secrets sealed again, and writes nothing here") - func movedEditCarriesTheTeamsSecrets() async throws { + @Test("A port change publishes under the team's id naming no secret, so the team seals its own again, and writes nothing here") + func movedEditNamesNoSecret() async throws { let (team, original) = try await teamCopy() let editor = try ConnectionEditorStoreFixture() let store = editor.makeStore(.editTeamCopy(target(original, secrets: [.password: "s3cret"], in: team)), teamLibrary: team.library) @@ -72,13 +72,13 @@ struct ConnectionEditorStoreTeamCopyTests { let edit = try #require(team.engine.connectionEdits.first) #expect(edit.connection.connection.id == "c1") #expect(edit.connection.connection.port == 5_433) - #expect(secrets(edit) == ["password=s3cret"]) + #expect(changes(edit) == []) #expect(editor.storage.loadConnections().isEmpty) #expect(editor.secretKeys(for: original.connection.id).isEmpty) #expect(!store.isPublishingTeamCopy) } - @Test("A password a teammate rotated after the form opened is the one sealed again, never the one the form read") + @Test("A password a teammate rotated after the form opened is never overwritten with the one the form read") func rotatedPasswordIsKept() async throws { let (team, original) = try await teamCopy() let editor = try ConnectionEditorStoreFixture() @@ -87,7 +87,24 @@ struct ConnectionEditorStoreTeamCopyTests { try await save(store) { $0.portText = "5433" } - #expect(secrets(team.engine.connectionEdits.first) == ["password=rotated"]) + #expect(changes(team.engine.connectionEdits.first) == []) + } + + @Test( + "A password field the form could not fill and the person left alone keeps the team's password", + arguments: [[:], nil] as [[ConnectionSecretItem: String]?] + ) + func unfilledPasswordIsKept(opened: [ConnectionSecretItem: String]?) async throws { + let (team, original) = try await teamCopy(secrets: []) + let editor = try ConnectionEditorStoreFixture() + let store = editor.makeStore(.editTeamCopy(target(original, secrets: opened, in: team)), teamLibrary: team.library) + #expect(store.draft.credentials.password.isEmpty) + + try await save(store) { $0.portText = "56432" } + + let edit = try #require(team.engine.connectionEdits.first) + #expect(edit.connection.connection.port == 56_432) + #expect(changes(edit) == []) } @Test("A typed password replaces the team's, and a cleared one removes it") @@ -107,7 +124,7 @@ struct ConnectionEditorStoreTeamCopyTests { $0.ssh.password = "" } - #expect(secrets(team.engine.connectionEdits.first) == ["password=typed"]) + #expect(changes(team.engine.connectionEdits.first) == ["password=typed", "ssh_password=cleared"]) } @Test("A name-only change leaves the team's envelopes as they are") @@ -120,7 +137,7 @@ struct ConnectionEditorStoreTeamCopyTests { let edit = try #require(team.engine.connectionEdits.first) #expect(edit.connection.connection.name == "Production") - #expect(edit.secrets == nil) + #expect(changes(edit) == []) } @Test("A team edit with key passphrases set sends no passphrase: they belong to this Mac's key files") @@ -135,26 +152,25 @@ struct ConnectionEditorStoreTeamCopyTests { try await save(store) { $0.portText = "5433" + $0.credentials.password = "typed" $0.ssh.keyPassphrase = "key file" $0.ssl.clientKeyPassphrase = "client key" } - #expect(team.engine.connectionEdits.first?.secrets?.map { $0.kind } == ["password"]) + #expect(team.engine.connectionEdits.first?.changes.map { $0.kind } == ["password"]) } - @Test("A password typed while the team's secrets cannot be read is refused, and nothing is sent") - func unreadableSecretsRefuseATypedOne() async throws { + @Test("A password typed while the team's secrets cannot be read goes up alone") + func typedPasswordGoesUpWhenTheTeamsCannotBeRead() async throws { let (team, original) = try await teamCopy() team.engine.failSecretReads(with: TeamConflictFixture.failure("sync.server")) let editor = try ConnectionEditorStoreFixture() let store = editor.makeStore(.editTeamCopy(target(original, secrets: nil, in: team)), teamLibrary: team.library) - store.update { $0.credentials.password = "typed" } - _ = store.save() + try await save(store) { $0.credentials.password = "typed" } - try await waitUntil { store.saveError != nil } - #expect(team.engine.connectionEdits.isEmpty) - #expect(!store.isPublishingTeamCopy) + #expect(changes(team.engine.connectionEdits.first) == ["password=typed"]) + #expect(store.saveError == nil) } @Test("An edit the team refuses keeps the window open and says why") diff --git a/apple/changelog.d/4706.fixed.1.md b/apple/changelog.d/4706.fixed.1.md new file mode 100644 index 0000000000..61e001dd3c --- /dev/null +++ b/apple/changelog.d/4706.fixed.1.md @@ -0,0 +1 @@ +Saving a Team Library connection whose password field was empty could delete the team's password. diff --git a/apple/changelog.d/4706.fixed.md b/apple/changelog.d/4706.fixed.md new file mode 100644 index 0000000000..69a3a6ac93 --- /dev/null +++ b/apple/changelog.d/4706.fixed.md @@ -0,0 +1 @@ +Keep Theirs on a Team Library connection conflict could leave the team's password unreadable for everyone. diff --git a/core/ARCHITECTURE.md b/core/ARCHITECTURE.md index 89132e5ecd..50aeb97d48 100644 --- a/core/ARCHITECTURE.md +++ b/core/ARCHITECTURE.md @@ -158,7 +158,7 @@ One engine in `tablepro-sync` syncs every app with TablePro Sync and the Apple a - **Adapters.** Each kind has a `RecordAdapter` over its core store, which names the store whose identity puts the kind into refill: `connections.json` for connections, groups, tags, projects and SSH and credential profiles; `saved_queries.db` for saved queries, their folders, favourites and table folders; `history.db` for history entries; `team_library.json` for Team Library and its sealed team envelopes ([0079](docs/decisions/0079-team-connection-secrets-go-up-sealed-with-a-publish-and-open-at-use.md)); the host's `HostSettings` for settings; and the device's secret store, through `DeviceSecrets`, for personal envelopes ([0076](docs/decisions/0076-personal-envelopes-go-up-from-the-device-secret-store-and-land-on-the-record-they-were-sealed-for.md)). Each store's write path tells a `StoreJournal` which records each commit wrote and deleted, and the journal asks every engine that listens for a pass ([0060](docs/decisions/0060-the-change-journal-names-the-records-each-write-changed-and-a-store-is-one-file.md)). The diff against the bases, not the journal, decides what goes up. - **The outbox.** On TablePro Sync, a scope's batch in flight keeps its idempotency key and request digest in `outbox` before it is sent. The same request within the server's retention reuses the key, so a retry after a lost answer is the same request, and the answer goes into the bases in one commit with the outbox cleared. `refused` keeps what the server refused, so a pass sends it again only once it changed ([0066](docs/decisions/0066-the-state-file-keeps-refused-changes-and-per-kind-refills-and-the-engine-rulings-are-settled.md)). - **Write reports.** A library write the engine commits reaches a host that tags `connections.json` through `peek_library_writes` and `ack_library_writes` (Bindings, above). -- **Team Library.** A team connection crosses as the Mac's bundle (`ExportableConnection`), which `adapters::library::team_bundle` and `team_connection` map to and from a saved connection for every platform; startup commands, a tunnel command and Local only never go out. Its secrets go up as team envelopes sealed under the team key when a publish names them, read from the device's secret store for a saved connection, and a member opens them at use only for the destination the team's copy names (`team_connection_secrets`, [0079](docs/decisions/0079-team-connection-secrets-go-up-sealed-with-a-publish-and-open-at-use.md)). Every Team Library call on a `SyncService` names the owner it was started for and is refused with `sync.team_library.other_owner` on another owner's engine. `Core::delete_other_team_library_data` deletes every owner's Team Library data on the device but the one it keeps. +- **Team Library.** A team connection crosses as the Mac's bundle (`ExportableConnection`), which `adapters::library::team_bundle` and `team_connection` map to and from a saved connection for every platform; startup commands, a tunnel command and Local only never go out. Its secrets go up as team envelopes sealed under the team key when a publish names them, read from the device's secret store for a saved connection, and a member opens them at use only for the destination the team's copy names (`team_connection_secrets`, [0079](docs/decisions/0079-team-connection-secrets-go-up-sealed-with-a-publish-and-open-at-use.md)). An edit of a team copy names only the secrets it changes, and a connection's envelopes written here wait with its open conflict ([0080](docs/decisions/0080-team-secrets-follow-their-connection-s-conflict-and-an-edit-names-what-it-changes.md)). Every Team Library call on a `SyncService` names the owner it was started for and is refused with `sync.team_library.other_owner` on another owner's engine. `Core::delete_other_team_library_data` deletes every owner's Team Library data on the device but the one it keeps. - **The policy gate.** `PolicyGate` in `tablepro-account` orders managed policy changes against the commits that act on them. `Account::apply_policy` applies a change inside `PolicyGate::change`, which blocks the host's calling thread until the reads in flight end. A move commit, and Team Library's publish, import and Keep Mine, hold a read from their policy check until they land ([0073](docs/decisions/0073-moves-the-account-choice-and-the-policy-gate-are-settled.md)). - **The service's lifecycle.** `Core::open_sync` builds the `SyncService` over this Core's state files and stores. It runs an iCloud engine when the app picked iCloud, and a service engine for the account's sign-in: in `Personal` mode when TablePro Sync is the personal provider and the policies allow it, else `TeamsOnly`, which still syncs the team scopes and the key objects. The service engine stays bound to the sign-in it started with. Its start takes the file lock, opens the state file, counts the last sign-in's file for the account choice, attaches Team Library, starts the scheduler, listens to the stores and runs a first pass. Dropping the service stops it, and its file lock goes once the calls in flight end. A service opened while the one before still holds the file reports `Waiting` with `sync.state.busy` and starts once the file is free; a call made meanwhile waits for it under the same sign-in. A start that fails for a reason that passes, such as a locked device store, starts again on the next call. diff --git a/core/crates/ffi/src/sync/team_library.rs b/core/crates/ffi/src/sync/team_library.rs index 952dd4dec7..1c52318359 100644 --- a/core/crates/ffi/src/sync/team_library.rs +++ b/core/crates/ffi/src/sync/team_library.rs @@ -124,6 +124,13 @@ pub struct TeamSecretArg { pub value: SecretString, } +// A secret an edit of a team copy changes, by the same names: a value sets it, None clears it. +#[derive(Clone, uniffi::Record)] +pub struct TeamSecretChangeArg { + pub kind: String, + pub value: Option, +} + #[derive(Debug, Clone, PartialEq, Eq, uniffi::Enum)] pub enum UnsentTeamEditTag { Pending, @@ -529,11 +536,23 @@ const TEAM_SECRETS: [SecretKind; 5] = [ SecretKind::SshTotpSecret, ]; -fn team_secret(arg: TeamSecretArg) -> Result { - let kind = SecretKind::parse(Kind::LibraryConnection, &arg.kind) +fn team_secret_kind(kind: &str) -> Result { + SecretKind::parse(Kind::LibraryConnection, kind) .filter(|kind| TEAM_SECRETS.contains(kind)) - .ok_or_else(|| malformed("secret kind"))?; - Ok(TeamSecret { kind, value: arg.value }) + .ok_or_else(|| malformed("secret kind")) +} + +// An empty value is no secret, so it clears as None does. +fn team_secret_edit(changes: Vec) -> Result { + let (mut set, mut cleared) = (Vec::new(), Vec::new()); + for change in changes { + let kind = team_secret_kind(&change.kind)?; + match change.value.filter(|value| !value.expose_secret().is_empty()) { + Some(value) => set.push(TeamSecret { kind, value }), + None => cleared.push(kind), + } + } + Ok(TeamSecrets::Edit { set, cleared }) } fn team_secret_arg(secret: TeamSecret) -> TeamSecretArg { @@ -920,22 +939,19 @@ impl SyncService { #[uniffi::export] impl SyncService { // An editor's edit of a team copy, which this device never saves: `connection.connection.id` is the id the team - // stores. `secrets` None leaves the team's envelopes of it as they are; Some is every secret it signs in with, each - // sealed again for the edited destination, and a kind left out loses its envelope. + // stores. `changes` names only the secrets the person set or cleared; every other keeps the team's envelope, sealed + // again for a moved copy when this device opens it for where the team's copy goes now, else left as it is. pub async fn publish_team_connection_edit( &self, expected_owner: TeamLibraryOwnerArg, team_id: String, connection: LibraryConnectionRecord, - secrets: Option>, + changes: Vec, ) -> Result { let team = team(&team_id)?; let (names, profiles) = (self.driver_names(), self.held_profiles()); let (mut connection, _) = self::connection(connection, names, &profiles)?; - connection.secrets = match secrets { - Some(secrets) => TeamSecrets::Set(secrets.into_iter().map(team_secret).collect::>()?), - None => TeamSecrets::Keep, - }; + connection.secrets = team_secret_edit(changes)?; let publish = self .on_team_library(expected_owner, move |control| async move { control.publish_team_connections(team, vec![connection]).await @@ -1477,24 +1493,64 @@ mod tests { // An edit's secrets cross by their 0056 names; a name no team envelope holds is refused, and each goes back by name. #[test] fn an_edit_s_secret_kinds_are_the_envelope_table_s_and_anything_else_is_refused() { - let arg = |kind: &str| TeamSecretArg { + let change = |kind: &str| TeamSecretChangeArg { kind: kind.to_owned(), - value: SecretString::from("x".to_owned()), + value: Some(SecretString::from("x".to_owned())), }; - let password = team_secret(arg("ssh_key_passphrase")).unwrap(); - let back = team_secret_arg(password.clone()); + let TeamSecrets::Edit { set, .. } = team_secret_edit(vec![change("ssh_key_passphrase")]).unwrap() else { + panic!("an edit"); + }; + let back = team_secret_arg(set[0].clone()); - assert_eq!(password.kind, SecretKind::SshKeyPassphrase); + assert_eq!(set[0].kind, SecretKind::SshKeyPassphrase); assert_eq!( (back.kind.as_str(), back.value.expose_secret()), ("ssh_key_passphrase", "x") ); for bad in ["ai_key.openai", "plugin.token", "token", ""] { - assert_eq!(team_secret(arg(bad)).unwrap_err().code(), "sync.team_library.malformed"); + assert_eq!( + team_secret_edit(vec![change(bad)]).unwrap_err().code(), + "sync.team_library.malformed" + ); } } + // A field the person left alone is not named, so the team's envelope stays; only a set or a cleared one changes. + #[test] + fn an_edit_names_only_what_the_person_set_or_cleared() { + let change = |kind: &str, value: Option<&str>| TeamSecretChangeArg { + kind: kind.to_owned(), + value: value.map(|value| SecretString::from(value.to_owned())), + }; + + let edit = team_secret_edit(vec![ + change("password", Some("typed")), + change("ssh_password", None), + change("ssh_totp_secret", Some("")), + ]) + .unwrap(); + let untouched = team_secret_edit(Vec::new()).unwrap(); + + assert_eq!( + edit, + TeamSecrets::Edit { + set: vec![TeamSecret { + kind: SecretKind::Password, + value: SecretString::from("typed".to_owned()), + }], + cleared: vec![SecretKind::SshPassword, SecretKind::SshTotpSecret], + } + ); + assert_eq!( + untouched, + TeamSecrets::Edit { + set: Vec::new(), + cleared: Vec::new(), + } + ); + } + #[test] fn a_publish_names_why_it_left_the_secrets_out_by_code() { let info = publish_info(TeamPublish { diff --git a/core/crates/sync/src/adapters/conflict.rs b/core/crates/sync/src/adapters/conflict.rs index 632fca6994..bc011827f3 100644 --- a/core/crates/sync/src/adapters/conflict.rs +++ b/core/crates/sync/src/adapters/conflict.rs @@ -58,6 +58,31 @@ pub fn contested(row: &ConflictRow) -> Vec { .collect() } +// The record the team holds once this device sends what a choice leaves: the chosen side in the contested members, this +// device's own changes in the others, and the team's copy for the rest. A deletion against an edit leaves the chosen +// side whole, None when the record goes. +pub fn settled(row: &ConflictRow, keep: ConflictChoice) -> Option { + let (Some(mine), Some(theirs)) = (row.mine.as_ref(), row.theirs.as_ref()) else { + return match keep { + ConflictChoice::KeepMine => row.mine.clone(), + ConflictChoice::KeepTheirs => row.theirs.clone(), + }; + }; + let base = row.base.as_ref(); + let contested = contested(row); + let mine_wins: Vec = names([base, Some(mine), Some(theirs)]) + .into_iter() + .filter(|name| { + if contested.contains(name) { + keep == ConflictChoice::KeepMine + } else { + member(Some(mine), name) != member(base, name) + } + }) + .collect(); + Some(overlay(theirs, Some(mine), &mine_wins)) +} + pub fn overlay(onto: &Value, from: Option<&Value>, names: &[String]) -> Value { let mut out = onto.clone(); let Some(members) = out.as_object_mut() else { diff --git a/core/crates/sync/src/api/team_library.rs b/core/crates/sync/src/api/team_library.rs index d94f2d174e..34ccb672a0 100644 --- a/core/crates/sync/src/api/team_library.rs +++ b/core/crates/sync/src/api/team_library.rs @@ -184,6 +184,13 @@ pub enum TeamSecrets { Keep, // Every secret the connection signs in with: each kind not named here loses its envelope. Set(Vec), + // An edit of the team's copy names only what the person changed. Every other secret keeps the team's envelope, sealed + // again for a moved copy when this device opens it for the destination the team's copy names now, else left as it + // is; one the edited copy no longer uses loses it. + Edit { + set: Vec, + cleared: Vec, + }, } #[derive(Debug, Clone, PartialEq, Eq)] diff --git a/core/crates/sync/src/keys/account_replace.rs b/core/crates/sync/src/keys/account_replace.rs index ff97d3d1bd..cc08dc29be 100644 --- a/core/crates/sync/src/keys/account_replace.rs +++ b/core/crates/sync/src/keys/account_replace.rs @@ -125,13 +125,7 @@ impl KeyService { }; let mut txn = self.begin().await?; let own = self.rotating_account(txn.as_mut()).await?; - let mut keep_ids: Vec = Vec::new(); - for key_device in keep { - if *key_device != own.device.key_device && !keep_ids.contains(key_device) { - keep_ids.push(*key_device); - } - } - keep_ids.sort(); + let keep_ids = kept_others(keep, own.device.key_device); if held.is_none() && keep_ids .iter() @@ -549,6 +543,14 @@ impl KeyService { } } +// The other devices a replace keeps, once each and in order, so a retry compares equal to what was built. +fn kept_others(keep: &[KeyDeviceId], own: KeyDeviceId) -> Vec { + let mut ids: Vec = keep.iter().copied().filter(|device| *device != own).collect(); + ids.sort(); + ids.dedup(); + ids +} + fn account_device(key_device: KeyDeviceId, this_device: bool, device: Option) -> AccountDevice { AccountDevice { key_device, diff --git a/core/crates/sync/src/service/mod.rs b/core/crates/sync/src/service/mod.rs index 2b1d444e0d..b6ae91e125 100644 --- a/core/crates/sync/src/service/mod.rs +++ b/core/crates/sync/src/service/mod.rs @@ -1446,6 +1446,9 @@ impl SyncControl for ServiceSync { }); } let mine = self.team_conflict_side(&key).await?; + if mine.is_some() { + self.team_choosing(&key, seen, keep).await?; + } if let (Some(_), ConflictChoice::KeepMine) = (&mine, keep) { let _read = self.team_keep_mine().await?; let fence = team_library::TeamCommitFence(self); diff --git a/core/crates/sync/src/service/push.rs b/core/crates/sync/src/service/push.rs index 2d915e4a8d..bfd1434cba 100644 --- a/core/crates/sync/src/service/push.rs +++ b/core/crates/sync/src/service/push.rs @@ -7,7 +7,7 @@ use std::collections::{BTreeSet, HashMap, HashSet}; use sha2::{Digest, Sha256}; use tablepro_keys::encoding::HistoryId; use tablepro_records::Kind; -use tablepro_records::record_id::parse_uuid; +use tablepro_records::record_id::{library_ids_match, parse_envelope_id, parse_uuid}; use uuid::Uuid; use super::scopes::kind_off; @@ -248,6 +248,30 @@ fn deletes_last(pending: &mut [Pending]) { pending.sort_by_key(rank); } +// A team connection's envelopes go after the connection's own write is taken: the server answers each change on its +// own, so one sent beside a write the team turns down as a conflict would leave this device's secret over the team's +// before the person chose (0080). Returns whether any waits. +fn envelopes_after_connections(pending: &mut Vec) -> bool { + let written: Vec = pending + .iter() + .filter(|pending| { + matches!(pending.op, PendingOp::Write { .. }) && pending.key.kind.known() == Some(Kind::LibraryConnection) + }) + .map(|pending| pending.key.record_id.clone()) + .collect(); + if written.is_empty() { + return false; + } + let before = pending.len(); + pending.retain(|pending| { + pending.key.kind.known() != Some(Kind::SecretEnvelope) + || !parse_envelope_id(&pending.key.record_id).is_some_and(|(parent, connection, _)| { + parent == Kind::LibraryConnection && written.iter().any(|id| library_ids_match(id, connection)) + }) + }); + pending.len() != before +} + impl ServiceSync { pub(super) async fn push_scope(&self, ctx: &mut PassCtx, info: &ScopeInfo) -> Result { let scope = info.scope; @@ -285,15 +309,19 @@ impl ServiceSync { self.reseal_unsent_envelopes(scope).await?; } let mut pending = self.pending(ctx, &row).await?; + let mut waiting = false; if matches!(scope, ScopeName::Team(_)) { + waiting = envelopes_after_connections(&mut pending); deletes_last(&mut pending); } ctx.report.queued += pending.len(); *ctx.report.queued_in.entry(scope).or_default() += pending.len(); - if pending.is_empty() { + if pending.is_empty() && !waiting { self.clear_outbox(scope).await?; } - let mut after = AfterPush::Done; + // The pull after this push shows whether the team took each connection, and holds a conflicted one's envelopes + // with it; the next round sends the rest. + let mut after = if waiting { AfterPush::Pull } else { AfterPush::Done }; let limits = ctx.body.limits; for batch in split(pending, &limits, |pending: &Pending| change_bytes(&pending.change())) { match self.send(ctx, scope, epoch, &batch).await? { @@ -632,18 +660,30 @@ impl ServiceSync { } pub(super) async fn skipped(&self, scope: ScopeName) -> Result>, SyncError> { - let mut txn = begin(&self.state).await?; let mut skip: HashMap> = HashMap::new(); - for table in [Table::Held, Table::Conflicts] { - for row in txn.scan(&RowRange::Scope(table, scope)).await? { - let key = match row { - Row::Held(row) => row.key, - Row::Conflict(row) => row.key, - _ => continue, - }; - skip.entry(key.kind).or_default().insert(key.record_id); + let mut contested = Vec::new(); + { + let mut txn = begin(&self.state).await?; + for table in [Table::Held, Table::Conflicts] { + for row in txn.scan(&RowRange::Scope(table, scope)).await? { + let key = match row { + Row::Held(row) => row.key, + Row::Conflict(row) => row.key, + _ => continue, + }; + if table == Table::Conflicts && key.kind == KindName::of(Kind::LibraryConnection) { + contested.push(key.record_id.clone()); + } + skip.entry(key.kind).or_default().insert(key.record_id); + } } } + if !contested.is_empty() { + let envelopes = self.contested_envelopes(scope, &contested).await?; + skip.entry(KindName::of(Kind::SecretEnvelope)) + .or_default() + .extend(envelopes); + } Ok(skip) } diff --git a/core/crates/sync/src/service/team_library/pass.rs b/core/crates/sync/src/service/team_library/pass.rs index 7fc5f95f56..bb4d14a67f 100644 --- a/core/crates/sync/src/service/team_library/pass.rs +++ b/core/crates/sync/src/service/team_library/pass.rs @@ -6,11 +6,12 @@ use std::collections::HashMap; use serde_json::Value; use tablepro_records::record_id::library_ids_match; -use tablepro_storage::TeamLibraryCopy; +use tablepro_storage::{TeamLibraryCopy, TeamLibraryKind}; use super::super::{PassReport, ServiceSync, Session, begin}; use super::{library_kind, team_of}; -use crate::api::control::ConflictChoice; +use crate::adapters::conflict::settled; +use crate::api::control::{ConflictChoice, conflict_digest}; use crate::api::error::SyncError; use crate::api::ids::{RecordKey, ScopeName}; use crate::api::state::{Row, RowKey}; @@ -120,6 +121,28 @@ impl ServiceSync { ) } + // A choice over a connection settles its envelopes before the conflict goes, under the same session lock, so a + // failure leaves the conflict open, still holding this device's envelopes back, and the choice can be made again. + pub(in crate::service) async fn team_choosing( + &self, + key: &RecordKey, + seen: [u8; 32], + keep: ConflictChoice, + ) -> Result<(), SyncError> { + if key.kind.known().and_then(library_kind) != Some(TeamLibraryKind::Connection) { + return Ok(()); + } + let Some(Row::Conflict(row)) = begin(&self.state).await?.get(&RowKey::Conflict(key.clone())).await? else { + return Err(SyncError::Unknown { what: "conflict" }); + }; + if conflict_digest(row.base.as_ref(), row.mine.as_ref(), row.theirs.as_ref()) != seen { + return Err(SyncError::Changed { what: "conflict" }); + } + let kept = settled(&row, keep); + self.settle_envelopes(key.scope, &key.record_id, kept.as_ref(), keep) + .await + } + // Keep Theirs turns this device's copy down, so a later publish leaves the team's alone until the copy here changes, // and a deletion the team kept is no longer this device's to make. Keep Mine undoes an earlier Keep Theirs. pub(in crate::service) async fn team_resolved( diff --git a/core/crates/sync/src/service/team_library/plan.rs b/core/crates/sync/src/service/team_library/plan.rs index b8e6ee83e5..f14a93193d 100644 --- a/core/crates/sync/src/service/team_library/plan.rs +++ b/core/crates/sync/src/service/team_library/plan.rs @@ -9,13 +9,14 @@ use std::collections::{BTreeSet, HashMap, HashSet}; use serde_json::{Map, Value}; +use tablepro_records::envelope::{SecretKind, destination}; use tablepro_records::record_id::{library_id, library_ids_match}; use tablepro_records::schema::schema; use tablepro_records::secret_key::is_secret_key; use tablepro_storage::{TeamLibraryItem, TeamLibraryKind, TeamLibraryLocal}; use uuid::Uuid; -use super::secrets::SecretTarget; +use super::secrets::{SecretEdit, SecretTarget, TEAM_SECRETS, applies}; use crate::api::state::BaseRow; use crate::api::team_library::{TeamConnection, TeamFolder, TeamItemRef, TeamQuery, TeamSecrets}; use crate::api::transport::DeletedReason; @@ -291,29 +292,54 @@ pub(super) fn connections(view: &TeamView<'_>, connections: &[TeamConnection]) - } // The connections whose secrets a publish names, under the id the team stores each, left out where `connections` leaves -// the connection itself out: an id in other case, or a copy Keep Theirs turned down. +// the connection itself out: an id in other case, or a copy Keep Theirs turned down. An edit that names no secret and +// leaves the copy going where the team's goes, using the same secrets, changes no envelope. pub(super) fn secret_targets(view: &TeamView<'_>, connections: &[TeamConnection]) -> Vec { connections .iter() .filter_map(|connection| { - let TeamSecrets::Set(secrets) = &connection.secrets else { - return None; - }; let kind = TeamLibraryKind::Connection; let id = view.stored_id(kind, connection.id); let fields = without_secret_keys(connection.settings.clone()); if view.collides(kind, &id) || view.declines(kind, &id, &fields) { return None; } + let (secrets, edit) = match &connection.secrets { + TeamSecrets::Keep => return None, + TeamSecrets::Set(secrets) => (secrets.clone(), None), + TeamSecrets::Edit { set, cleared } => { + let held = view.held(kind, &id).map(|held| held.fields.clone()); + let moved = held.as_ref().is_some_and(|held| changes_secrets(held, &fields)); + if set.is_empty() && cleared.is_empty() && !moved { + return None; + } + let edit = SecretEdit { + cleared: cleared.clone(), + held, + }; + (set.clone(), Some(edit)) + } + }; Some(SecretTarget { id, fields, - secrets: secrets.clone(), + secrets, + edit, }) }) .collect() } +// A password's destination names every member any team secret is sealed for. A secret the copy starts or stops using +// also changes its envelopes. +fn changes_secrets(held: &Value, edited: &Value) -> bool { + let to = |fields: &Value| destination(tablepro_records::Kind::LibraryConnection, &SecretKind::Password, fields); + to(held) != to(edited) + || TEAM_SECRETS + .iter() + .any(|kind| applies(kind, held) != applies(kind, edited)) +} + fn object(members: Vec<(&str, Value)>) -> Value { Value::Object( members diff --git a/core/crates/sync/src/service/team_library/secrets.rs b/core/crates/sync/src/service/team_library/secrets.rs index 2ed779d777..1bc667f301 100644 --- a/core/crates/sync/src/service/team_library/secrets.rs +++ b/core/crates/sync/src/service/team_library/secrets.rs @@ -3,7 +3,7 @@ // engine sends and pulls any record, and opened only when the app asks for them, for the destination the store's copy // names then. Nothing plaintext is written anywhere. -use std::collections::{HashMap, HashSet}; +use std::collections::{BTreeSet, HashMap, HashSet}; use secrecy::ExposeSecret; use serde_json::Value; @@ -17,6 +17,7 @@ use tablepro_storage::{TeamLibraryEnvelope, TeamLibraryKind}; use super::super::scopes::kind_off; use super::super::{ServiceSync, begin}; use crate::adapters::envelopes::team_envelope_of; +use crate::api::control::ConflictChoice; use crate::api::error::SyncError; use crate::api::ids::{KindName, ScopeName}; use crate::api::scopes::{Role, ScopeInfo}; @@ -25,11 +26,28 @@ use crate::api::team_library::{SecretsLeftOut, TeamSecret}; use crate::api::transport::RejectedCode; // A connection a publish carries secrets for: the id the team stores it under, the fields it goes up with, and every -// secret it signs in with. +// secret it signs in with, or for an edit the secrets it names. pub(super) struct SecretTarget { pub(super) id: String, pub(super) fields: Value, pub(super) secrets: Vec, + pub(super) edit: Option, +} + +// What an edit says of the secrets it does not set: the kinds it cleared, and the copy the team's library holds now, +// whose destination a kept secret must open for before it is sealed again for the edited one. +pub(super) struct SecretEdit { + pub(super) cleared: Vec, + pub(super) held: Option, +} + +// What one connection's publish writes of its envelopes, or why this device could not seal them. +enum TargetWrites { + Writes { + puts: Vec, + removes: Vec, + }, + LeftOut(SecretsLeftOut), } // What a publish writes of the team's envelopes, and why it left its connections' secrets out, when it did. @@ -50,10 +68,19 @@ impl EnvelopeWrites { } } +// The secrets a team connection's envelopes hold, as 0056 lists them. +pub(super) const TEAM_SECRETS: [SecretKind; 5] = [ + SecretKind::Password, + SecretKind::SslKeyPassphrase, + SecretKind::SshPassword, + SecretKind::SshKeyPassphrase, + SecretKind::SshTotpSecret, +]; + // Whether the copy uses the secret at all: the SSH ones only through a tunnel that is on, and the TOTP secret only when // it asks for a code. A key passphrase never: it opens a key file on the device that published, which a team copy does // not name. A driver's own fields have no store here. -fn applies(kind: &SecretKind, fields: &Value) -> bool { +pub(super) fn applies(kind: &SecretKind, fields: &Value) -> bool { let ssh = fields .get("sshConfig") .filter(|ssh| ssh.get("enabled") == Some(&Value::Bool(true))); @@ -71,12 +98,20 @@ fn applies(kind: &SecretKind, fields: &Value) -> bool { // The connection a held envelope belongs to and the secret it holds, for a team connection's envelope only. fn parent_of(envelope: &TeamLibraryEnvelope) -> Option<(&str, SecretKind)> { - match parse_envelope_id(&envelope.id) { + connection_of(&envelope.id) +} + +fn connection_of(envelope: &str) -> Option<(&str, SecretKind)> { + match parse_envelope_id(envelope) { Some((Kind::LibraryConnection, parent, kind)) => Some((parent, kind)), _ => None, } } +fn belongs_to(envelope: &str, connection: &str) -> bool { + connection_of(envelope).is_some_and(|(parent, _)| library_ids_match(parent, connection)) +} + // Why a seal was refused, as the publish reports it; anything that is not about the keys fails the publish. fn left_out(error: SyncError, role: Option) -> Result { match error { @@ -177,55 +212,129 @@ impl ServiceSync { let mut puts = Vec::new(); let mut removes = Vec::new(); for target in targets { - let theirs = of(&target.id); - let mut kept: HashSet = HashSet::new(); - for secret in target - .secrets - .iter() - .filter(|secret| applies(&secret.kind, &target.fields)) + match self + .target_writes(team, version, info.role, &target, &of(&target.id)) + .await? { - let Some(envelope) = team_envelope_of(&target.id, &secret.kind) else { - continue; - }; - let id = envelope.to_wire(); - if !kept.insert(id.clone()) { - continue; - } - let dest = destination(Kind::LibraryConnection, &secret.kind, &target.fields); - let current = match theirs.iter().find(|held| held.id == id) { - Some(held) => { - self.still_opens(team, &envelope, &held.fields, secret, &dest, version) - .await - } - None => false, - }; - if current { - continue; + TargetWrites::Writes { + puts: sealed, + removes: gone, + } => { + puts.extend(sealed); + removes.extend(gone); } - match self - .keys - .seal_team_envelope(team, envelope, secret.value.clone(), dest) - .await - { - Ok(fields) => puts.push(TeamLibraryEnvelope { id, fields }), - Err(error) => { - writes.left_out = Some(left_out(error, info.role)?); - return Ok(writes); - } + TargetWrites::LeftOut(reason) => { + writes.left_out = Some(reason); + return Ok(writes); } } - removes.extend( - theirs - .into_iter() - .filter(|held| !kept.contains(&held.id)) - .map(|held| held.id.clone()), - ); } writes.puts = puts; writes.removes.extend(removes); Ok(writes) } + // One sealed copy per secret the copy uses, each kept while it still opens as it would be written; the team's other + // envelopes of the connection go, but those an edit leaves as they are. + async fn target_writes( + &self, + team: TeamId, + version: Version, + role: Option, + target: &SecretTarget, + theirs: &[&TeamLibraryEnvelope], + ) -> Result { + let (sealing, mut kept) = self.edited_secrets(team, target, theirs).await?; + let mut puts = Vec::new(); + for secret in sealing.iter().filter(|secret| applies(&secret.kind, &target.fields)) { + let Some(envelope) = team_envelope_of(&target.id, &secret.kind) else { + continue; + }; + let id = envelope.to_wire(); + if !kept.insert(id.clone()) { + continue; + } + let dest = destination(Kind::LibraryConnection, &secret.kind, &target.fields); + let current = match theirs.iter().find(|held| held.id == id) { + Some(held) => { + self.still_opens(team, &envelope, &held.fields, secret, &dest, version) + .await + } + None => false, + }; + if current { + continue; + } + match self + .keys + .seal_team_envelope(team, envelope, secret.value.clone(), dest) + .await + { + Ok(fields) => puts.push(TeamLibraryEnvelope { id, fields }), + Err(error) => return Ok(TargetWrites::LeftOut(left_out(error, role)?)), + } + } + let removes = theirs + .iter() + .filter(|held| !kept.contains(&held.id)) + .map(|held| held.id.clone()) + .collect(); + Ok(TargetWrites::Writes { puts, removes }) + } + + // The secrets a publish seals, and the team's envelopes it leaves as they are. A publish that names every secret + // seals those. An edit seals those it set and each other the team keeps for a kind the edited copy uses, opened here + // for the destination the team's copy names now; one that does not open, or was sealed for another destination, + // stays as it is, since only the person's own clear removes a secret. + async fn edited_secrets( + &self, + team: TeamId, + target: &SecretTarget, + theirs: &[&TeamLibraryEnvelope], + ) -> Result<(Vec, HashSet), SyncError> { + let mut sealing = target.secrets.clone(); + let mut left = HashSet::new(); + let Some(edit) = &target.edit else { + return Ok((sealing, left)); + }; + for held in theirs { + let Some((_, kind)) = parent_of(held) else { + continue; + }; + if sealing.iter().any(|secret| secret.kind == kind) + || edit.cleared.contains(&kind) + || !applies(&kind, &target.fields) + { + continue; + } + self.check_stop()?; + let opened = match EnvelopeId::parse(&held.id) { + Ok(id) => self + .keys + .open_held_team_envelope(team, id, held.fields.clone()) + .await + .map_err(|error| tracing::debug!(code = error.code(), "a kept team secret did not open")) + .ok(), + Err(_) => None, + }; + let sealed_for_copy = |dest: &Value| { + edit.held + .as_ref() + .is_some_and(|copy| *dest == destination(Kind::LibraryConnection, &kind, copy)) + }; + match opened { + Some(opened) if sealed_for_copy(&opened.dest) => sealing.push(TeamSecret { + kind, + value: opened.secret, + }), + _ => { + left.insert(held.id.clone()); + } + } + } + Ok((sealing, left)) + } + // Under the publish's session lock and policy read, each write checking the sign-in just before it lands. pub(super) async fn write_envelopes(&self, scope: ScopeName, writes: &EnvelopeWrites) -> Result<(), SyncError> { let team = scope.wire(); @@ -371,16 +480,27 @@ impl ServiceSync { .map(|(_, refusal)| refusal.code)) } - // A discard puts the team's sealed copies back as the server last agreed on them. - pub(super) async fn revert_envelopes(&self, scope: ScopeName) -> Result<(), SyncError> { + // A discard puts the team's sealed copies back as the server last agreed on them, and a choice over a connection + // those it settles on the team's. + pub(super) async fn revert_envelopes( + &self, + scope: ScopeName, + only: Option<&HashSet>, + ) -> Result<(), SyncError> { + let named = |id: &str| only.is_none_or(|only| only.contains(id)); let live: HashMap = self .bases_in(scope, Kind::SecretEnvelope) .await? .into_iter() - .filter(|base| base.deleted.is_none()) + .filter(|base| base.deleted.is_none() && named(&base.key.record_id)) .filter_map(|base| base.fields.map(|fields| (base.key.record_id, fields))) .collect(); - let held = self.team_envelopes(scope).await?; + let held: Vec = self + .team_envelopes(scope) + .await? + .into_iter() + .filter(|envelope| named(&envelope.id)) + .collect(); let removes: Vec = held .iter() .filter(|envelope| !live.contains_key(&envelope.id)) @@ -411,7 +531,9 @@ impl ServiceSync { .await? .into_iter() .filter_map(|row| match row { - Row::Refused(row) if row.key.kind == KindName::of(Kind::SecretEnvelope) => { + Row::Refused(row) + if row.key.kind == KindName::of(Kind::SecretEnvelope) && named(&row.key.record_id) => + { Some(RowKey::Refused(row.key)) } _ => None, @@ -428,6 +550,102 @@ impl ServiceSync { Ok(()) } + // A choice over a connection keeps, of each of its secrets, the envelope that opens for the copy the team holds once + // the choice is sent: the chosen side's first, the other side's when only it does, as when this device's own move of + // the connection outlives Keep Theirs, else the chosen side's. This device's goes up once the conflict is gone; the + // team's is put back here. + pub(super) async fn settle_envelopes( + &self, + scope: ScopeName, + connection: &str, + kept: Option<&Value>, + keep: ConflictChoice, + ) -> Result<(), SyncError> { + let ScopeName::Team(team) = scope else { + return Ok(()); + }; + let theirs: HashMap = self + .bases_in(scope, Kind::SecretEnvelope) + .await? + .into_iter() + .filter(|base| base.deleted.is_none() && belongs_to(&base.key.record_id, connection)) + .filter_map(|base| base.fields.map(|fields| (base.key.record_id, fields))) + .collect(); + let mine: HashMap = self + .team_envelopes(scope) + .await? + .into_iter() + .filter(|envelope| belongs_to(&envelope.id, connection)) + .map(|envelope| (envelope.id, envelope.fields)) + .collect(); + let ids: BTreeSet<&String> = theirs.keys().chain(mine.keys()).collect(); + let mut reverting = HashSet::new(); + for id in ids { + let (held, team_held) = (mine.get(id), theirs.get(id)); + if held == team_held { + continue; + } + let mine_fits = self.fits(team, id, held, kept).await; + let theirs_fit = self.fits(team, id, team_held, kept).await; + let take_theirs = match keep { + ConflictChoice::KeepTheirs => theirs_fit || !mine_fits, + ConflictChoice::KeepMine => theirs_fit && !mine_fits, + }; + if take_theirs { + reverting.insert(id.clone()); + } + } + if reverting.is_empty() { + return Ok(()); + } + self.revert_envelopes(scope, Some(&reverting)).await + } + + // Whether a sealed copy opens here for the copy a choice leaves. A deletion fits nothing. + async fn fits(&self, team: TeamId, id: &str, sealed: Option<&Value>, kept: Option<&Value>) -> bool { + let (Some(sealed), Some(kept), Some((_, kind)), Ok(envelope)) = + (sealed, kept, connection_of(id), EnvelopeId::parse(id)) + else { + return false; + }; + match self.keys.open_held_team_envelope(team, envelope, sealed.clone()).await { + Ok(opened) => opened.dest == destination(Kind::LibraryConnection, &kind, kept), + Err(error) => { + tracing::debug!(code = error.code(), "a team envelope under a conflict did not open"); + false + } + } + } + + // The envelopes of the connections with an open conflict, as this device and the server last agreed on them hold + // them. Each is sealed for one side's destination, so what this device wrote of them waits with the conflict: Keep + // Mine sends it and Keep Theirs puts the team's back, and meanwhile the team keeps a password sealed for the copy it + // holds. + pub(in crate::service) async fn contested_envelopes( + &self, + scope: ScopeName, + connections: &[String], + ) -> Result, SyncError> { + let contested = |id: &str| connections.iter().any(|connection| belongs_to(id, connection)); + let mut ids: HashSet = self + .bases_in(scope, Kind::SecretEnvelope) + .await? + .into_iter() + .map(|base| base.key.record_id) + .filter(|id| contested(id)) + .collect(); + if self.team_library.attached.get().is_some() { + ids.extend( + self.team_envelopes(scope) + .await? + .into_iter() + .map(|envelope| envelope.id) + .filter(|id| contested(id)), + ); + } + Ok(ids) + } + // Each secret the team keeps for the connection that opens here, sealed for the destination the store's copy of it // names now. One sealed for another destination waits for a writer to seal it again; the app asks the person. pub(super) async fn connection_secrets( diff --git a/core/crates/sync/src/service/team_library/unsent.rs b/core/crates/sync/src/service/team_library/unsent.rs index 8387dd921f..aba039c001 100644 --- a/core/crates/sync/src/service/team_library/unsent.rs +++ b/core/crates/sync/src/service/team_library/unsent.rs @@ -201,6 +201,8 @@ impl ServiceSync { None => self.known_teams(session).await?, }; for scope in scopes { + // Before the conflicts go, which hold back this device's envelopes of their connections. + self.revert_envelopes(scope, None).await?; // The team keeps its copy of each, so none becomes this device's. let mut reverted = Vec::new(); for row in self.team_conflicts(scope).await? { @@ -210,7 +212,6 @@ impl ServiceSync { reverted.push((row.kind, row.key.record_id)); } reverted.extend(self.revert(scope).await?); - self.revert_envelopes(scope).await?; self.forget_refusals(scope).await?; self.update_local(scope, move |local| { local.imports.clear(); diff --git a/core/crates/sync/tests/core_engine/device.rs b/core/crates/sync/tests/core_engine/device.rs index 49030fd56e..152e47bb7a 100644 --- a/core/crates/sync/tests/core_engine/device.rs +++ b/core/crates/sync/tests/core_engine/device.rs @@ -1,23 +1,30 @@ // One device as the app wires it: its state file, device store, the key flows and the engine over one set of hooks. -use std::sync::Arc; +use std::sync::{Arc, Mutex}; + +use async_trait::async_trait; use secrecy::SecretString; +use tokio::sync::Notify; -use tablepro_keys::encoding::AccountId; +use tablepro_keys::encoding::{AccountId, TeamId, Version}; use tablepro_storage::{StoragePaths, TeamLibraryOwner, TeamLibraryStore}; use tablepro_sync::adapters::team_library::{TeamEnvelopeAdapter, TeamLibraryAdapter}; use tablepro_sync::api::adapter::RecordAdapter; use tablepro_sync::api::control::PassReason; use tablepro_sync::api::ids::{DeviceRowId, ScopeName}; use tablepro_sync::api::key_flows::{AccountFlows, KeyFlows, KeyHooks, KeyState}; +use tablepro_sync::api::scopes::ScopesAnswer; use tablepro_sync::api::state::{Row, RowKey, ScopeRow, StateFiles, StateIdentity, StateStore}; use tablepro_sync::api::team_library::{SignInGuard, TeamLibraryPolicy}; -use tablepro_sync::api::transport::ServiceTransport; +use tablepro_sync::api::transport::{ + DpopKey, Proof, PullRequest, PulledPage, PushAnswer, PushBatch, RowKeyDevice, ServiceTransport, Transport, + TransportError, +}; use tablepro_sync::engine::{Adapters, EngineHooks, Journal, StopSignal, SystemClock, Wake}; use tablepro_sync::keys::{Clock, KeyService, KeyServiceParts}; use tablepro_sync::service::{PassReport, ServiceParts, ServiceSync}; -use tablepro_sync_testing::{FakeDeviceStore, FakeServer, MemoryStateFiles}; +use tablepro_sync_testing::{FakeClient, FakeDeviceStore, FakeServer, MemoryStateFiles}; use super::harness::{origin, typed_back}; @@ -30,11 +37,78 @@ impl Clock for ServerClock { } } +// The device's client, which can hold its next push until the test lets it go, as when another device writes between +// this one's pull and its push. +pub struct Wire { + client: FakeClient, + held: Mutex, Arc)>>, +} + +impl Wire { + fn new(client: FakeClient) -> Self { + Self { + client, + held: Mutex::new(None), + } + } + + // The first notify says the push was reached; the push goes once the second is notified. + pub fn hold_next_push(&self) -> (Arc, Arc) { + let (reached, release) = (Arc::new(Notify::new()), Arc::new(Notify::new())); + *self.held.lock().unwrap() = Some((Arc::clone(&reached), Arc::clone(&release))); + (reached, release) + } +} + +#[async_trait] +impl Transport for Wire { + async fn pull(&self, request: PullRequest) -> Result { + self.client.pull(request).await + } + + async fn push(&self, batch: PushBatch) -> Result { + let held = self.held.lock().unwrap().take(); + if let Some((reached, release)) = held { + reached.notify_one(); + release.notified().await; + } + self.client.push(batch).await + } +} + +#[async_trait] +impl ServiceTransport for Wire { + async fn scopes(&self, if_none_match: Option, proof: Proof) -> Result { + self.client.scopes(if_none_match, proof).await + } + + async fn revoke_key_device(&self, proof: DpopKey) -> Result<(), TransportError> { + self.client.revoke_key_device(proof).await + } + + async fn report_stopped(&self, team: TeamId, version: Version, proof: DpopKey) -> Result<(), TransportError> { + self.client.report_stopped(team, version, proof).await + } + + async fn withdraw_stopped(&self, team: TeamId, proof: DpopKey) -> Result<(), TransportError> { + self.client.withdraw_stopped(team, proof).await + } + + async fn remove_device_row(&self, device: DeviceRowId, proof: DpopKey) -> Result<(), TransportError> { + self.client.remove_device_row(device, proof).await + } + + async fn rows_with_key_devices(&self) -> Result, TransportError> { + self.client.rows_with_key_devices().await + } +} + pub struct Device { pub keys: Arc, pub sync: ServiceSync, pub state: Arc, pub server: Arc, + pub wire: Arc, pub row: DeviceRowId, // The Team Library store, when the device runs Team Library. pub store: Option, @@ -89,7 +163,7 @@ impl Device { }) .await .unwrap(); - let transport = Arc::new(server.client(account, row.clone())); + let transport = Arc::new(Wire::new(server.client(account, row.clone()))); let wake = Wake::new(); let hooks = Arc::new(EngineHooks::new(wake.clone(), None)); let keys = Arc::new(KeyService::new(KeyServiceParts { @@ -108,7 +182,7 @@ impl Device { adapters.push(Arc::new(TeamEnvelopeAdapter::new(store)) as Arc); } let sync = ServiceSync::new(ServiceParts { - transport, + transport: Arc::clone(&transport) as Arc, state: Arc::clone(&state), adapters: Adapters::new(adapters), keys: Arc::clone(&keys) as Arc, @@ -129,6 +203,7 @@ impl Device { sync, state, server: Arc::clone(server), + wire: transport, row, store, } diff --git a/core/crates/sync/tests/core_engine/team_secrets.rs b/core/crates/sync/tests/core_engine/team_secrets.rs index 8dfc35f9e3..25a116548b 100644 --- a/core/crates/sync/tests/core_engine/team_secrets.rs +++ b/core/crates/sync/tests/core_engine/team_secrets.rs @@ -9,12 +9,13 @@ use serde_json::{Value, json}; use tablepro_keys::encoding::{AccountId, TeamId}; use tablepro_records::envelope::SecretKind; use tablepro_storage::TeamLibraryKind; -use tablepro_sync::api::control::SyncControl; +use tablepro_sync::api::control::{ConflictChoice, SyncControl}; use tablepro_sync::api::key_flows::TeamFlows; use tablepro_sync::api::scopes::Role; use tablepro_sync::api::team_library::{ SecretsLeftOut, TeamConnection, TeamItemRef, TeamLibraryControl, TeamSecret, TeamSecrets, }; +use tablepro_sync::api::transport::TransportError; use tablepro_sync_testing::FakeServer; use tablepro_sync_testing::service::{Policies, ScopeOwner}; use uuid::Uuid; @@ -440,3 +441,361 @@ async fn a_kind_left_out_loses_its_envelope_keep_changes_none_and_a_removal_take assert!(stored(&world, "ssh_password").is_none()); assert!(held_envelopes(&world.owner, world.team).is_empty()); } + +// The owner's publish stays on its device while the server answers nothing, as a paused sync leaves it. +async fn published_offline(device: &Device, team: TeamId, connection: TeamConnection) { + for _ in 0..2 { + device.server.fail_next(TransportError::Network { + detail: "paused".to_owned(), + }); + } + let held = device + .sync + .publish_team_connections(team, vec![connection]) + .await + .unwrap(); + assert!(held.unsent > 0, "{held:?}"); +} + +// The owner moved the port while the editor moved it elsewhere, both sealing the password for their own port. +async fn moved_on_both_sides(world: &World) { + world + .owner + .sync + .publish_team_connections(world.team, vec![with_password(5432, "s3cret")]) + .await + .unwrap(); + pulled(&world.editor).await; + published_offline(&world.owner, world.team, with_password(6000, "s3cret")).await; + world + .editor + .sync + .publish_team_connections(world.team, vec![with_password(7000, "s3cret")]) + .await + .unwrap(); + world.owner.pass().await; +} + +async fn decide(device: &Device, keep: ConflictChoice) { + let open = device.sync.conflicts().await.unwrap(); + assert_eq!(open.len(), 1, "{open:?}"); + let conflict = &open[0]; + device + .sync + .resolve_conflict(conflict.key.clone(), conflict.digest, keep) + .await + .unwrap(); + approve_all(device).await; + device.pass().await; +} + +fn port(world: &World) -> Option { + world + .server + .stored(ScopeOwner::Team(world.team), "library_connection", &connection_id()) + .and_then(|record| record.fields) + .and_then(|fields| fields.get("port").cloned()) +} + +// Ciphertext does not merge, but a team secret is sealed for its connection's destination: while the copy waits for +// Keep Mine or Keep Theirs, the team keeps the password sealed for the copy it holds, and each choice keeps the two +// together. +#[tokio::test] +async fn a_conflict_over_the_destination_keeps_the_team_s_password_until_the_choice_and_keep_theirs_keeps_theirs() { + let world = world().await; + moved_on_both_sides(&world).await; + pulled(&world.viewer).await; + let while_open = secrets(&world.viewer, world.team).await; + + decide(&world.owner, ConflictChoice::KeepTheirs).await; + pulled(&world.viewer).await; + + let expected = vec![(SecretKind::Password, "s3cret".to_owned())]; + assert_eq!(while_open, expected); + assert_eq!(port(&world), Some(json!(7000))); + assert_eq!(secrets(&world.owner, world.team).await, expected); + assert_eq!(secrets(&world.viewer, world.team).await, expected); +} + +#[tokio::test] +async fn keep_mine_over_the_destination_sends_the_password_sealed_for_mine() { + let world = world().await; + moved_on_both_sides(&world).await; + + decide(&world.owner, ConflictChoice::KeepMine).await; + pulled(&world.viewer).await; + + let expected = vec![(SecretKind::Password, "s3cret".to_owned())]; + assert_eq!(port(&world), Some(json!(6000))); + assert_eq!(secrets(&world.owner, world.team).await, expected); + assert_eq!(secrets(&world.viewer, world.team).await, expected); +} + +fn edit(fields: Value, set: Vec, cleared: Vec) -> TeamConnection { + connection(fields, TeamSecrets::Edit { set, cleared }) +} + +// The Edit form's save after a choice left the team's password sealed for another port: the field could not be filled, +// and the person never touched it, so the envelope stays for an editor who can open it to seal again. +#[tokio::test] +async fn an_edit_naming_no_secret_keeps_an_envelope_this_device_cannot_open_for_the_team_s_copy() { + let world = world().await; + world + .owner + .sync + .publish_team_connections(world.team, vec![with_password(5432, "s3cret")]) + .await + .unwrap(); + world + .owner + .sync + .publish_team_connections(world.team, vec![connection(settings(6000), TeamSecrets::Keep)]) + .await + .unwrap(); + let sealed = stored(&world, "password").unwrap(); + + let saved = world + .owner + .sync + .publish_team_connections(world.team, vec![edit(settings(56432), Vec::new(), Vec::new())]) + .await + .unwrap(); + + assert_eq!((saved.edits, saved.unsent), (1, 0), "{saved:?}"); + assert_eq!(port(&world), Some(json!(56432))); + assert_eq!(stored(&world, "password"), Some(sealed)); +} + +#[tokio::test] +async fn an_edit_that_moves_the_copy_seals_the_team_s_secrets_again_for_the_new_destination() { + let world = world().await; + let both = TeamSecrets::Set(vec![ + secret(SecretKind::Password, "s3cret"), + secret(SecretKind::SshPassword, "tunnel"), + ]); + world + .owner + .sync + .publish_team_connections(world.team, vec![connection(tunnelled(5432), both)]) + .await + .unwrap(); + pulled(&world.editor).await; + + let moved = world + .editor + .sync + .publish_team_connections(world.team, vec![edit(tunnelled(5433), Vec::new(), Vec::new())]) + .await + .unwrap(); + pulled(&world.viewer).await; + + assert_eq!((moved.unsent, moved.secrets_left_out), (0, None), "{moved:?}"); + let mut opened = secrets(&world.viewer, world.team).await; + opened.sort_by_key(|(kind, _)| kind.to_string()); + assert_eq!( + opened, + vec![ + (SecretKind::Password, "s3cret".to_owned()), + (SecretKind::SshPassword, "tunnel".to_owned()) + ] + ); +} + +#[tokio::test] +async fn an_edit_sets_what_it_names_clears_what_it_cleared_and_leaves_the_rest() { + let world = world().await; + let both = TeamSecrets::Set(vec![ + secret(SecretKind::Password, "s3cret"), + secret(SecretKind::SshPassword, "tunnel"), + ]); + world + .owner + .sync + .publish_team_connections(world.team, vec![connection(tunnelled(5432), both)]) + .await + .unwrap(); + let tunnel = stored(&world, "ssh_password").unwrap(); + + let typed = world + .owner + .sync + .publish_team_connections( + world.team, + vec![edit( + tunnelled(5432), + vec![secret(SecretKind::Password, "typed")], + Vec::new(), + )], + ) + .await + .unwrap(); + let after_typed = stored(&world, "ssh_password"); + let renamed = world + .owner + .sync + .publish_team_connections(world.team, vec![edit(tunnelled(5432), Vec::new(), Vec::new())]) + .await + .unwrap(); + let cleared = world + .owner + .sync + .publish_team_connections( + world.team, + vec![edit(tunnelled(5432), Vec::new(), vec![SecretKind::Password])], + ) + .await + .unwrap(); + + assert_eq!(typed.edits, 1, "{typed:?}"); + assert_eq!(after_typed, Some(tunnel)); + assert_eq!((renamed.edits, renamed.secrets_left_out), (0, None), "{renamed:?}"); + assert_eq!(cleared.edits, 1, "{cleared:?}"); + assert!(stored(&world, "password").is_none()); +} + +// The editor renamed the connection after the owner's last pull, so the owner's push meets a conflict over the name. The +// password the owner changed waits with that conflict instead of going up beside the copy the team turned down, and +// Keep Theirs leaves the team's. +#[tokio::test] +async fn a_password_sent_with_a_connection_the_team_turns_down_waits_with_its_conflict() { + let world = world().await; + world + .owner + .sync + .publish_team_connections(world.team, vec![with_password(5432, "s3cret")]) + .await + .unwrap(); + pulled(&world.editor).await; + let sealed = stored(&world, "password").unwrap(); + let mut mine = settings(5432); + mine["name"] = json!("Shop (owner)"); + let changed = TeamSecrets::Set(vec![secret(SecretKind::Password, "changed")]); + published_offline(&world.owner, world.team, connection(mine, changed)).await; + let mut theirs = settings(5432); + theirs["name"] = json!("Shop (editor)"); + + let (reached, release) = world.owner.wire.hold_next_push(); + let renamed_there = async { + reached.notified().await; + world + .editor + .sync + .publish_team_connections(world.team, vec![connection(theirs, TeamSecrets::Keep)]) + .await + .unwrap(); + release.notify_one(); + }; + tokio::join!(world.owner.pass(), renamed_there); + let while_open = stored(&world, "password"); + decide(&world.owner, ConflictChoice::KeepTheirs).await; + pulled(&world.viewer).await; + + let expected = vec![(SecretKind::Password, "s3cret".to_owned())]; + assert_eq!(while_open, Some(sealed.clone())); + assert_eq!(stored(&world, "password"), Some(sealed)); + assert_eq!(secrets(&world.owner, world.team).await, expected); + assert_eq!(secrets(&world.viewer, world.team).await, expected); +} + +// Turning the code off is the person's own change: the TOTP secret the copy no longer uses goes, the rest stay. +#[tokio::test] +async fn an_edit_that_stops_asking_for_a_code_drops_only_the_totp_secret() { + let world = world().await; + let with_code = |mode: &str| { + let mut fields = tunnelled(5432); + fields["sshConfig"]["totpMode"] = json!(mode); + fields + }; + let all = TeamSecrets::Set(vec![ + secret(SecretKind::Password, "s3cret"), + secret(SecretKind::SshPassword, "tunnel"), + secret(SecretKind::SshTotpSecret, "JBSWY3DP"), + ]); + world + .owner + .sync + .publish_team_connections(world.team, vec![connection(with_code("Auto Generate"), all)]) + .await + .unwrap(); + let (password, tunnel) = (stored(&world, "password"), stored(&world, "ssh_password")); + + world + .owner + .sync + .publish_team_connections(world.team, vec![edit(with_code("none"), Vec::new(), Vec::new())]) + .await + .unwrap(); + + assert!(stored(&world, "ssh_totp_secret").is_none()); + assert_eq!(stored(&world, "password"), password); + assert_eq!(stored(&world, "ssh_password"), tunnel); +} + +fn named(port: u16, name: &str) -> Value { + let mut fields = settings(port); + fields["name"] = json!(name); + fields +} + +// Only the name is contested: the owner's own move to 6000 outlives Keep Theirs, so the password it sealed for 6000 is +// the one that fits the team's copy and goes up. +#[tokio::test] +async fn keep_theirs_keeps_the_password_sealed_for_a_move_of_mine_that_outlives_it() { + let world = world().await; + world + .owner + .sync + .publish_team_connections(world.team, vec![with_password(5432, "s3cret")]) + .await + .unwrap(); + pulled(&world.editor).await; + let resealed = TeamSecrets::Set(vec![secret(SecretKind::Password, "s3cret")]); + published_offline(&world.owner, world.team, connection(named(6000, "Owner's"), resealed)).await; + world + .editor + .sync + .publish_team_connections(world.team, vec![connection(named(5432, "Editor's"), TeamSecrets::Keep)]) + .await + .unwrap(); + world.owner.pass().await; + + decide(&world.owner, ConflictChoice::KeepTheirs).await; + pulled(&world.viewer).await; + + let expected = vec![(SecretKind::Password, "s3cret".to_owned())]; + assert_eq!(port(&world), Some(json!(6000))); + assert_eq!(secrets(&world.owner, world.team).await, expected); + assert_eq!(secrets(&world.viewer, world.team).await, expected); +} + +// Only the name is contested and the editor moved the port: Keep Mine leaves the editor's port, so the team's password +// sealed for it stays and the owner's, sealed for the old port, does not go up. +#[tokio::test] +async fn keep_mine_keeps_the_team_s_password_when_only_it_fits_the_copy() { + let world = world().await; + world + .owner + .sync + .publish_team_connections(world.team, vec![with_password(5432, "s3cret")]) + .await + .unwrap(); + pulled(&world.editor).await; + let changed = TeamSecrets::Set(vec![secret(SecretKind::Password, "changed")]); + published_offline(&world.owner, world.team, connection(named(5432, "Owner's"), changed)).await; + let resealed = TeamSecrets::Set(vec![secret(SecretKind::Password, "s3cret")]); + world + .editor + .sync + .publish_team_connections(world.team, vec![connection(named(7000, "Editor's"), resealed)]) + .await + .unwrap(); + world.owner.pass().await; + + decide(&world.owner, ConflictChoice::KeepMine).await; + pulled(&world.viewer).await; + + let expected = vec![(SecretKind::Password, "s3cret".to_owned())]; + assert_eq!(port(&world), Some(json!(7000))); + assert_eq!(secrets(&world.owner, world.team).await, expected); + assert_eq!(secrets(&world.viewer, world.team).await, expected); +} diff --git a/core/docs/decisions/0051-sync-protocol-and-record-rules.md b/core/docs/decisions/0051-sync-protocol-and-record-rules.md index d62b50acb9..99b9f37886 100644 --- a/core/docs/decisions/0051-sync-protocol-and-record-rules.md +++ b/core/docs/decisions/0051-sync-protocol-and-record-rules.md @@ -1,6 +1,6 @@ # 0051: Sync protocol and record rules -- **Status**: Accepted; amends 0044, 0047, 0048 and 0055; 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 +- **Status**: Accepted; amends 0044, 0047, 0048 and 0055; 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 - **Date**: 2026-11-25 ## Context diff --git a/core/docs/decisions/0079-team-connection-secrets-go-up-sealed-with-a-publish-and-open-at-use.md b/core/docs/decisions/0079-team-connection-secrets-go-up-sealed-with-a-publish-and-open-at-use.md index 52c37ea859..0dcadeab0b 100644 --- a/core/docs/decisions/0079-team-connection-secrets-go-up-sealed-with-a-publish-and-open-at-use.md +++ b/core/docs/decisions/0079-team-connection-secrets-go-up-sealed-with-a-publish-and-open-at-use.md @@ -1,6 +1,6 @@ # 0079: Team connection secrets go up sealed with a publish and open at use -- **Status**: Accepted; amends 0054, 0066 and 0076 +- **Status**: Accepted; amends 0054, 0066 and 0076; envelopes under a conflict and an edit's secrets amended by 0080 - **Date**: 2026-11-28 ## Context diff --git a/core/docs/decisions/0080-team-secrets-follow-their-connection-s-conflict-and-an-edit-names-what-it-changes.md b/core/docs/decisions/0080-team-secrets-follow-their-connection-s-conflict-and-an-edit-names-what-it-changes.md new file mode 100644 index 0000000000..018df99649 --- /dev/null +++ b/core/docs/decisions/0080-team-secrets-follow-their-connection-s-conflict-and-an-edit-names-what-it-changes.md @@ -0,0 +1,46 @@ +# 0080: Team secrets follow their connection's conflict, and an edit names only the secrets it changes + +- **Status**: Accepted; amends 0051 and 0079 +- **Date**: 2026-11-29 + +## Context + +[0079](0079-team-connection-secrets-go-up-sealed-with-a-publish-and-open-at-use.md) seals a team connection's secrets for the destination its copy names, and [0051](0051-sync-protocol-and-record-rules.md), Conflict rules, lets the later pusher win an envelope, since ciphertext does not merge. E2E finding F35 met both at once. Two writers moved one connection to different ports while offline, each sealing the password for their own. The later one's connection waited for Keep Mine or Keep Theirs, but its envelope went up at once over the team's. The team then held one side's copy with the other side's password: no member opened it, and after Keep Theirs neither did the owner. The owner's Edit form showed an empty password field. Saving a port change from it sent an empty set of secrets, which under 0079 deleted the team's password. + +## Decision + +### An envelope waits with its connection's conflict (0051, Conflict rules) + +- While a team connection has an open conflict, the envelopes of it that this device wrote do not go up. The diff leaves them out as it leaves the connection out, so the team keeps the secrets sealed for the copy it holds. +- A connection's envelopes go up after the connection's own write is taken. The server answers each change on its own, so an envelope sent beside a write it turns down as a conflict would land before the person chose. The push sends the connection, the pull after it shows whether the team took it, and the next round sends the envelopes or holds them with the conflict. +- A choice keeps, of each secret, the envelope that opens for the copy the team holds once the choice is sent: the chosen side in the contested members, this device's own changes in the others, the team's copy for the rest. + - The chosen side's envelope stays when it fits that copy. + - Otherwise the other side's stays when only it fits, as when this device's own move of the connection outlives Keep Theirs. + - When neither fits, the chosen side's stays. +- This device's envelope goes up on the stored tag once the conflict is gone. The team's is put back as the server last agreed on it, or removed when the server holds none, as a discard does for a whole team. +- The choice settles the envelopes before the conflict goes, so a failure leaves the conflict open and the choice can be made again. A discard puts the envelopes back before its conflicts go, for the same reason. +- The later pusher still wins an envelope whose connection has no open conflict and no write waiting. + +### An edit of a team copy names what changed (0079, Publishing) + +- An editor's edit names only the secrets the person set or cleared. Every other secret keeps the team's envelope: + - When the edit moves the copy, the secret is sealed again for the new destination if this device opens it for the destination the team's copy names now. + - An envelope that does not open here, or was sealed for another destination, stays as it is. +- A secret the edited copy no longer uses loses its envelope, as in a publish that names every secret. +- An edit that names no secret, does not move the copy and uses the same secrets changes no envelope and reports no reason for leaving secrets out. +- A field the app could not fill, or one the person did not touch, is not named, so it never removes a team secret. An empty value clears the secret. +- A publish of a saved connection still names every secret it signs in with. + +## Consequences + +- Each choice leaves the copy and its password together where either side sealed one for it, and the team's password stays readable while the choice waits. +- A password changed here, with no change to where the connection goes, gives way to the team's on Keep Theirs, since the team's still fits. +- The app no longer reads the team's secrets to save an edit. A typed password goes up even when the team's secrets cannot be read. +- A publish that writes a connection and its secrets takes one more pull before the secrets go up. +- When neither side's envelope fits the settled copy, as when each side moved a different member of the destination, members are asked for the password until a writer seals it again. +- A deletion pulled against an edit here still deletes the envelopes this device left unchanged, so Keep Mine brings the connection back without them, as before this decision. + +## Alternatives considered + +- **Seal this device's waiting envelope again for whichever copy the choice keeps.** Keep Theirs would then seal this device's secret for the other writer's destination, which the person never chose. +- **Keep the full set in the edit and have the app read the team's secrets first.** A secret the app could not read still drops out of the set, which is the F35 loss. diff --git a/core/docs/decisions/README.md b/core/docs/decisions/README.md index 7faca65e5a..ddf1f74b28 100644 --- a/core/docs/decisions/README.md +++ b/core/docs/decisions/README.md @@ -56,7 +56,7 @@ The format, the statuses and how a later ADR changes an earlier one follow [the | [0048](0048-a-self-hosted-install-signs-in-through-oidc-or-saml.md) | A self-hosted install signs in through an OIDC or a SAML 2.0 IdP | Accepted; step-up amended by 0051 | Exactly one of `OIDC_ISSUER` and `SAML_IDP_ENTITY_ID`; SAML is the `saml` provider on the same sign-in path, SP-initiated through crewjam/saml v0.6.3 with an unsigned HTTP-Redirect AuthnRequest whose ID is the sign-in's nonce; a posted answer, SAML's or Apple's, is kept only with the starting browser's `__Host-` SameSite=None answer key; metadata is an installed credential; persistent NameIDs keyed by the entity ID; assertion IDs kept until expiry; admins from `IDP_ADMIN_GROUP_ID` or, without it, set by the owner in the portal; an app session's cap counts from its portal sign-in. | | [0049](0049-ai-model-catalog.md) | A provider's model list merges with one model catalog | Accepted; the catalog refresh under `AllowOtherAccountServers` amended by 0055 | The provider's list decides which models exist and the fields it states; `core/crates/ai/ai-models.json`, generated from models.dev v2, fills the rest and is refreshed keyless from updates.tablepro.app when a list loads, newer `generated` wins; one merge pinned by shared cases: lookup by id, fine-tune base or undated id, drop by protocol and hidden unknowns, live fields first, deprecated when either says so, live default else catalog's, documented order else newest first, default first, deprecated last, catalog offline when the list fails; Linux and Windows save the catalog default once for an empty model. | | [0050](0050-license-renewals-requested-by-tablepro-app-signed-by-the-operator.md) | A self-hosted license renewal is requested by tablepro.app and signed by the operator | Accepted | tablepro.app works out each bound license's file from Polar's paid state and opens a request that fixes every claim; the operator signs it on a Mac with KMS under their own AWS session over an SSH key restricted to `requests` and `record`, checking it against the license's previous file, and the host verifies the file before recording it; the renewal fetch answers only a recorded bearer; files reach the buyer's tablepro.app Billing, a link email and the fetch; a monthly file's grace is 21 days, covering Polar's retries. | -| [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 | `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. | +| [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. | @@ -84,4 +84,5 @@ The format, the statuses and how a later ADR changes an earlier one follow [the | [0076](0076-personal-envelopes-go-up-from-the-device-secret-store-and-land-on-the-record-they-were-sealed-for.md) | Personal envelopes go up from the device's secret store and land on the record they were sealed for | Accepted; amends 0054 and 0066; which path a connection's own secrets take amended by 0077; the store that serves a team's envelopes named by 0079 | `secret_envelope` in the personal scope sits over the device's secret store, the connections' secrets through the Core's and the rest through the app's `HostSyncedSecrets`; an unchanged secret reads as its base and a rotation seals it again; a pulled envelope lands only on its record as sealed for, else waits as `awaiting_store` and is offered again on each pull; a `policy` refusal lapses once its switch is on. | | [0077](0077-the-app-lands-every-synced-secret-it-names.md) | The app lands every synced secret it names | Accepted; amends 0076 | A kind the app names in `HostSyncedSecrets::kinds` goes through it, a connection's password, SSH password and key passphrase included, and the app keeps each as this device's own item; the three it leaves out go through the Core's `SecretVault`. | | [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 | 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. | +| [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. | diff --git a/windows/src/TablePro.Interop/Generated/tablepro_ffi.cs b/windows/src/TablePro.Interop/Generated/tablepro_ffi.cs index e453061745..747dcd5afc 100644 --- a/windows/src/TablePro.Interop/Generated/tablepro_ffi.cs +++ b/windows/src/TablePro.Interop/Generated/tablepro_ffi.cs @@ -6938,7 +6938,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ulong uniffi_tablepro_ffi_fn_method_syncservice_publish_team_connection_edit(ulong @ptr,RustBuffer @expectedOwner,RustBuffer @teamId,RustBuffer @connection,RustBuffer @secrets + ulong uniffi_tablepro_ffi_fn_method_syncservice_publish_team_connection_edit(ulong @ptr,RustBuffer @expectedOwner,RustBuffer @teamId,RustBuffer @connection,RustBuffer @changes ); #if NET8_0_OR_GREATER @@ -15635,8 +15635,8 @@ static void uniffiCheckApiChecksums() { } { var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_syncservice_publish_team_connection_edit(); - if (checksum != 56809) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_syncservice_publish_team_connection_edit` checksum `56809`, library returned `{checksum}`"); + if (checksum != 32412) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_syncservice_publish_team_connection_edit` checksum `32412`, library returned `{checksum}`"); } } { @@ -25254,7 +25254,7 @@ internal interface ISyncService { /// Task ImportTeamLibrary(TeamLibraryOwnerArg @expectedOwner, TeamLibraryImportArg[] @teams); /// - Task PublishTeamConnectionEdit(TeamLibraryOwnerArg @expectedOwner, string @teamId, LibraryConnectionRecord @connection, TeamSecretArg[]? @secrets); + Task PublishTeamConnectionEdit(TeamLibraryOwnerArg @expectedOwner, string @teamId, LibraryConnectionRecord @connection, TeamSecretChangeArg[] @changes); /// Task PublishTeamConnections(TeamLibraryOwnerArg @expectedOwner, string @teamId, LibraryConnectionRecord[] @connections); /// @@ -26706,11 +26706,11 @@ public async Task ImportTeamLibrary(TeamLibraryOwnerArg @expectedOwner, TeamLibr } /// - public async Task PublishTeamConnectionEdit(TeamLibraryOwnerArg @expectedOwner, string @teamId, LibraryConnectionRecord @connection, TeamSecretArg[]? @secrets) { + public async Task PublishTeamConnectionEdit(TeamLibraryOwnerArg @expectedOwner, string @teamId, LibraryConnectionRecord @connection, TeamSecretChangeArg[] @changes) { return await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_syncservice_publish_team_connection_edit(thisPtr, FfiConverterTypeTeamLibraryOwnerArg.INSTANCE.Lower(@expectedOwner), FfiConverterString.INSTANCE.Lower(@teamId), FfiConverterTypeLibraryConnectionRecord.INSTANCE.Lower(@connection), FfiConverterOptionalSequenceTypeTeamSecretArg.INSTANCE.Lower(@secrets)); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_syncservice_publish_team_connection_edit(thisPtr, FfiConverterTypeTeamLibraryOwnerArg.INSTANCE.Lower(@expectedOwner), FfiConverterString.INSTANCE.Lower(@teamId), FfiConverterTypeLibraryConnectionRecord.INSTANCE.Lower(@connection), FfiConverterSequenceTypeTeamSecretChangeArg.INSTANCE.Lower(@changes)); }), // Poll (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), @@ -38255,6 +38255,36 @@ public override void Write(TeamSecretArg value, BigEndianStream stream) { +internal record TeamSecretChangeArg ( + string Kind, + SecretString? Value +) { +} + +class FfiConverterTypeTeamSecretChangeArg: FfiConverterRustBuffer { + public static FfiConverterTypeTeamSecretChangeArg INSTANCE = new FfiConverterTypeTeamSecretChangeArg(); + + public override TeamSecretChangeArg Read(BigEndianStream stream) { + return new TeamSecretChangeArg( + Kind: FfiConverterString.INSTANCE.Read(stream), + Value: FfiConverterOptionalTypeSecretString.INSTANCE.Read(stream) + ); + } + + public override int AllocationSize(TeamSecretChangeArg value) { + return 0 + + FfiConverterString.INSTANCE.AllocationSize(value.Kind) + + FfiConverterOptionalTypeSecretString.INSTANCE.AllocationSize(value.Value); + } + + public override void Write(TeamSecretChangeArg value, BigEndianStream stream) { + FfiConverterString.INSTANCE.Write(value.Kind, stream); + FfiConverterOptionalTypeSecretString.INSTANCE.Write(value.Value, stream); + } +} + + + internal record TlsSettings ( TlsModeTag Mode, string? CaFile, @@ -54429,37 +54459,6 @@ public override void Write(string[]? value, BigEndianStream stream) { -class FfiConverterOptionalSequenceTypeTeamSecretArg: FfiConverterRustBuffer { - public static FfiConverterOptionalSequenceTypeTeamSecretArg INSTANCE = new FfiConverterOptionalSequenceTypeTeamSecretArg(); - - public override TeamSecretArg[]? Read(BigEndianStream stream) { - if (stream.ReadByte() == 0) { - return null; - } - return FfiConverterSequenceTypeTeamSecretArg.INSTANCE.Read(stream); - } - - public override int AllocationSize(TeamSecretArg[]? value) { - if (value == null) { - return 1; - } else { - return 1 + FfiConverterSequenceTypeTeamSecretArg.INSTANCE.AllocationSize((TeamSecretArg[])value); - } - } - - public override void Write(TeamSecretArg[]? value, BigEndianStream stream) { - if (value == null) { - stream.WriteByte(0); - } else { - stream.WriteByte(1); - FfiConverterSequenceTypeTeamSecretArg.INSTANCE.Write((TeamSecretArg[])value, stream); - } - } -} - - - - class FfiConverterOptionalSequenceTypeHistorySourceTag: FfiConverterRustBuffer { public static FfiConverterOptionalSequenceTypeHistorySourceTag INSTANCE = new FfiConverterOptionalSequenceTypeHistorySourceTag(); @@ -59889,6 +59888,52 @@ public override void Write(TeamSecretArg[] value, BigEndianStream stream) { +class FfiConverterSequenceTypeTeamSecretChangeArg: FfiConverterRustBuffer { + public static FfiConverterSequenceTypeTeamSecretChangeArg INSTANCE = new FfiConverterSequenceTypeTeamSecretChangeArg(); + + public override TeamSecretChangeArg[] Read(BigEndianStream stream) { + var length = stream.ReadInt(); + if (length == 0) { + return []; + } + + var result = new TeamSecretChangeArg[length]; + var readFn = FfiConverterTypeTeamSecretChangeArg.INSTANCE.Read; + for (int i = 0; i < length; i++) { + result[i] = readFn(stream); + } + return result; + } + + public override int AllocationSize(TeamSecretChangeArg[] value) { + var sizeForLength = 4; + + // details/1-empty-list-as-default-method-parameter.md + if (value == null) { + return sizeForLength; + } + + var allocationSizeFn = FfiConverterTypeTeamSecretChangeArg.INSTANCE.AllocationSize; + var sizeForItems = value.Sum(item => allocationSizeFn(item)); + return sizeForLength + sizeForItems; + } + + public override void Write(TeamSecretChangeArg[] value, BigEndianStream stream) { + // details/1-empty-list-as-default-method-parameter.md + if (value == null) { + stream.WriteInt(0); + return; + } + + stream.WriteInt(value.Length); + var writerFn = FfiConverterTypeTeamSecretChangeArg.INSTANCE.Write; + value.ForEach(item => writerFn(item, stream)); + } +} + + + + class FfiConverterSequenceTypeUnsentTeamEditInfo: FfiConverterRustBuffer { public static FfiConverterSequenceTypeUnsentTeamEditInfo INSTANCE = new FfiConverterSequenceTypeUnsentTeamEditInfo();