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
56 changes: 45 additions & 11 deletions apple/TablePro/Core/Storage/DialedSecrets.swift
Original file line number Diff line number Diff line change
Expand Up @@ -99,23 +99,57 @@ enum DialedSecrets {
return landed <= storage.library.landingsRead && current.destination == dialed
}

// For a reader that shows a saved connection's secrets, as the editor: the library read back first when a secret of
// the connection or its profiles landed since it was read. What it returns goes to `landed(since:for:storage:)`.
static func readBackLandings(for connectionId: UUID, storage: ConnectionStorage = .shared) -> UInt64 {
guard let stored = storage.loadConnection(id: connectionId) else { return 0 }
// Where a reader that holds a saved connection's secrets past one read, as the editor, read them: the library's
// destination for the connection, the connection and profiles it named, and how many landings there had been.
struct Reading {
let connectionId: UUID
fileprivate let destination: Destination?
fileprivate let owners: [UUID]
fileprivate let sequence: UInt64
}

// For a reader about to show a saved connection's secrets: a secret of the connection or its profiles that landed
// since the library was read is for where the core's file points, so the library is read back first.
static func readLandingsBack(for connectionId: UUID, storage: ConnectionStorage = .shared) {
guard let stored = storage.loadConnection(id: connectionId) else { return }
let library = storage.library
if library.secretLandings.latest(parents(of: stored)) > library.landingsRead {
storage.readCoreWrites()
}
let current = storage.loadConnection(id: connectionId) ?? stored
return library.secretLandings.latest(parents(of: current))
}

// True when a secret of the connection or its profiles landed after `mark`, or one is still unread by the library.
static func landed(since mark: UInt64, for connection: DatabaseConnection, storage: ConnectionStorage = .shared) -> Bool {
// Taken before the secrets are read. A landing the library has not read back fails `holds` until it does.
static func reading(for connectionId: UUID, storage: ConnectionStorage = .shared) -> Reading {
// Counted first: a landing between the count and the library read reads as one after the reading.
let sequence = storage.library.secretLandings.sequence
guard let current = storage.loadConnection(id: connectionId) else {
return Reading(connectionId: connectionId, destination: nil, owners: [], sequence: sequence)
}
return Reading(
connectionId: connectionId,
destination: Destination(SSHProfileStorage(connectionStorage: storage).refreshingLinkedProfile(current)),
owners: parents(of: current),
sequence: sequence
)
}

// True when a secret of the connection, or of a profile it named then or names now, landed after `reading`, or one
// is still unread by the library.
static func landed(since reading: Reading, storage: ConnectionStorage = .shared) -> Bool {
guard let current = storage.loadConnection(id: reading.connectionId) else { return true }
let library = storage.library
let latest = library.secretLandings.latest(parents(of: connection))
return latest != mark || latest > library.landingsRead
let latest = library.secretLandings.latest(reading.owners + parents(of: current))
return latest > reading.sequence || latest > library.landingsRead
}

// Whether a secret read at `reading` still goes where the connection points: the library points it where it did
// then, and nothing of it or its profiles landed since.
static func holds(_ reading: Reading, storage: ConnectionStorage = .shared) -> Bool {
guard let destination = reading.destination,
let current = storage.loadConnection(id: reading.connectionId),
!landed(since: reading, storage: storage)
else { return false }
return Destination(SSHProfileStorage(connectionStorage: storage).refreshingLinkedProfile(current)) == destination
}

// The connection a read is for: the library's copy when it holds one, else the row itself, as Test Connection's
Expand Down Expand Up @@ -177,7 +211,7 @@ enum DialedSecrets {
// profile's own landings stand for its servers and username. Left out: the database a session moved to, which it
// writes into its copy, the settings only this Mac reads, and the published SSH route, which names what a device
// resolved: this Mac dials through its own SSH config and records its own route after the tunnel opens.
private struct Destination: Equatable {
fileprivate struct Destination: Equatable {
let route: ConnectionDestination
let username: String
let tls: [String]
Expand Down
15 changes: 15 additions & 0 deletions apple/TablePro/Views/ConnectionForm/Engine/SecretWritePlan.swift
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,21 @@ extension ConnectionEditorEngine {
}
}

static func setSecretValue(_ item: SecretWritePlan.Item, to value: String, in draft: inout ConnectionDraft) {
switch item {
case .password: draft.credentials.password = value
case .sshPassword: draft.ssh.password = value
case .sshKeyPassphrase: draft.ssh.keyPassphrase = value
case .totpSecret: draft.ssh.totpSecret = value
case .sslClientKeyPassphrase: draft.ssl.clientKeyPassphrase = value
case .cloudflareTokenId: draft.cloudflare.serviceTokenId = value
case .cloudflareTokenSecret: draft.cloudflare.serviceTokenSecret = value
case .cloudSQLServiceAccountKey: draft.cloudSQLProxy.serviceAccountKeyJSON = value
case .socksPassword: draft.socksProxy.password = value
case .pluginField(let fieldId): draft.fieldValues[fieldId] = value
}
}

static func delegatesToProfile(_ item: SecretWritePlan.Item, _ record: DatabaseConnection, _ context: EditorContext) -> Bool {
guard let profileId = record.credentialMode.profileId else { return false }
switch item {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -244,20 +244,25 @@ extension ConnectionEditorStore {
sshProfileSheet = .saveCurrent(sshProfileFromInline())
}

// A profile saved from the inline values is linked at once; a create or an edit only refreshes the list.
// A profile saved from the inline values is linked at once; a create only refreshes the list.
func didSaveSSHProfile(_ profile: SSHProfile) {
let linksSaved: Bool
if case .saveCurrent = sshProfileSheet { linksSaved = true } else { linksSaved = false }
let sheet = sshProfileSheet
sshProfileSheet = nil
refreshContext()
if linksSaved {
switch sheet {
case .saveCurrent:
selectSSHProfile(profile.id)
case .edit:
renewSecretReadings()
case .create, nil:
break
}
}

func didDeleteSSHProfile() {
sshProfileSheet = nil
refreshContext()
renewSecretReadings()
}

// MARK: - Derived values for rows
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,10 @@ extension ConnectionEditorStore {
func load(_ request: Request) {
// A secret a pull landed is for where the core's file points, which the library may not have read yet; read
// first, so the profiles the context lists are the ones the record names.
var landings: UInt64 = 0
var reading: DialedSecrets.Reading?
if case .edit(let id) = request {
landings = DialedSecrets.readBackLandings(for: id, storage: storage)
DialedSecrets.readLandingsBack(for: id, storage: storage)
reading = DialedSecrets.reading(for: id, storage: storage)
}
context = makeContext()
switch request {
Expand Down Expand Up @@ -47,12 +48,25 @@ extension ConnectionEditorStore {
secrets = readSecrets(of: record)
}
// One that landed during the read may belong to another destination than the record shows: none is shown.
if DialedSecrets.landed(since: landings, for: record, storage: storage) {
if let reading, DialedSecrets.landed(since: reading, storage: storage) {
secrets = .none
}
unreadableSecretKeys = reads.unreadable
loadedSecrets = reads.loaded
draft = ConnectionDraft.loaded(from: record, secrets: secrets, traits: traits)
if let reading {
let ssh: [SecretWritePlan.Item] = [.sshPassword, .sshKeyPassphrase, .totpSecret]
// A plain-text copy an unfinished Keychain migration left is part of the record Test dials, and Save
// moves it to the Keychain: no item was read for it.
let plaintext = traits.declaredSecureFieldIds.filter { fieldId in
let copy = record.additionalFields[fieldId] ?? ""
return !copy.isEmpty && secrets.pluginSecureFields[fieldId] == copy
}.map { SecretWritePlan.Item.pluginField($0) }
var linked = false
if case .profile = record.sshTunnelMode { linked = true }
noteSecretsRead(checkedSecretItems.filter { !ssh.contains($0) && !plaintext.contains($0) }, at: reading)
noteSecretsRead(ssh, at: reading, fromConnection: !linked)
}
baseline = draft
loadedRecord = record
baselineEdits = ConnectionEditorEngine.edits(draft, traits, originalTraits: originalTraits, context)
Expand Down Expand Up @@ -103,6 +117,51 @@ extension ConnectionEditorStore {
return secrets
}

// The secrets a connect reads through `DialedSecrets`. The rest have no sealed destination and stay with their
// record wherever it goes (core ADR 0114).
var checkedSecretItems: [SecretWritePlan.Item] {
[.password, .sshPassword, .sshKeyPassphrase, .totpSecret, .sslClientKeyPassphrase]
+ traits.declaredSecureFieldIds.map { .pluginField($0) }
}

func noteSecretsRead(
_ items: [SecretWritePlan.Item],
at reading: DialedSecrets.Reading,
fromConnection: Bool = true
) {
for item in items {
let read = !ConnectionEditorEngine.secretValue(item, in: draft).isEmpty
secretReadings[item] = read ? SecretReading(reading: reading, fromConnection: fromConnection) : nil
}
}

// A field the person changed holds their own value from then on, even when they type the read one again.
func forgetSecretReadings(changedFrom old: ConnectionDraft, to new: ConnectionDraft) {
for item in Array(secretReadings.keys)
where ConnectionEditorEngine.secretValue(item, in: old) != ConnectionEditorEngine.secretValue(item, in: new) {
secretReadings[item] = nil
}
}

// A secret read here reads as missing once the library points its connection elsewhere than it did at the read,
// or one of its secrets landed since, as at connect: the person sees the old settings, and Test dials them over
// the profiles as they stand now. A value the person typed is theirs and goes where the editor points.
func secretsReadingAsMissing() -> Set<SecretWritePlan.Item> {
Set(secretReadings.compactMap { item, read in
DialedSecrets.holds(read.reading, storage: storage) ? nil : item
})
}

// A profile the person edited or deleted in this window moved the connection on their word, so what the form
// shows goes where they pointed it, unless a secret landed in the meantime.
func renewSecretReadings() {
guard !isNew, teamCopy == nil else { return }
let reading = DialedSecrets.reading(for: connectionId, storage: storage)
for (item, read) in secretReadings where !DialedSecrets.landed(since: read.reading, storage: storage) {
secretReadings[item]?.reading = reading
}
}

func makeContext() -> EditorContext {
var context = EditorContext()
context.isNew = isNew
Expand Down Expand Up @@ -191,7 +250,9 @@ extension ConnectionEditorStore {
else { return }
var next = draft
next.credentials.mode = .inline
var reading: DialedSecrets.Reading?
if !isNew, let refreshed = storage.loadConnection(id: connectionId) {
reading = DialedSecrets.reading(for: connectionId, storage: storage)
let reads = storage.recordingSecretReads {
next.credentials.username = refreshed.username
next.credentials.promptsForPassword = refreshed.promptForPassword
Expand All @@ -208,6 +269,9 @@ extension ConnectionEditorStore {
loadedRecord?.takeSignIn(from: refreshed)
}
commit(next)
if let reading {
noteSecretsRead([.password], at: reading)
}
}

// Storage turns a deleted profile's links inline with its secrets: adopt that. A profile never on this Mac stays linked.
Expand All @@ -225,6 +289,7 @@ extension ConnectionEditorStore {
next.ssh.profileId = nil
next.ssh.profileSnapshot = nil
next.ssh.populateFields(from: config, configEntries: context.sshConfigEntries)
let reading = DialedSecrets.reading(for: connectionId, storage: storage)
let reads = storage.recordingSecretReads {
next.ssh.storedPasswordState = storage.sshPasswordState(for: connectionId)
next.ssh.storedKeyPassphraseState = storage.keyPassphraseState(for: connectionId)
Expand All @@ -237,6 +302,7 @@ extension ConnectionEditorStore {
unreadableSecretKeys.formUnion(reads.unreadable)
loadedSecrets.merge(reads.loaded) { _, fresh in fresh }
commit(next)
noteSecretsRead([.sshPassword, .sshKeyPassphrase, .totpSecret], at: reading)
}

// The baseline stays where load put it: moving it would make every untouched field look edited and revert the change.
Expand Down Expand Up @@ -351,3 +417,10 @@ private extension DatabaseConnection {
}
}
}

// A secret a read put in the draft, until the person changes the field.
struct SecretReading {
var reading: DialedSecrets.Reading
// False for an SSH secret read from the linked profile's item, which a switch to Inline carries to the connection's.
let fromConnection: Bool
}
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,13 @@ extension ConnectionEditorStore {
reviewed = record
plan = ConnectionEditorEngine.secretPlan(saving, traits, originalTraits: originalTraits, context)
}
// A value read into the form goes back to no item of the connection's: on every attempt the item holds it, or
// what a pull left there. One read from the linked SSH profile goes to the connection's own items only while
// the library still points where it did at the read.
plan.writes.removeAll { write in
guard let read = secretReadings[write.item] else { return false }
return read.fromConnection || !DialedSecrets.holds(read.reading, storage: storage)
}

let staged = storage.stagingSecretEdits(
for: connectionId,
Expand Down Expand Up @@ -257,6 +264,21 @@ extension ConnectionEditorStore {
}
}

func storedSecret(_ item: SecretWritePlan.Item, for id: UUID) -> String? {
switch item {
case .password: storage.loadPassword(for: id)
case .sshPassword: storage.loadSSHPassword(for: id)
case .sshKeyPassphrase: storage.loadKeyPassphrase(for: id)
case .totpSecret: storage.loadTOTPSecret(for: id)
case .sslClientKeyPassphrase: storage.loadSSLClientKeyPassphrase(for: id)
case .cloudflareTokenId: storage.loadCloudflareTokenId(for: id)
case .cloudflareTokenSecret: storage.loadCloudflareTokenSecret(for: id)
case .cloudSQLServiceAccountKey: storage.loadCloudSQLProxyServiceAccountKey(for: id)
case .socksPassword: storage.loadSOCKSProxyPassword(for: id)
case .pluginField(let fieldId): storage.loadPluginSecureField(fieldId: fieldId, for: id)
}
}

func deleteSecret(_ item: SecretWritePlan.Item, for id: UUID) {
switch item {
case .password: storage.deletePassword(for: id)
Expand Down
Loading