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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 7 additions & 9 deletions apple/TablePro/Core/Services/TeamLibrary/TeamLibrary.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
)
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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.
Expand Down
6 changes: 3 additions & 3 deletions apple/TableProTests/TeamLibrary/TeamLibraryFixture.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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])] = []
Expand Down Expand Up @@ -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()
}
}
Expand Down
12 changes: 6 additions & 6 deletions apple/TableProTests/TeamLibrary/TeamLibrarySecretsTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand All @@ -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")
Expand All @@ -132,7 +132,7 @@ struct TeamLibrarySecretsTests {
try await fixture.library.publishConnectionEdit(
original.connection,
of: original,
secrets: nil,
secretChanges: [:],
to: fixture.library.destination(TeamLibraryFixture.team)
)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand All @@ -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)
Expand All @@ -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()
Expand All @@ -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")
Expand All @@ -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")
Expand All @@ -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")
Expand All @@ -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")
Expand Down
1 change: 1 addition & 0 deletions apple/changelog.d/4706.fixed.1.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Saving a Team Library connection whose password field was empty could delete the team's password.
1 change: 1 addition & 0 deletions apple/changelog.d/4706.fixed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Keep Theirs on a Team Library connection conflict could leave the team's password unreadable for everyone.
Loading
Loading